id
stringlengths
25
30
content
stringlengths
14
942k
max_stars_repo_path
stringlengths
49
55
crossvul-cpp_data_good_3547_4
/* * 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. * * Copyright (C) Jonathan Naylor G4KLX (g4klx@g4klx.demon.co.uk) */ #include <linux/errno.h> #include <linux/types.h> #include <linux/socket.h> #include <linux/in.h> #include <linux/kernel.h> #include <linux/timer.h> #include <linux/string.h> #include <linux/sockios.h> #include <linux/net.h> #include <linux/slab.h> #include <net/ax25.h> #include <linux/inet.h> #include <linux/netdevice.h> #include <linux/skbuff.h> #include <net/sock.h> #include <net/tcp_states.h> #include <asm/system.h> #include <linux/fcntl.h> #include <linux/mm.h> #include <linux/interrupt.h> #include <net/rose.h> static int rose_create_facilities(unsigned char *buffer, struct rose_sock *rose); /* * This routine purges all of the queues of frames. */ void rose_clear_queues(struct sock *sk) { skb_queue_purge(&sk->sk_write_queue); skb_queue_purge(&rose_sk(sk)->ack_queue); } /* * This routine purges the input queue of those frames that have been * acknowledged. This replaces the boxes labelled "V(a) <- N(r)" on the * SDL diagram. */ void rose_frames_acked(struct sock *sk, unsigned short nr) { struct sk_buff *skb; struct rose_sock *rose = rose_sk(sk); /* * Remove all the ack-ed frames from the ack queue. */ if (rose->va != nr) { while (skb_peek(&rose->ack_queue) != NULL && rose->va != nr) { skb = skb_dequeue(&rose->ack_queue); kfree_skb(skb); rose->va = (rose->va + 1) % ROSE_MODULUS; } } } void rose_requeue_frames(struct sock *sk) { struct sk_buff *skb, *skb_prev = NULL; /* * Requeue all the un-ack-ed frames on the output queue to be picked * up by rose_kick. This arrangement handles the possibility of an * empty output queue. */ while ((skb = skb_dequeue(&rose_sk(sk)->ack_queue)) != NULL) { if (skb_prev == NULL) skb_queue_head(&sk->sk_write_queue, skb); else skb_append(skb_prev, skb, &sk->sk_write_queue); skb_prev = skb; } } /* * Validate that the value of nr is between va and vs. Return true or * false for testing. */ int rose_validate_nr(struct sock *sk, unsigned short nr) { struct rose_sock *rose = rose_sk(sk); unsigned short vc = rose->va; while (vc != rose->vs) { if (nr == vc) return 1; vc = (vc + 1) % ROSE_MODULUS; } return nr == rose->vs; } /* * This routine is called when the packet layer internally generates a * control frame. */ void rose_write_internal(struct sock *sk, int frametype) { struct rose_sock *rose = rose_sk(sk); struct sk_buff *skb; unsigned char *dptr; unsigned char lci1, lci2; char buffer[100]; int len, faclen = 0; len = AX25_BPQ_HEADER_LEN + AX25_MAX_HEADER_LEN + ROSE_MIN_LEN + 1; switch (frametype) { case ROSE_CALL_REQUEST: len += 1 + ROSE_ADDR_LEN + ROSE_ADDR_LEN; faclen = rose_create_facilities(buffer, rose); len += faclen; break; case ROSE_CALL_ACCEPTED: case ROSE_CLEAR_REQUEST: case ROSE_RESET_REQUEST: len += 2; break; } if ((skb = alloc_skb(len, GFP_ATOMIC)) == NULL) return; /* * Space for AX.25 header and PID. */ skb_reserve(skb, AX25_BPQ_HEADER_LEN + AX25_MAX_HEADER_LEN + 1); dptr = skb_put(skb, skb_tailroom(skb)); lci1 = (rose->lci >> 8) & 0x0F; lci2 = (rose->lci >> 0) & 0xFF; switch (frametype) { case ROSE_CALL_REQUEST: *dptr++ = ROSE_GFI | lci1; *dptr++ = lci2; *dptr++ = frametype; *dptr++ = ROSE_CALL_REQ_ADDR_LEN_VAL; memcpy(dptr, &rose->dest_addr, ROSE_ADDR_LEN); dptr += ROSE_ADDR_LEN; memcpy(dptr, &rose->source_addr, ROSE_ADDR_LEN); dptr += ROSE_ADDR_LEN; memcpy(dptr, buffer, faclen); dptr += faclen; break; case ROSE_CALL_ACCEPTED: *dptr++ = ROSE_GFI | lci1; *dptr++ = lci2; *dptr++ = frametype; *dptr++ = 0x00; /* Address length */ *dptr++ = 0; /* Facilities length */ break; case ROSE_CLEAR_REQUEST: *dptr++ = ROSE_GFI | lci1; *dptr++ = lci2; *dptr++ = frametype; *dptr++ = rose->cause; *dptr++ = rose->diagnostic; break; case ROSE_RESET_REQUEST: *dptr++ = ROSE_GFI | lci1; *dptr++ = lci2; *dptr++ = frametype; *dptr++ = ROSE_DTE_ORIGINATED; *dptr++ = 0; break; case ROSE_RR: case ROSE_RNR: *dptr++ = ROSE_GFI | lci1; *dptr++ = lci2; *dptr = frametype; *dptr++ |= (rose->vr << 5) & 0xE0; break; case ROSE_CLEAR_CONFIRMATION: case ROSE_RESET_CONFIRMATION: *dptr++ = ROSE_GFI | lci1; *dptr++ = lci2; *dptr++ = frametype; break; default: printk(KERN_ERR "ROSE: rose_write_internal - invalid frametype %02X\n", frametype); kfree_skb(skb); return; } rose_transmit_link(skb, rose->neighbour); } int rose_decode(struct sk_buff *skb, int *ns, int *nr, int *q, int *d, int *m) { unsigned char *frame; frame = skb->data; *ns = *nr = *q = *d = *m = 0; switch (frame[2]) { case ROSE_CALL_REQUEST: case ROSE_CALL_ACCEPTED: case ROSE_CLEAR_REQUEST: case ROSE_CLEAR_CONFIRMATION: case ROSE_RESET_REQUEST: case ROSE_RESET_CONFIRMATION: return frame[2]; default: break; } if ((frame[2] & 0x1F) == ROSE_RR || (frame[2] & 0x1F) == ROSE_RNR) { *nr = (frame[2] >> 5) & 0x07; return frame[2] & 0x1F; } if ((frame[2] & 0x01) == ROSE_DATA) { *q = (frame[0] & ROSE_Q_BIT) == ROSE_Q_BIT; *d = (frame[0] & ROSE_D_BIT) == ROSE_D_BIT; *m = (frame[2] & ROSE_M_BIT) == ROSE_M_BIT; *nr = (frame[2] >> 5) & 0x07; *ns = (frame[2] >> 1) & 0x07; return ROSE_DATA; } return ROSE_ILLEGAL; } static int rose_parse_national(unsigned char *p, struct rose_facilities_struct *facilities, int len) { unsigned char *pt; unsigned char l, lg, n = 0; int fac_national_digis_received = 0; do { switch (*p & 0xC0) { case 0x00: if (len < 2) return -1; p += 2; n += 2; len -= 2; break; case 0x40: if (len < 3) return -1; if (*p == FAC_NATIONAL_RAND) facilities->rand = ((p[1] << 8) & 0xFF00) + ((p[2] << 0) & 0x00FF); p += 3; n += 3; len -= 3; break; case 0x80: if (len < 4) return -1; p += 4; n += 4; len -= 4; break; case 0xC0: if (len < 2) return -1; l = p[1]; if (len < 2 + l) return -1; if (*p == FAC_NATIONAL_DEST_DIGI) { if (!fac_national_digis_received) { if (l < AX25_ADDR_LEN) return -1; memcpy(&facilities->source_digis[0], p + 2, AX25_ADDR_LEN); facilities->source_ndigis = 1; } } else if (*p == FAC_NATIONAL_SRC_DIGI) { if (!fac_national_digis_received) { if (l < AX25_ADDR_LEN) return -1; memcpy(&facilities->dest_digis[0], p + 2, AX25_ADDR_LEN); facilities->dest_ndigis = 1; } } else if (*p == FAC_NATIONAL_FAIL_CALL) { if (l < AX25_ADDR_LEN) return -1; memcpy(&facilities->fail_call, p + 2, AX25_ADDR_LEN); } else if (*p == FAC_NATIONAL_FAIL_ADD) { if (l < 1 + ROSE_ADDR_LEN) return -1; memcpy(&facilities->fail_addr, p + 3, ROSE_ADDR_LEN); } else if (*p == FAC_NATIONAL_DIGIS) { if (l % AX25_ADDR_LEN) return -1; fac_national_digis_received = 1; facilities->source_ndigis = 0; facilities->dest_ndigis = 0; for (pt = p + 2, lg = 0 ; lg < l ; pt += AX25_ADDR_LEN, lg += AX25_ADDR_LEN) { if (pt[6] & AX25_HBIT) { if (facilities->dest_ndigis >= ROSE_MAX_DIGIS) return -1; memcpy(&facilities->dest_digis[facilities->dest_ndigis++], pt, AX25_ADDR_LEN); } else { if (facilities->source_ndigis >= ROSE_MAX_DIGIS) return -1; memcpy(&facilities->source_digis[facilities->source_ndigis++], pt, AX25_ADDR_LEN); } } } p += l + 2; n += l + 2; len -= l + 2; break; } } while (*p != 0x00 && len > 0); return n; } static int rose_parse_ccitt(unsigned char *p, struct rose_facilities_struct *facilities, int len) { unsigned char l, n = 0; char callsign[11]; do { switch (*p & 0xC0) { case 0x00: if (len < 2) return -1; p += 2; n += 2; len -= 2; break; case 0x40: if (len < 3) return -1; p += 3; n += 3; len -= 3; break; case 0x80: if (len < 4) return -1; p += 4; n += 4; len -= 4; break; case 0xC0: if (len < 2) return -1; l = p[1]; /* Prevent overflows*/ if (l < 10 || l > 20) return -1; if (*p == FAC_CCITT_DEST_NSAP) { memcpy(&facilities->source_addr, p + 7, ROSE_ADDR_LEN); memcpy(callsign, p + 12, l - 10); callsign[l - 10] = '\0'; asc2ax(&facilities->source_call, callsign); } if (*p == FAC_CCITT_SRC_NSAP) { memcpy(&facilities->dest_addr, p + 7, ROSE_ADDR_LEN); memcpy(callsign, p + 12, l - 10); callsign[l - 10] = '\0'; asc2ax(&facilities->dest_call, callsign); } p += l + 2; n += l + 2; len -= l + 2; break; } } while (*p != 0x00 && len > 0); return n; } int rose_parse_facilities(unsigned char *p, unsigned packet_len, struct rose_facilities_struct *facilities) { int facilities_len, len; facilities_len = *p++; if (facilities_len == 0 || (unsigned)facilities_len > packet_len) return 0; while (facilities_len >= 3 && *p == 0x00) { facilities_len--; p++; switch (*p) { case FAC_NATIONAL: /* National */ len = rose_parse_national(p + 1, facilities, facilities_len - 1); break; case FAC_CCITT: /* CCITT */ len = rose_parse_ccitt(p + 1, facilities, facilities_len - 1); break; default: printk(KERN_DEBUG "ROSE: rose_parse_facilities - unknown facilities family %02X\n", *p); len = 1; break; } if (len < 0) return 0; if (WARN_ON(len >= facilities_len)) return 0; facilities_len -= len + 1; p += len + 1; } return facilities_len == 0; } static int rose_create_facilities(unsigned char *buffer, struct rose_sock *rose) { unsigned char *p = buffer + 1; char *callsign; char buf[11]; int len, nb; /* National Facilities */ if (rose->rand != 0 || rose->source_ndigis == 1 || rose->dest_ndigis == 1) { *p++ = 0x00; *p++ = FAC_NATIONAL; if (rose->rand != 0) { *p++ = FAC_NATIONAL_RAND; *p++ = (rose->rand >> 8) & 0xFF; *p++ = (rose->rand >> 0) & 0xFF; } /* Sent before older facilities */ if ((rose->source_ndigis > 0) || (rose->dest_ndigis > 0)) { int maxdigi = 0; *p++ = FAC_NATIONAL_DIGIS; *p++ = AX25_ADDR_LEN * (rose->source_ndigis + rose->dest_ndigis); for (nb = 0 ; nb < rose->source_ndigis ; nb++) { if (++maxdigi >= ROSE_MAX_DIGIS) break; memcpy(p, &rose->source_digis[nb], AX25_ADDR_LEN); p[6] |= AX25_HBIT; p += AX25_ADDR_LEN; } for (nb = 0 ; nb < rose->dest_ndigis ; nb++) { if (++maxdigi >= ROSE_MAX_DIGIS) break; memcpy(p, &rose->dest_digis[nb], AX25_ADDR_LEN); p[6] &= ~AX25_HBIT; p += AX25_ADDR_LEN; } } /* For compatibility */ if (rose->source_ndigis > 0) { *p++ = FAC_NATIONAL_SRC_DIGI; *p++ = AX25_ADDR_LEN; memcpy(p, &rose->source_digis[0], AX25_ADDR_LEN); p += AX25_ADDR_LEN; } /* For compatibility */ if (rose->dest_ndigis > 0) { *p++ = FAC_NATIONAL_DEST_DIGI; *p++ = AX25_ADDR_LEN; memcpy(p, &rose->dest_digis[0], AX25_ADDR_LEN); p += AX25_ADDR_LEN; } } *p++ = 0x00; *p++ = FAC_CCITT; *p++ = FAC_CCITT_DEST_NSAP; callsign = ax2asc(buf, &rose->dest_call); *p++ = strlen(callsign) + 10; *p++ = (strlen(callsign) + 9) * 2; /* ??? */ *p++ = 0x47; *p++ = 0x00; *p++ = 0x11; *p++ = ROSE_ADDR_LEN * 2; memcpy(p, &rose->dest_addr, ROSE_ADDR_LEN); p += ROSE_ADDR_LEN; memcpy(p, callsign, strlen(callsign)); p += strlen(callsign); *p++ = FAC_CCITT_SRC_NSAP; callsign = ax2asc(buf, &rose->source_call); *p++ = strlen(callsign) + 10; *p++ = (strlen(callsign) + 9) * 2; /* ??? */ *p++ = 0x47; *p++ = 0x00; *p++ = 0x11; *p++ = ROSE_ADDR_LEN * 2; memcpy(p, &rose->source_addr, ROSE_ADDR_LEN); p += ROSE_ADDR_LEN; memcpy(p, callsign, strlen(callsign)); p += strlen(callsign); len = p - buffer; buffer[0] = len - 1; return len; } void rose_disconnect(struct sock *sk, int reason, int cause, int diagnostic) { struct rose_sock *rose = rose_sk(sk); rose_stop_timer(sk); rose_stop_idletimer(sk); rose_clear_queues(sk); rose->lci = 0; rose->state = ROSE_STATE_0; if (cause != -1) rose->cause = cause; if (diagnostic != -1) rose->diagnostic = diagnostic; sk->sk_state = TCP_CLOSE; sk->sk_err = reason; sk->sk_shutdown |= SEND_SHUTDOWN; if (!sock_flag(sk, SOCK_DEAD)) { sk->sk_state_change(sk); sock_set_flag(sk, SOCK_DEAD); } }
./CrossVul/dataset_final_sorted/CWE-20/c/good_3547_4
crossvul-cpp_data_bad_5845_0
/* * algif_hash: User-space interface for hash algorithms * * This file provides the user-space API for hash algorithms. * * Copyright (c) 2010 Herbert Xu <herbert@gondor.apana.org.au> * * 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 <crypto/hash.h> #include <crypto/if_alg.h> #include <linux/init.h> #include <linux/kernel.h> #include <linux/mm.h> #include <linux/module.h> #include <linux/net.h> #include <net/sock.h> struct hash_ctx { struct af_alg_sgl sgl; u8 *result; struct af_alg_completion completion; unsigned int len; bool more; struct ahash_request req; }; static int hash_sendmsg(struct kiocb *unused, struct socket *sock, struct msghdr *msg, size_t ignored) { int limit = ALG_MAX_PAGES * PAGE_SIZE; struct sock *sk = sock->sk; struct alg_sock *ask = alg_sk(sk); struct hash_ctx *ctx = ask->private; unsigned long iovlen; struct iovec *iov; long copied = 0; int err; if (limit > sk->sk_sndbuf) limit = sk->sk_sndbuf; lock_sock(sk); if (!ctx->more) { err = crypto_ahash_init(&ctx->req); if (err) goto unlock; } ctx->more = 0; for (iov = msg->msg_iov, iovlen = msg->msg_iovlen; iovlen > 0; iovlen--, iov++) { unsigned long seglen = iov->iov_len; char __user *from = iov->iov_base; while (seglen) { int len = min_t(unsigned long, seglen, limit); int newlen; newlen = af_alg_make_sg(&ctx->sgl, from, len, 0); if (newlen < 0) { err = copied ? 0 : newlen; goto unlock; } ahash_request_set_crypt(&ctx->req, ctx->sgl.sg, NULL, newlen); err = af_alg_wait_for_completion( crypto_ahash_update(&ctx->req), &ctx->completion); af_alg_free_sg(&ctx->sgl); if (err) goto unlock; seglen -= newlen; from += newlen; copied += newlen; } } err = 0; ctx->more = msg->msg_flags & MSG_MORE; if (!ctx->more) { ahash_request_set_crypt(&ctx->req, NULL, ctx->result, 0); err = af_alg_wait_for_completion(crypto_ahash_final(&ctx->req), &ctx->completion); } unlock: release_sock(sk); return err ?: copied; } static ssize_t hash_sendpage(struct socket *sock, struct page *page, int offset, size_t size, int flags) { struct sock *sk = sock->sk; struct alg_sock *ask = alg_sk(sk); struct hash_ctx *ctx = ask->private; int err; lock_sock(sk); sg_init_table(ctx->sgl.sg, 1); sg_set_page(ctx->sgl.sg, page, size, offset); ahash_request_set_crypt(&ctx->req, ctx->sgl.sg, ctx->result, size); if (!(flags & MSG_MORE)) { if (ctx->more) err = crypto_ahash_finup(&ctx->req); else err = crypto_ahash_digest(&ctx->req); } else { if (!ctx->more) { err = crypto_ahash_init(&ctx->req); if (err) goto unlock; } err = crypto_ahash_update(&ctx->req); } err = af_alg_wait_for_completion(err, &ctx->completion); if (err) goto unlock; ctx->more = flags & MSG_MORE; unlock: release_sock(sk); return err ?: size; } static int hash_recvmsg(struct kiocb *unused, struct socket *sock, struct msghdr *msg, size_t len, int flags) { struct sock *sk = sock->sk; struct alg_sock *ask = alg_sk(sk); struct hash_ctx *ctx = ask->private; unsigned ds = crypto_ahash_digestsize(crypto_ahash_reqtfm(&ctx->req)); int err; if (len > ds) len = ds; else if (len < ds) msg->msg_flags |= MSG_TRUNC; msg->msg_namelen = 0; lock_sock(sk); if (ctx->more) { ctx->more = 0; ahash_request_set_crypt(&ctx->req, NULL, ctx->result, 0); err = af_alg_wait_for_completion(crypto_ahash_final(&ctx->req), &ctx->completion); if (err) goto unlock; } err = memcpy_toiovec(msg->msg_iov, ctx->result, len); unlock: release_sock(sk); return err ?: len; } static int hash_accept(struct socket *sock, struct socket *newsock, int flags) { struct sock *sk = sock->sk; struct alg_sock *ask = alg_sk(sk); struct hash_ctx *ctx = ask->private; struct ahash_request *req = &ctx->req; char state[crypto_ahash_statesize(crypto_ahash_reqtfm(req))]; struct sock *sk2; struct alg_sock *ask2; struct hash_ctx *ctx2; int err; err = crypto_ahash_export(req, state); if (err) return err; err = af_alg_accept(ask->parent, newsock); if (err) return err; sk2 = newsock->sk; ask2 = alg_sk(sk2); ctx2 = ask2->private; ctx2->more = 1; err = crypto_ahash_import(&ctx2->req, state); if (err) { sock_orphan(sk2); sock_put(sk2); } return err; } static struct proto_ops algif_hash_ops = { .family = PF_ALG, .connect = sock_no_connect, .socketpair = sock_no_socketpair, .getname = sock_no_getname, .ioctl = sock_no_ioctl, .listen = sock_no_listen, .shutdown = sock_no_shutdown, .getsockopt = sock_no_getsockopt, .mmap = sock_no_mmap, .bind = sock_no_bind, .setsockopt = sock_no_setsockopt, .poll = sock_no_poll, .release = af_alg_release, .sendmsg = hash_sendmsg, .sendpage = hash_sendpage, .recvmsg = hash_recvmsg, .accept = hash_accept, }; static void *hash_bind(const char *name, u32 type, u32 mask) { return crypto_alloc_ahash(name, type, mask); } static void hash_release(void *private) { crypto_free_ahash(private); } static int hash_setkey(void *private, const u8 *key, unsigned int keylen) { return crypto_ahash_setkey(private, key, keylen); } static void hash_sock_destruct(struct sock *sk) { struct alg_sock *ask = alg_sk(sk); struct hash_ctx *ctx = ask->private; sock_kfree_s(sk, ctx->result, crypto_ahash_digestsize(crypto_ahash_reqtfm(&ctx->req))); sock_kfree_s(sk, ctx, ctx->len); af_alg_release_parent(sk); } static int hash_accept_parent(void *private, struct sock *sk) { struct hash_ctx *ctx; struct alg_sock *ask = alg_sk(sk); unsigned len = sizeof(*ctx) + crypto_ahash_reqsize(private); unsigned ds = crypto_ahash_digestsize(private); ctx = sock_kmalloc(sk, len, GFP_KERNEL); if (!ctx) return -ENOMEM; ctx->result = sock_kmalloc(sk, ds, GFP_KERNEL); if (!ctx->result) { sock_kfree_s(sk, ctx, len); return -ENOMEM; } memset(ctx->result, 0, ds); ctx->len = len; ctx->more = 0; af_alg_init_completion(&ctx->completion); ask->private = ctx; ahash_request_set_tfm(&ctx->req, private); ahash_request_set_callback(&ctx->req, CRYPTO_TFM_REQ_MAY_BACKLOG, af_alg_complete, &ctx->completion); sk->sk_destruct = hash_sock_destruct; return 0; } static const struct af_alg_type algif_type_hash = { .bind = hash_bind, .release = hash_release, .setkey = hash_setkey, .accept = hash_accept_parent, .ops = &algif_hash_ops, .name = "hash", .owner = THIS_MODULE }; static int __init algif_hash_init(void) { return af_alg_register_type(&algif_type_hash); } static void __exit algif_hash_exit(void) { int err = af_alg_unregister_type(&algif_type_hash); BUG_ON(err); } module_init(algif_hash_init); module_exit(algif_hash_exit); MODULE_LICENSE("GPL");
./CrossVul/dataset_final_sorted/CWE-20/c/bad_5845_0
crossvul-cpp_data_good_4716_2
/* * verify.c: * * Author: * Mono Project (http://www.mono-project.com) * * Copyright 2001-2003 Ximian, Inc (http://www.ximian.com) * Copyright 2004-2009 Novell, Inc (http://www.novell.com) */ #include <config.h> #include <mono/metadata/object-internals.h> #include <mono/metadata/verify.h> #include <mono/metadata/verify-internals.h> #include <mono/metadata/opcodes.h> #include <mono/metadata/tabledefs.h> #include <mono/metadata/reflection.h> #include <mono/metadata/debug-helpers.h> #include <mono/metadata/mono-endian.h> #include <mono/metadata/metadata.h> #include <mono/metadata/metadata-internals.h> #include <mono/metadata/class-internals.h> #include <mono/metadata/security-manager.h> #include <mono/metadata/security-core-clr.h> #include <mono/metadata/tokentype.h> #include <mono/metadata/mono-basic-block.h> #include <mono/utils/monobitset.h> #include <string.h> #include <signal.h> #include <ctype.h> static MiniVerifierMode verifier_mode = MONO_VERIFIER_MODE_OFF; static gboolean verify_all = FALSE; /* * Set the desired level of checks for the verfier. * */ void mono_verifier_set_mode (MiniVerifierMode mode) { verifier_mode = mode; } void mono_verifier_enable_verify_all () { verify_all = TRUE; } #ifndef DISABLE_VERIFIER /* * Pull the list of opcodes */ #define OPDEF(a,b,c,d,e,f,g,h,i,j) \ a = i, enum { #include "mono/cil/opcode.def" LAST = 0xff }; #undef OPDEF #ifdef MONO_VERIFIER_DEBUG #define VERIFIER_DEBUG(code) do { code } while (0) #else #define VERIFIER_DEBUG(code) #endif ////////////////////////////////////////////////////////////////// #define IS_STRICT_MODE(ctx) (((ctx)->level & MONO_VERIFY_NON_STRICT) == 0) #define IS_FAIL_FAST_MODE(ctx) (((ctx)->level & MONO_VERIFY_FAIL_FAST) == MONO_VERIFY_FAIL_FAST) #define IS_SKIP_VISIBILITY(ctx) (((ctx)->level & MONO_VERIFY_SKIP_VISIBILITY) == MONO_VERIFY_SKIP_VISIBILITY) #define IS_REPORT_ALL_ERRORS(ctx) (((ctx)->level & MONO_VERIFY_REPORT_ALL_ERRORS) == MONO_VERIFY_REPORT_ALL_ERRORS) #define CLEAR_PREFIX(ctx, prefix) do { (ctx)->prefix_set &= ~(prefix); } while (0) #define ADD_VERIFY_INFO(__ctx, __msg, __status, __exception) \ do { \ MonoVerifyInfoExtended *vinfo = g_new (MonoVerifyInfoExtended, 1); \ vinfo->info.status = __status; \ vinfo->info.message = ( __msg ); \ vinfo->exception_type = (__exception); \ (__ctx)->list = g_slist_prepend ((__ctx)->list, vinfo); \ } while (0) //TODO support MONO_VERIFY_REPORT_ALL_ERRORS #define ADD_VERIFY_ERROR(__ctx, __msg) \ do { \ ADD_VERIFY_INFO(__ctx, __msg, MONO_VERIFY_ERROR, MONO_EXCEPTION_INVALID_PROGRAM); \ (__ctx)->valid = 0; \ } while (0) #define CODE_NOT_VERIFIABLE(__ctx, __msg) \ do { \ if ((__ctx)->verifiable || IS_REPORT_ALL_ERRORS (__ctx)) { \ ADD_VERIFY_INFO(__ctx, __msg, MONO_VERIFY_NOT_VERIFIABLE, MONO_EXCEPTION_UNVERIFIABLE_IL); \ (__ctx)->verifiable = 0; \ if (IS_FAIL_FAST_MODE (__ctx)) \ (__ctx)->valid = 0; \ } \ } while (0) #define ADD_VERIFY_ERROR2(__ctx, __msg, __exception) \ do { \ ADD_VERIFY_INFO(__ctx, __msg, MONO_VERIFY_ERROR, __exception); \ (__ctx)->valid = 0; \ } while (0) #define CODE_NOT_VERIFIABLE2(__ctx, __msg, __exception) \ do { \ if ((__ctx)->verifiable || IS_REPORT_ALL_ERRORS (__ctx)) { \ ADD_VERIFY_INFO(__ctx, __msg, MONO_VERIFY_NOT_VERIFIABLE, __exception); \ (__ctx)->verifiable = 0; \ if (IS_FAIL_FAST_MODE (__ctx)) \ (__ctx)->valid = 0; \ } \ } while (0) #define CHECK_ADD4_OVERFLOW_UN(a, b) ((guint32)(0xFFFFFFFFU) - (guint32)(b) < (guint32)(a)) #define CHECK_ADD8_OVERFLOW_UN(a, b) ((guint64)(0xFFFFFFFFFFFFFFFFUL) - (guint64)(b) < (guint64)(a)) #if SIZEOF_VOID_P == 4 #define CHECK_ADDP_OVERFLOW_UN(a,b) CHECK_ADD4_OVERFLOW_UN(a, b) #else #define CHECK_ADDP_OVERFLOW_UN(a,b) CHECK_ADD8_OVERFLOW_UN(a, b) #endif #define ADDP_IS_GREATER_OR_OVF(a, b, c) (((a) + (b) > (c)) || CHECK_ADDP_OVERFLOW_UN (a, b)) #define ADD_IS_GREATER_OR_OVF(a, b, c) (((a) + (b) > (c)) || CHECK_ADD4_OVERFLOW_UN (a, b)) /*Flags to be used with ILCodeDesc::flags */ enum { /*Instruction has not been processed.*/ IL_CODE_FLAG_NOT_PROCESSED = 0, /*Instruction was decoded by mono_method_verify loop.*/ IL_CODE_FLAG_SEEN = 1, /*Instruction was target of a branch or is at a protected block boundary.*/ IL_CODE_FLAG_WAS_TARGET = 2, /*Used by stack_init to avoid double initialize each entry.*/ IL_CODE_FLAG_STACK_INITED = 4, /*Used by merge_stacks to decide if it should just copy the eval stack.*/ IL_CODE_STACK_MERGED = 8, /*This instruction is part of the delegate construction sequence, it cannot be target of a branch.*/ IL_CODE_DELEGATE_SEQUENCE = 0x10, /*This is a delegate created from a ldftn to a non final virtual method*/ IL_CODE_LDFTN_DELEGATE_NONFINAL_VIRTUAL = 0x20, /*This is a call to a non final virtual method*/ IL_CODE_CALL_NONFINAL_VIRTUAL = 0x40, }; typedef enum { RESULT_VALID, RESULT_UNVERIFIABLE, RESULT_INVALID } verify_result_t; typedef struct { MonoType *type; int stype; MonoMethod *method; } ILStackDesc; typedef struct { ILStackDesc *stack; guint16 size; guint16 flags; } ILCodeDesc; typedef struct { int max_args; int max_stack; int verifiable; int valid; int level; int code_size; ILCodeDesc *code; ILCodeDesc eval; MonoType **params; GSList *list; /*Allocated fnptr MonoType that should be freed by us.*/ GSList *funptrs; /*Type dup'ed exception types from catch blocks.*/ GSList *exception_types; int num_locals; MonoType **locals; /*TODO get rid of target here, need_merge in mono_method_verify and hoist the merging code in the branching code*/ int target; guint32 ip_offset; MonoMethodSignature *signature; MonoMethodHeader *header; MonoGenericContext *generic_context; MonoImage *image; MonoMethod *method; /*This flag helps solving a corner case of delegate verification in that you cannot have a "starg 0" *on a method that creates a delegate for a non-final virtual method using ldftn*/ gboolean has_this_store; /*This flag is used to control if the contructor of the parent class has been called. *If the this pointer is pushed on the eval stack and it's a reference type constructor and * super_ctor_called is false, the uninitialized flag is set on the pushed value. * * Poping an uninitialized this ptr from the eval stack is an unverifiable operation unless * the safe variant is used. Only a few opcodes can use it : dup, pop, ldfld, stfld and call to a constructor. */ gboolean super_ctor_called; guint32 prefix_set; gboolean has_flags; MonoType *constrained_type; } VerifyContext; static void merge_stacks (VerifyContext *ctx, ILCodeDesc *from, ILCodeDesc *to, gboolean start, gboolean external); static int get_stack_type (MonoType *type); static gboolean mono_delegate_signature_equal (MonoMethodSignature *delegate_sig, MonoMethodSignature *method_sig, gboolean is_static_ldftn); static gboolean mono_class_is_valid_generic_instantiation (VerifyContext *ctx, MonoClass *klass); static gboolean mono_method_is_valid_generic_instantiation (VerifyContext *ctx, MonoMethod *method); ////////////////////////////////////////////////////////////////// enum { TYPE_INV = 0, /* leave at 0. */ TYPE_I4 = 1, TYPE_I8 = 2, TYPE_NATIVE_INT = 3, TYPE_R8 = 4, /* Used by operator tables to resolve pointer types (managed & unmanaged) and by unmanaged pointer types*/ TYPE_PTR = 5, /* value types and classes */ TYPE_COMPLEX = 6, /* Number of types, used to define the size of the tables*/ TYPE_MAX = 6, /* Used by tables to signal that a result is not verifiable*/ NON_VERIFIABLE_RESULT = 0x80, /*Mask used to extract just the type, excluding flags */ TYPE_MASK = 0x0F, /* The stack type is a managed pointer, unmask the value to res */ POINTER_MASK = 0x100, /*Stack type with the pointer mask*/ RAW_TYPE_MASK = 0x10F, /* Controlled Mutability Manager Pointer */ CMMP_MASK = 0x200, /* The stack type is a null literal*/ NULL_LITERAL_MASK = 0x400, /**Used by ldarg.0 and family to let delegate verification happens.*/ THIS_POINTER_MASK = 0x800, /**Signals that this is a boxed value type*/ BOXED_MASK = 0x1000, /*This is an unitialized this ref*/ UNINIT_THIS_MASK = 0x2000, }; static const char* const type_names [TYPE_MAX + 1] = { "Invalid", "Int32", "Int64", "Native Int", "Float64", "Native Pointer", "Complex" }; enum { PREFIX_UNALIGNED = 1, PREFIX_VOLATILE = 2, PREFIX_TAIL = 4, PREFIX_CONSTRAINED = 8, PREFIX_READONLY = 16 }; ////////////////////////////////////////////////////////////////// /*Token validation macros and functions */ #define IS_MEMBER_REF(token) (mono_metadata_token_table (token) == MONO_TABLE_MEMBERREF) #define IS_METHOD_DEF(token) (mono_metadata_token_table (token) == MONO_TABLE_METHOD) #define IS_METHOD_SPEC(token) (mono_metadata_token_table (token) == MONO_TABLE_METHODSPEC) #define IS_FIELD_DEF(token) (mono_metadata_token_table (token) == MONO_TABLE_FIELD) #define IS_TYPE_REF(token) (mono_metadata_token_table (token) == MONO_TABLE_TYPEREF) #define IS_TYPE_DEF(token) (mono_metadata_token_table (token) == MONO_TABLE_TYPEDEF) #define IS_TYPE_SPEC(token) (mono_metadata_token_table (token) == MONO_TABLE_TYPESPEC) #define IS_METHOD_DEF_OR_REF_OR_SPEC(token) (IS_METHOD_DEF (token) || IS_MEMBER_REF (token) || IS_METHOD_SPEC (token)) #define IS_TYPE_DEF_OR_REF_OR_SPEC(token) (IS_TYPE_DEF (token) || IS_TYPE_REF (token) || IS_TYPE_SPEC (token)) #define IS_FIELD_DEF_OR_REF(token) (IS_FIELD_DEF (token) || IS_MEMBER_REF (token)) /* * Verify if @token refers to a valid row on int's table. */ static gboolean token_bounds_check (MonoImage *image, guint32 token) { if (image->dynamic) return mono_reflection_is_valid_dynamic_token ((MonoDynamicImage*)image, token); return image->tables [mono_metadata_token_table (token)].rows >= mono_metadata_token_index (token); } static MonoType * mono_type_create_fnptr_from_mono_method (VerifyContext *ctx, MonoMethod *method) { MonoType *res = g_new0 (MonoType, 1); //FIXME use mono_method_get_signature_full res->data.method = mono_method_signature (method); res->type = MONO_TYPE_FNPTR; ctx->funptrs = g_slist_prepend (ctx->funptrs, res); return res; } /* * mono_type_is_enum_type: * * Returns TRUE if @type is an enum type. */ static gboolean mono_type_is_enum_type (MonoType *type) { if (type->type == MONO_TYPE_VALUETYPE && type->data.klass->enumtype) return TRUE; if (type->type == MONO_TYPE_GENERICINST && type->data.generic_class->container_class->enumtype) return TRUE; return FALSE; } /* * mono_type_is_value_type: * * Returns TRUE if @type is named after @namespace.@name. * */ static gboolean mono_type_is_value_type (MonoType *type, const char *namespace, const char *name) { return type->type == MONO_TYPE_VALUETYPE && !strcmp (namespace, type->data.klass->name_space) && !strcmp (name, type->data.klass->name); } /* * Returns TURE if @type is VAR or MVAR */ static gboolean mono_type_is_generic_argument (MonoType *type) { return type->type == MONO_TYPE_VAR || type->type == MONO_TYPE_MVAR; } /* * mono_type_get_underlying_type_any: * * This functions is just like mono_type_get_underlying_type but it doesn't care if the type is byref. * * Returns the underlying type of @type regardless if it is byref or not. */ static MonoType* mono_type_get_underlying_type_any (MonoType *type) { if (type->type == MONO_TYPE_VALUETYPE && type->data.klass->enumtype) return mono_class_enum_basetype (type->data.klass); if (type->type == MONO_TYPE_GENERICINST && type->data.generic_class->container_class->enumtype) return mono_class_enum_basetype (type->data.generic_class->container_class); return type; } static const char* mono_type_get_stack_name (MonoType *type) { return type_names [get_stack_type (type) & TYPE_MASK]; } #define CTOR_REQUIRED_FLAGS (METHOD_ATTRIBUTE_SPECIAL_NAME | METHOD_ATTRIBUTE_RT_SPECIAL_NAME) #define CTOR_INVALID_FLAGS (METHOD_ATTRIBUTE_STATIC) static gboolean mono_method_is_constructor (MonoMethod *method) { return ((method->flags & CTOR_REQUIRED_FLAGS) == CTOR_REQUIRED_FLAGS && !(method->flags & CTOR_INVALID_FLAGS) && !strcmp (".ctor", method->name)); } static gboolean mono_class_has_default_constructor (MonoClass *klass) { MonoMethod *method; int i; mono_class_setup_methods (klass); if (klass->exception_type) return FALSE; for (i = 0; i < klass->method.count; ++i) { method = klass->methods [i]; if (mono_method_is_constructor (method) && mono_method_signature (method) && mono_method_signature (method)->param_count == 0 && (method->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) == METHOD_ATTRIBUTE_PUBLIC) return TRUE; } return FALSE; } static gboolean mono_class_interface_implements_interface (MonoClass *candidate, MonoClass *iface) { MonoError error; int i; do { if (candidate == iface) return TRUE; mono_class_setup_interfaces (candidate, &error); if (!mono_error_ok (&error)) { mono_error_cleanup (&error); return FALSE; } for (i = 0; i < candidate->interface_count; ++i) { if (candidate->interfaces [i] == iface || mono_class_interface_implements_interface (candidate->interfaces [i], iface)) return TRUE; } candidate = candidate->parent; } while (candidate); return FALSE; } /* * Verify if @type is valid for the given @ctx verification context. * this function checks for VAR and MVAR types that are invalid under the current verifier, */ static gboolean mono_type_is_valid_type_in_context (MonoType *type, MonoGenericContext *context) { int i; MonoGenericInst *inst; switch (type->type) { case MONO_TYPE_VAR: case MONO_TYPE_MVAR: if (!context) return FALSE; inst = type->type == MONO_TYPE_VAR ? context->class_inst : context->method_inst; if (!inst || mono_type_get_generic_param_num (type) >= inst->type_argc) return FALSE; break; case MONO_TYPE_SZARRAY: return mono_type_is_valid_type_in_context (&type->data.klass->byval_arg, context); case MONO_TYPE_ARRAY: return mono_type_is_valid_type_in_context (&type->data.array->eklass->byval_arg, context); case MONO_TYPE_PTR: return mono_type_is_valid_type_in_context (type->data.type, context); case MONO_TYPE_GENERICINST: inst = type->data.generic_class->context.class_inst; if (!inst->is_open) break; for (i = 0; i < inst->type_argc; ++i) if (!mono_type_is_valid_type_in_context (inst->type_argv [i], context)) return FALSE; break; case MONO_TYPE_CLASS: case MONO_TYPE_VALUETYPE: { MonoClass *klass = type->data.klass; /* * It's possible to encode generic'sh types in such a way that they disguise themselves as class or valuetype. * Fixing the type decoding is really tricky since under some cases this behavior is needed, for example, to * have a 'class' type pointing to a 'genericinst' class. * * For the runtime these non canonical (weird) encodings work fine, they worst they can cause is some * reflection oddities which are harmless - to security at least. */ if (klass->byval_arg.type != type->type) return mono_type_is_valid_type_in_context (&klass->byval_arg, context); break; } } return TRUE; } /*This function returns NULL if the type is not instantiatable*/ static MonoType* verifier_inflate_type (VerifyContext *ctx, MonoType *type, MonoGenericContext *context) { MonoError error; MonoType *result; result = mono_class_inflate_generic_type_checked (type, context, &error); if (!mono_error_ok (&error)) { mono_error_cleanup (&error); return NULL; } return result; } /* * Test if @candidate is a subtype of @target using the minimal possible information * TODO move the code for non finished TypeBuilders to here. */ static gboolean mono_class_is_constraint_compatible (MonoClass *candidate, MonoClass *target) { if (candidate == target) return TRUE; if (target == mono_defaults.object_class) return TRUE; //setup_supertypes don't mono_class_init anything mono_class_setup_supertypes (candidate); mono_class_setup_supertypes (target); if (mono_class_has_parent (candidate, target)) return TRUE; //if target is not a supertype it must be an interface if (!MONO_CLASS_IS_INTERFACE (target)) return FALSE; if (candidate->image->dynamic && !candidate->wastypebuilder) { MonoReflectionTypeBuilder *tb = candidate->reflection_info; int j; if (tb->interfaces) { for (j = mono_array_length (tb->interfaces) - 1; j >= 0; --j) { MonoReflectionType *iface = mono_array_get (tb->interfaces, MonoReflectionType*, j); MonoClass *ifaceClass = mono_class_from_mono_type (iface->type); if (mono_class_is_constraint_compatible (ifaceClass, target)) { return TRUE; } } } return FALSE; } return mono_class_interface_implements_interface (candidate, target); } static gboolean is_valid_generic_instantiation (MonoGenericContainer *gc, MonoGenericContext *context, MonoGenericInst *ginst) { MonoError error; int i; if (ginst->type_argc != gc->type_argc) return FALSE; for (i = 0; i < gc->type_argc; ++i) { MonoGenericParamInfo *param_info = mono_generic_container_get_param_info (gc, i); MonoClass *paramClass; MonoClass **constraints; if (!param_info->constraints && !(param_info->flags & GENERIC_PARAMETER_ATTRIBUTE_SPECIAL_CONSTRAINTS_MASK)) continue; if (mono_type_is_generic_argument (ginst->type_argv [i])) continue; //it's not our job to validate type variables paramClass = mono_class_from_mono_type (ginst->type_argv [i]); if (paramClass->exception_type != MONO_EXCEPTION_NONE) return FALSE; /*it's not safe to call mono_class_init from here*/ if (paramClass->generic_class && !paramClass->inited) { if (!mono_class_is_valid_generic_instantiation (NULL, paramClass)) return FALSE; } if ((param_info->flags & GENERIC_PARAMETER_ATTRIBUTE_VALUE_TYPE_CONSTRAINT) && (!paramClass->valuetype || mono_class_is_nullable (paramClass))) return FALSE; if ((param_info->flags & GENERIC_PARAMETER_ATTRIBUTE_REFERENCE_TYPE_CONSTRAINT) && paramClass->valuetype) return FALSE; if ((param_info->flags & GENERIC_PARAMETER_ATTRIBUTE_CONSTRUCTOR_CONSTRAINT) && !paramClass->valuetype && !mono_class_has_default_constructor (paramClass)) return FALSE; if (!param_info->constraints) continue; for (constraints = param_info->constraints; *constraints; ++constraints) { MonoClass *ctr = *constraints; MonoType *inflated; inflated = mono_class_inflate_generic_type_checked (&ctr->byval_arg, context, &error); if (!mono_error_ok (&error)) { mono_error_cleanup (&error); return FALSE; } ctr = mono_class_from_mono_type (inflated); mono_metadata_free_type (inflated); if (!mono_class_is_constraint_compatible (paramClass, ctr)) return FALSE; } } return TRUE; } /* * Return true if @candidate is constraint compatible with @target. * * This means that @candidate constraints are a super set of @target constaints */ static gboolean mono_generic_param_is_constraint_compatible (VerifyContext *ctx, MonoGenericParam *target, MonoGenericParam *candidate, MonoClass *candidate_param_class, MonoGenericContext *context) { MonoGenericParamInfo *tinfo = mono_generic_param_info (target); MonoGenericParamInfo *cinfo = mono_generic_param_info (candidate); int tmask = tinfo->flags & GENERIC_PARAMETER_ATTRIBUTE_SPECIAL_CONSTRAINTS_MASK; int cmask = cinfo->flags & GENERIC_PARAMETER_ATTRIBUTE_SPECIAL_CONSTRAINTS_MASK; if ((tmask & cmask) != tmask) return FALSE; if (tinfo->constraints) { MonoClass **target_class, **candidate_class; for (target_class = tinfo->constraints; *target_class; ++target_class) { MonoClass *tc; MonoType *inflated = verifier_inflate_type (ctx, &(*target_class)->byval_arg, context); if (!inflated) return FALSE; tc = mono_class_from_mono_type (inflated); mono_metadata_free_type (inflated); /* * A constraint from @target might inflate into @candidate itself and in that case we don't need * check it's constraints since it satisfy the constraint by itself. */ if (mono_metadata_type_equal (&tc->byval_arg, &candidate_param_class->byval_arg)) continue; if (!cinfo->constraints) return FALSE; for (candidate_class = cinfo->constraints; *candidate_class; ++candidate_class) { MonoClass *cc; inflated = verifier_inflate_type (ctx, &(*candidate_class)->byval_arg, ctx->generic_context); if (!inflated) return FALSE; cc = mono_class_from_mono_type (inflated); mono_metadata_free_type (inflated); if (mono_class_is_assignable_from (tc, cc)) break; } if (!*candidate_class) return FALSE; } } return TRUE; } static MonoGenericParam* verifier_get_generic_param_from_type (VerifyContext *ctx, MonoType *type) { MonoGenericContainer *gc; MonoMethod *method = ctx->method; int num; num = mono_type_get_generic_param_num (type); if (type->type == MONO_TYPE_VAR) { MonoClass *gtd = method->klass; if (gtd->generic_class) gtd = gtd->generic_class->container_class; gc = gtd->generic_container; } else { //MVAR MonoMethod *gmd = method; if (method->is_inflated) gmd = ((MonoMethodInflated*)method)->declaring; gc = mono_method_get_generic_container (gmd); } if (!gc) return FALSE; return mono_generic_container_get_param (gc, num); } /* * Verify if @type is valid for the given @ctx verification context. * this function checks for VAR and MVAR types that are invalid under the current verifier, * This means that it either */ static gboolean is_valid_type_in_context (VerifyContext *ctx, MonoType *type) { return mono_type_is_valid_type_in_context (type, ctx->generic_context); } static gboolean is_valid_generic_instantiation_in_context (VerifyContext *ctx, MonoGenericInst *ginst) { int i; for (i = 0; i < ginst->type_argc; ++i) { MonoType *type = ginst->type_argv [i]; if (!is_valid_type_in_context (ctx, type)) return FALSE; } return TRUE; } static gboolean generic_arguments_respect_constraints (VerifyContext *ctx, MonoGenericContainer *gc, MonoGenericContext *context, MonoGenericInst *ginst) { int i; for (i = 0; i < ginst->type_argc; ++i) { MonoType *type = ginst->type_argv [i]; MonoGenericParam *target = mono_generic_container_get_param (gc, i); MonoGenericParam *candidate; MonoClass *candidate_class; if (!mono_type_is_generic_argument (type)) continue; if (!is_valid_type_in_context (ctx, type)) return FALSE; candidate = verifier_get_generic_param_from_type (ctx, type); candidate_class = mono_class_from_mono_type (type); if (!mono_generic_param_is_constraint_compatible (ctx, target, candidate, candidate_class, context)) return FALSE; } return TRUE; } static gboolean mono_method_repect_method_constraints (VerifyContext *ctx, MonoMethod *method) { MonoMethodInflated *gmethod = (MonoMethodInflated *)method; MonoGenericInst *ginst = gmethod->context.method_inst; MonoGenericContainer *gc = mono_method_get_generic_container (gmethod->declaring); return !gc || generic_arguments_respect_constraints (ctx, gc, &gmethod->context, ginst); } static gboolean mono_class_repect_method_constraints (VerifyContext *ctx, MonoClass *klass) { MonoGenericClass *gklass = klass->generic_class; MonoGenericInst *ginst = gklass->context.class_inst; MonoGenericContainer *gc = gklass->container_class->generic_container; return !gc || generic_arguments_respect_constraints (ctx, gc, &gklass->context, ginst); } static gboolean mono_method_is_valid_generic_instantiation (VerifyContext *ctx, MonoMethod *method) { MonoMethodInflated *gmethod = (MonoMethodInflated *)method; MonoGenericInst *ginst = gmethod->context.method_inst; MonoGenericContainer *gc = mono_method_get_generic_container (gmethod->declaring); if (!gc) /*non-generic inflated method - it's part of a generic type */ return TRUE; if (ctx && !is_valid_generic_instantiation_in_context (ctx, ginst)) return FALSE; return is_valid_generic_instantiation (gc, &gmethod->context, ginst); } static gboolean mono_class_is_valid_generic_instantiation (VerifyContext *ctx, MonoClass *klass) { MonoGenericClass *gklass = klass->generic_class; MonoGenericInst *ginst = gklass->context.class_inst; MonoGenericContainer *gc = gklass->container_class->generic_container; if (ctx && !is_valid_generic_instantiation_in_context (ctx, ginst)) return FALSE; return is_valid_generic_instantiation (gc, &gklass->context, ginst); } static gboolean mono_type_is_valid_in_context (VerifyContext *ctx, MonoType *type) { MonoClass *klass; if (type == NULL) { ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid null type at 0x%04x", ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE); return FALSE; } if (!is_valid_type_in_context (ctx, type)) { char *str = mono_type_full_name (type); ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid generic type (%s%s) (argument out of range or %s is not generic) at 0x%04x", type->type == MONO_TYPE_VAR ? "!" : "!!", str, type->type == MONO_TYPE_VAR ? "class" : "method", ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE); g_free (str); return FALSE; } klass = mono_class_from_mono_type (type); mono_class_init (klass); if (mono_loader_get_last_error () || klass->exception_type != MONO_EXCEPTION_NONE) { if (klass->generic_class && !mono_class_is_valid_generic_instantiation (NULL, klass)) ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid generic instantiation of type %s.%s at 0x%04x", klass->name_space, klass->name, ctx->ip_offset), MONO_EXCEPTION_TYPE_LOAD); else ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Could not load type %s.%s at 0x%04x", klass->name_space, klass->name, ctx->ip_offset), MONO_EXCEPTION_TYPE_LOAD); return FALSE; } if (klass->generic_class && klass->generic_class->container_class->exception_type != MONO_EXCEPTION_NONE) { ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Could not load type %s.%s at 0x%04x", klass->name_space, klass->name, ctx->ip_offset), MONO_EXCEPTION_TYPE_LOAD); return FALSE; } if (!klass->generic_class) return TRUE; if (!mono_class_is_valid_generic_instantiation (ctx, klass)) { ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid generic type instantiation of type %s.%s at 0x%04x", klass->name_space, klass->name, ctx->ip_offset), MONO_EXCEPTION_TYPE_LOAD); return FALSE; } if (!mono_class_repect_method_constraints (ctx, klass)) { ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid generic type instantiation of type %s.%s (generic args don't respect target's constraints) at 0x%04x", klass->name_space, klass->name, ctx->ip_offset), MONO_EXCEPTION_TYPE_LOAD); return FALSE; } return TRUE; } static verify_result_t mono_method_is_valid_in_context (VerifyContext *ctx, MonoMethod *method) { if (!mono_type_is_valid_in_context (ctx, &method->klass->byval_arg)) return RESULT_INVALID; if (!method->is_inflated) return RESULT_VALID; if (!mono_method_is_valid_generic_instantiation (ctx, method)) { ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid generic method instantiation of method %s.%s::%s at 0x%04x", method->klass->name_space, method->klass->name, method->name, ctx->ip_offset), MONO_EXCEPTION_UNVERIFIABLE_IL); return RESULT_INVALID; } if (!mono_method_repect_method_constraints (ctx, method)) { CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid generic method instantiation of method %s.%s::%s (generic args don't respect target's constraints) at 0x%04x", method->klass->name_space, method->klass->name, method->name, ctx->ip_offset)); return RESULT_UNVERIFIABLE; } return RESULT_VALID; } static MonoClassField* verifier_load_field (VerifyContext *ctx, int token, MonoClass **out_klass, const char *opcode) { MonoClassField *field; MonoClass *klass = NULL; if (!IS_FIELD_DEF_OR_REF (token) || !token_bounds_check (ctx->image, token)) { ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid field token 0x%08x for %s at 0x%04x", token, opcode, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE); return NULL; } field = mono_field_from_token (ctx->image, token, &klass, ctx->generic_context); if (!field || !field->parent || !klass) { ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Cannot load field from token 0x%08x for %s at 0x%04x", token, opcode, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE); return NULL; } if (!mono_type_is_valid_in_context (ctx, &klass->byval_arg)) return NULL; *out_klass = klass; return field; } static MonoMethod* verifier_load_method (VerifyContext *ctx, int token, const char *opcode) { MonoMethod* method; if (!IS_METHOD_DEF_OR_REF_OR_SPEC (token) || !token_bounds_check (ctx->image, token)) { ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid method token 0x%08x for %s at 0x%04x", token, opcode, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE); return NULL; } method = mono_get_method_full (ctx->image, token, NULL, ctx->generic_context); if (!method) { ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Cannot load method from token 0x%08x for %s at 0x%04x", token, opcode, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE); return NULL; } if (mono_method_is_valid_in_context (ctx, method) == RESULT_INVALID) return NULL; return method; } static MonoType* verifier_load_type (VerifyContext *ctx, int token, const char *opcode) { MonoType* type; if (!IS_TYPE_DEF_OR_REF_OR_SPEC (token) || !token_bounds_check (ctx->image, token)) { ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid type token 0x%08x at 0x%04x", token, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE); return NULL; } type = mono_type_get_full (ctx->image, token, ctx->generic_context); if (!type) { ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Cannot load type from token 0x%08x for %s at 0x%04x", token, opcode, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE); return NULL; } if (!mono_type_is_valid_in_context (ctx, type)) return NULL; return type; } /* stack_slot_get_type: * * Returns the stack type of @value. This value includes POINTER_MASK. * * Use this function to checks that account for a managed pointer. */ static gint32 stack_slot_get_type (ILStackDesc *value) { return value->stype & RAW_TYPE_MASK; } /* stack_slot_get_underlying_type: * * Returns the stack type of @value. This value does not include POINTER_MASK. * * Use this function is cases where the fact that the value could be a managed pointer is * irrelevant. For example, field load doesn't care about this fact of type on stack. */ static gint32 stack_slot_get_underlying_type (ILStackDesc *value) { return value->stype & TYPE_MASK; } /* stack_slot_is_managed_pointer: * * Returns TRUE is @value is a managed pointer. */ static gboolean stack_slot_is_managed_pointer (ILStackDesc *value) { return (value->stype & POINTER_MASK) == POINTER_MASK; } /* stack_slot_is_managed_mutability_pointer: * * Returns TRUE is @value is a managed mutability pointer. */ static G_GNUC_UNUSED gboolean stack_slot_is_managed_mutability_pointer (ILStackDesc *value) { return (value->stype & CMMP_MASK) == CMMP_MASK; } /* stack_slot_is_null_literal: * * Returns TRUE is @value is the null literal. */ static gboolean stack_slot_is_null_literal (ILStackDesc *value) { return (value->stype & NULL_LITERAL_MASK) == NULL_LITERAL_MASK; } /* stack_slot_is_this_pointer: * * Returns TRUE is @value is the this literal */ static gboolean stack_slot_is_this_pointer (ILStackDesc *value) { return (value->stype & THIS_POINTER_MASK) == THIS_POINTER_MASK; } /* stack_slot_is_boxed_value: * * Returns TRUE is @value is a boxed value */ static gboolean stack_slot_is_boxed_value (ILStackDesc *value) { return (value->stype & BOXED_MASK) == BOXED_MASK; } static const char * stack_slot_get_name (ILStackDesc *value) { return type_names [value->stype & TYPE_MASK]; } #define APPEND_WITH_PREDICATE(PRED,NAME) do {\ if (PRED (value)) { \ if (!first) \ g_string_append (str, ", "); \ g_string_append (str, NAME); \ first = FALSE; \ } } while (0) static char* stack_slot_stack_type_full_name (ILStackDesc *value) { GString *str = g_string_new (""); char *result; gboolean has_pred = FALSE, first = TRUE; if ((value->stype & TYPE_MASK) != value->stype) { g_string_append(str, "["); APPEND_WITH_PREDICATE (stack_slot_is_this_pointer, "this"); APPEND_WITH_PREDICATE (stack_slot_is_boxed_value, "boxed"); APPEND_WITH_PREDICATE (stack_slot_is_null_literal, "null"); APPEND_WITH_PREDICATE (stack_slot_is_managed_mutability_pointer, "cmmp"); APPEND_WITH_PREDICATE (stack_slot_is_managed_pointer, "mp"); has_pred = TRUE; } if (mono_type_is_generic_argument (value->type) && !stack_slot_is_boxed_value (value)) { if (!has_pred) g_string_append(str, "["); if (!first) g_string_append (str, ", "); g_string_append (str, "unboxed"); has_pred = TRUE; } if (has_pred) g_string_append(str, "] "); g_string_append (str, stack_slot_get_name (value)); result = str->str; g_string_free (str, FALSE); return result; } static char* stack_slot_full_name (ILStackDesc *value) { char *type_name = mono_type_full_name (value->type); char *stack_name = stack_slot_stack_type_full_name (value); char *res = g_strdup_printf ("%s (%s)", type_name, stack_name); g_free (type_name); g_free (stack_name); return res; } ////////////////////////////////////////////////////////////////// void mono_free_verify_list (GSList *list) { MonoVerifyInfoExtended *info; GSList *tmp; for (tmp = list; tmp; tmp = tmp->next) { info = tmp->data; g_free (info->info.message); g_free (info); } g_slist_free (list); } #define ADD_ERROR(list,msg) \ do { \ MonoVerifyInfoExtended *vinfo = g_new (MonoVerifyInfoExtended, 1); \ vinfo->info.status = MONO_VERIFY_ERROR; \ vinfo->info.message = (msg); \ (list) = g_slist_prepend ((list), vinfo); \ } while (0) #define ADD_WARN(list,code,msg) \ do { \ MonoVerifyInfoExtended *vinfo = g_new (MonoVerifyInfoExtended, 1); \ vinfo->info.status = (code); \ vinfo->info.message = (msg); \ (list) = g_slist_prepend ((list), vinfo); \ } while (0) static const char valid_cultures[][9] = { "ar-SA", "ar-IQ", "ar-EG", "ar-LY", "ar-DZ", "ar-MA", "ar-TN", "ar-OM", "ar-YE", "ar-SY", "ar-JO", "ar-LB", "ar-KW", "ar-AE", "ar-BH", "ar-QA", "bg-BG", "ca-ES", "zh-TW", "zh-CN", "zh-HK", "zh-SG", "zh-MO", "cs-CZ", "da-DK", "de-DE", "de-CH", "de-AT", "de-LU", "de-LI", "el-GR", "en-US", "en-GB", "en-AU", "en-CA", "en-NZ", "en-IE", "en-ZA", "en-JM", "en-CB", "en-BZ", "en-TT", "en-ZW", "en-PH", "es-ES-Ts", "es-MX", "es-ES-Is", "es-GT", "es-CR", "es-PA", "es-DO", "es-VE", "es-CO", "es-PE", "es-AR", "es-EC", "es-CL", "es-UY", "es-PY", "es-BO", "es-SV", "es-HN", "es-NI", "es-PR", "Fi-FI", "fr-FR", "fr-BE", "fr-CA", "Fr-CH", "fr-LU", "fr-MC", "he-IL", "hu-HU", "is-IS", "it-IT", "it-CH", "Ja-JP", "ko-KR", "nl-NL", "nl-BE", "nb-NO", "nn-NO", "pl-PL", "pt-BR", "pt-PT", "ro-RO", "ru-RU", "hr-HR", "Lt-sr-SP", "Cy-sr-SP", "sk-SK", "sq-AL", "sv-SE", "sv-FI", "th-TH", "tr-TR", "ur-PK", "id-ID", "uk-UA", "be-BY", "sl-SI", "et-EE", "lv-LV", "lt-LT", "fa-IR", "vi-VN", "hy-AM", "Lt-az-AZ", "Cy-az-AZ", "eu-ES", "mk-MK", "af-ZA", "ka-GE", "fo-FO", "hi-IN", "ms-MY", "ms-BN", "kk-KZ", "ky-KZ", "sw-KE", "Lt-uz-UZ", "Cy-uz-UZ", "tt-TA", "pa-IN", "gu-IN", "ta-IN", "te-IN", "kn-IN", "mr-IN", "sa-IN", "mn-MN", "gl-ES", "kok-IN", "syr-SY", "div-MV" }; static int is_valid_culture (const char *cname) { int i; int found; found = *cname == 0; for (i = 0; i < G_N_ELEMENTS (valid_cultures); ++i) { if (g_ascii_strcasecmp (valid_cultures [i], cname)) { found = 1; break; } } return found; } static int is_valid_assembly_flags (guint32 flags) { /* Metadata: 22.1.2 */ flags &= ~(0x8000 | 0x4000); /* ignore reserved bits 0x0030? */ return ((flags == 1) || (flags == 0)); } static int is_valid_blob (MonoImage *image, guint32 blob_index, int notnull) { guint32 size; const char *p, *blob_end; if (blob_index >= image->heap_blob.size) return 0; p = mono_metadata_blob_heap (image, blob_index); size = mono_metadata_decode_blob_size (p, &blob_end); if (blob_index + size + (blob_end-p) > image->heap_blob.size) return 0; if (notnull && !size) return 0; return 1; } static const char* is_valid_string (MonoImage *image, guint32 str_index, int notnull) { const char *p, *blob_end, *res; if (str_index >= image->heap_strings.size) return NULL; res = p = mono_metadata_string_heap (image, str_index); blob_end = mono_metadata_string_heap (image, image->heap_strings.size - 1); if (notnull && !*p) return 0; /* * FIXME: should check it's a valid utf8 string, too. */ while (p <= blob_end) { if (!*p) return res; ++p; } return *p? NULL: res; } static int is_valid_cls_ident (const char *p) { /* * FIXME: we need the full unicode glib support for this. * Check: http://www.unicode.org/unicode/reports/tr15/Identifier.java * We do the lame thing for now. */ if (!isalpha (*p)) return 0; ++p; while (*p) { if (!isalnum (*p) && *p != '_') return 0; ++p; } return 1; } static int is_valid_filename (const char *p) { if (!*p) return 0; return strpbrk (p, "\\//:")? 0: 1; } static GSList* verify_assembly_table (MonoImage *image, GSList *list, int level) { MonoTableInfo *t = &image->tables [MONO_TABLE_ASSEMBLY]; guint32 cols [MONO_ASSEMBLY_SIZE]; const char *p; if (level & MONO_VERIFY_ERROR) { if (t->rows > 1) ADD_ERROR (list, g_strdup ("Assembly table may only have 0 or 1 rows")); mono_metadata_decode_row (t, 0, cols, MONO_ASSEMBLY_SIZE); switch (cols [MONO_ASSEMBLY_HASH_ALG]) { case ASSEMBLY_HASH_NONE: case ASSEMBLY_HASH_MD5: case ASSEMBLY_HASH_SHA1: break; default: ADD_ERROR (list, g_strdup_printf ("Hash algorithm 0x%x unknown", cols [MONO_ASSEMBLY_HASH_ALG])); } if (!is_valid_assembly_flags (cols [MONO_ASSEMBLY_FLAGS])) ADD_ERROR (list, g_strdup_printf ("Invalid flags in assembly: 0x%x", cols [MONO_ASSEMBLY_FLAGS])); if (!is_valid_blob (image, cols [MONO_ASSEMBLY_PUBLIC_KEY], FALSE)) ADD_ERROR (list, g_strdup ("Assembly public key is an invalid index")); if (!(p = is_valid_string (image, cols [MONO_ASSEMBLY_NAME], TRUE))) { ADD_ERROR (list, g_strdup ("Assembly name is invalid")); } else { if (strpbrk (p, ":\\/.")) ADD_ERROR (list, g_strdup_printf ("Assembly name `%s' contains invalid chars", p)); } if (!(p = is_valid_string (image, cols [MONO_ASSEMBLY_CULTURE], FALSE))) { ADD_ERROR (list, g_strdup ("Assembly culture is an invalid index")); } else { if (!is_valid_culture (p)) ADD_ERROR (list, g_strdup_printf ("Assembly culture `%s' is invalid", p)); } } return list; } static GSList* verify_assemblyref_table (MonoImage *image, GSList *list, int level) { MonoTableInfo *t = &image->tables [MONO_TABLE_ASSEMBLYREF]; guint32 cols [MONO_ASSEMBLYREF_SIZE]; const char *p; int i; if (level & MONO_VERIFY_ERROR) { for (i = 0; i < t->rows; ++i) { mono_metadata_decode_row (t, i, cols, MONO_ASSEMBLYREF_SIZE); if (!is_valid_assembly_flags (cols [MONO_ASSEMBLYREF_FLAGS])) ADD_ERROR (list, g_strdup_printf ("Invalid flags in assemblyref row %d: 0x%x", i + 1, cols [MONO_ASSEMBLY_FLAGS])); if (!is_valid_blob (image, cols [MONO_ASSEMBLYREF_PUBLIC_KEY], FALSE)) ADD_ERROR (list, g_strdup_printf ("AssemblyRef public key in row %d is an invalid index", i + 1)); if (!(p = is_valid_string (image, cols [MONO_ASSEMBLYREF_CULTURE], FALSE))) { ADD_ERROR (list, g_strdup_printf ("AssemblyRef culture in row %d is invalid", i + 1)); } else { if (!is_valid_culture (p)) ADD_ERROR (list, g_strdup_printf ("AssemblyRef culture `%s' in row %d is invalid", p, i + 1)); } if (cols [MONO_ASSEMBLYREF_HASH_VALUE] && !is_valid_blob (image, cols [MONO_ASSEMBLYREF_HASH_VALUE], TRUE)) ADD_ERROR (list, g_strdup_printf ("AssemblyRef hash value in row %d is invalid or not null and empty", i + 1)); } } if (level & MONO_VERIFY_WARNING) { /* check for duplicated rows */ for (i = 0; i < t->rows; ++i) { } } return list; } static GSList* verify_class_layout_table (MonoImage *image, GSList *list, int level) { MonoTableInfo *t = &image->tables [MONO_TABLE_CLASSLAYOUT]; MonoTableInfo *tdef = &image->tables [MONO_TABLE_TYPEDEF]; guint32 cols [MONO_CLASS_LAYOUT_SIZE]; guint32 value, i; if (level & MONO_VERIFY_ERROR) { for (i = 0; i < t->rows; ++i) { mono_metadata_decode_row (t, i, cols, MONO_CLASS_LAYOUT_SIZE); if (cols [MONO_CLASS_LAYOUT_PARENT] > tdef->rows || !cols [MONO_CLASS_LAYOUT_PARENT]) { ADD_ERROR (list, g_strdup_printf ("Parent in class layout is invalid in row %d", i + 1)); } else { value = mono_metadata_decode_row_col (tdef, cols [MONO_CLASS_LAYOUT_PARENT] - 1, MONO_TYPEDEF_FLAGS); if (value & TYPE_ATTRIBUTE_INTERFACE) ADD_ERROR (list, g_strdup_printf ("Parent in class layout row %d is an interface", i + 1)); if (value & TYPE_ATTRIBUTE_AUTO_LAYOUT) ADD_ERROR (list, g_strdup_printf ("Parent in class layout row %d is AutoLayout", i + 1)); if (value & TYPE_ATTRIBUTE_SEQUENTIAL_LAYOUT) { switch (cols [MONO_CLASS_LAYOUT_PACKING_SIZE]) { case 0: case 1: case 2: case 4: case 8: case 16: case 32: case 64: case 128: break; default: ADD_ERROR (list, g_strdup_printf ("Packing size %d in class layout row %d is invalid", cols [MONO_CLASS_LAYOUT_PACKING_SIZE], i + 1)); } } else if (value & TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) { /* * FIXME: LAMESPEC: it claims it must be 0 (it's 1, instead). if (cols [MONO_CLASS_LAYOUT_PACKING_SIZE]) ADD_ERROR (list, g_strdup_printf ("Packing size %d in class layout row %d is invalid with explicit layout", cols [MONO_CLASS_LAYOUT_PACKING_SIZE], i + 1)); */ } /* * FIXME: we need to check that if class size != 0, * it needs to be greater than the class calculated size. * If parent is a valuetype it also needs to be smaller than * 1 MByte (0x100000 bytes). * To do both these checks we need to load the referenced * assemblies, though (the spec claims we didn't have to, bah). */ /* * We need to check that the parent types have the same layout * type as well. */ } } } return list; } static GSList* verify_constant_table (MonoImage *image, GSList *list, int level) { MonoTableInfo *t = &image->tables [MONO_TABLE_CONSTANT]; guint32 cols [MONO_CONSTANT_SIZE]; guint32 value, i; GHashTable *dups = g_hash_table_new (NULL, NULL); for (i = 0; i < t->rows; ++i) { mono_metadata_decode_row (t, i, cols, MONO_CONSTANT_SIZE); if (level & MONO_VERIFY_ERROR) if (g_hash_table_lookup (dups, GUINT_TO_POINTER (cols [MONO_CONSTANT_PARENT]))) ADD_ERROR (list, g_strdup_printf ("Parent 0x%08x is duplicated in Constant row %d", cols [MONO_CONSTANT_PARENT], i + 1)); g_hash_table_insert (dups, GUINT_TO_POINTER (cols [MONO_CONSTANT_PARENT]), GUINT_TO_POINTER (cols [MONO_CONSTANT_PARENT])); switch (cols [MONO_CONSTANT_TYPE]) { case MONO_TYPE_U1: /* LAMESPEC: it says I1...*/ case MONO_TYPE_U2: case MONO_TYPE_U4: case MONO_TYPE_U8: if (level & MONO_VERIFY_CLS) ADD_WARN (list, MONO_VERIFY_CLS, g_strdup_printf ("Type 0x%x not CLS compliant in Constant row %d", cols [MONO_CONSTANT_TYPE], i + 1)); case MONO_TYPE_BOOLEAN: case MONO_TYPE_CHAR: case MONO_TYPE_I1: case MONO_TYPE_I2: case MONO_TYPE_I4: case MONO_TYPE_I8: case MONO_TYPE_R4: case MONO_TYPE_R8: case MONO_TYPE_STRING: case MONO_TYPE_CLASS: break; default: if (level & MONO_VERIFY_ERROR) ADD_ERROR (list, g_strdup_printf ("Type 0x%x is invalid in Constant row %d", cols [MONO_CONSTANT_TYPE], i + 1)); } if (level & MONO_VERIFY_ERROR) { value = cols [MONO_CONSTANT_PARENT] >> MONO_HASCONSTANT_BITS; switch (cols [MONO_CONSTANT_PARENT] & MONO_HASCONSTANT_MASK) { case MONO_HASCONSTANT_FIEDDEF: if (value > image->tables [MONO_TABLE_FIELD].rows) ADD_ERROR (list, g_strdup_printf ("Parent (field) is invalid in Constant row %d", i + 1)); break; case MONO_HASCONSTANT_PARAM: if (value > image->tables [MONO_TABLE_PARAM].rows) ADD_ERROR (list, g_strdup_printf ("Parent (param) is invalid in Constant row %d", i + 1)); break; case MONO_HASCONSTANT_PROPERTY: if (value > image->tables [MONO_TABLE_PROPERTY].rows) ADD_ERROR (list, g_strdup_printf ("Parent (property) is invalid in Constant row %d", i + 1)); break; default: ADD_ERROR (list, g_strdup_printf ("Parent is invalid in Constant row %d", i + 1)); break; } } if (level & MONO_VERIFY_CLS) { /* * FIXME: verify types is consistent with the enum type * is parent is an enum. */ } } g_hash_table_destroy (dups); return list; } static GSList* verify_event_map_table (MonoImage *image, GSList *list, int level) { MonoTableInfo *t = &image->tables [MONO_TABLE_EVENTMAP]; guint32 cols [MONO_EVENT_MAP_SIZE]; guint32 i, last_event; GHashTable *dups = g_hash_table_new (NULL, NULL); last_event = 0; for (i = 0; i < t->rows; ++i) { mono_metadata_decode_row (t, i, cols, MONO_EVENT_MAP_SIZE); if (level & MONO_VERIFY_ERROR) if (g_hash_table_lookup (dups, GUINT_TO_POINTER (cols [MONO_EVENT_MAP_PARENT]))) ADD_ERROR (list, g_strdup_printf ("Parent 0x%08x is duplicated in Event Map row %d", cols [MONO_EVENT_MAP_PARENT], i + 1)); g_hash_table_insert (dups, GUINT_TO_POINTER (cols [MONO_EVENT_MAP_PARENT]), GUINT_TO_POINTER (cols [MONO_EVENT_MAP_PARENT])); if (level & MONO_VERIFY_ERROR) { if (cols [MONO_EVENT_MAP_PARENT] > image->tables [MONO_TABLE_TYPEDEF].rows) ADD_ERROR (list, g_strdup_printf ("Parent 0x%08x is invalid in Event Map row %d", cols [MONO_EVENT_MAP_PARENT], i + 1)); if (cols [MONO_EVENT_MAP_EVENTLIST] > image->tables [MONO_TABLE_EVENT].rows) ADD_ERROR (list, g_strdup_printf ("EventList 0x%08x is invalid in Event Map row %d", cols [MONO_EVENT_MAP_EVENTLIST], i + 1)); if (cols [MONO_EVENT_MAP_EVENTLIST] <= last_event) ADD_ERROR (list, g_strdup_printf ("EventList overlap in Event Map row %d", i + 1)); last_event = cols [MONO_EVENT_MAP_EVENTLIST]; } } g_hash_table_destroy (dups); return list; } static GSList* verify_event_table (MonoImage *image, GSList *list, int level) { MonoTableInfo *t = &image->tables [MONO_TABLE_EVENT]; guint32 cols [MONO_EVENT_SIZE]; const char *p; guint32 value, i; for (i = 0; i < t->rows; ++i) { mono_metadata_decode_row (t, i, cols, MONO_EVENT_SIZE); if (cols [MONO_EVENT_FLAGS] & ~(EVENT_SPECIALNAME|EVENT_RTSPECIALNAME)) { if (level & MONO_VERIFY_ERROR) ADD_ERROR (list, g_strdup_printf ("Flags 0x%04x invalid in Event row %d", cols [MONO_EVENT_FLAGS], i + 1)); } if (!(p = is_valid_string (image, cols [MONO_EVENT_NAME], TRUE))) { if (level & MONO_VERIFY_ERROR) ADD_ERROR (list, g_strdup_printf ("Invalid name in Event row %d", i + 1)); } else { if (level & MONO_VERIFY_CLS) { if (!is_valid_cls_ident (p)) ADD_WARN (list, MONO_VERIFY_CLS, g_strdup_printf ("Invalid CLS name '%s` in Event row %d", p, i + 1)); } } if (level & MONO_VERIFY_ERROR && cols [MONO_EVENT_TYPE]) { value = cols [MONO_EVENT_TYPE] >> MONO_TYPEDEFORREF_BITS; switch (cols [MONO_EVENT_TYPE] & MONO_TYPEDEFORREF_MASK) { case MONO_TYPEDEFORREF_TYPEDEF: if (!value || value > image->tables [MONO_TABLE_TYPEDEF].rows) ADD_ERROR (list, g_strdup_printf ("Type invalid in Event row %d", i + 1)); break; case MONO_TYPEDEFORREF_TYPEREF: if (!value || value > image->tables [MONO_TABLE_TYPEREF].rows) ADD_ERROR (list, g_strdup_printf ("Type invalid in Event row %d", i + 1)); break; case MONO_TYPEDEFORREF_TYPESPEC: if (!value || value > image->tables [MONO_TABLE_TYPESPEC].rows) ADD_ERROR (list, g_strdup_printf ("Type invalid in Event row %d", i + 1)); break; default: ADD_ERROR (list, g_strdup_printf ("Type invalid in Event row %d", i + 1)); } } /* * FIXME: check that there is 1 add and remove row in methodsemantics * and 0 or 1 raise and 0 or more other (maybe it's better to check for * these while checking methodsemantics). * check for duplicated names for the same type [ERROR] * check for CLS duplicate names for the same type [CLS] */ } return list; } static GSList* verify_field_table (MonoImage *image, GSList *list, int level) { MonoTableInfo *t = &image->tables [MONO_TABLE_FIELD]; guint32 cols [MONO_FIELD_SIZE]; const char *p; guint32 i, flags; for (i = 0; i < t->rows; ++i) { mono_metadata_decode_row (t, i, cols, MONO_FIELD_SIZE); /* * Check this field has only one owner and that the owner is not * an interface (done in verify_typedef_table() ) */ flags = cols [MONO_FIELD_FLAGS]; switch (flags & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK) { case FIELD_ATTRIBUTE_COMPILER_CONTROLLED: case FIELD_ATTRIBUTE_PRIVATE: case FIELD_ATTRIBUTE_FAM_AND_ASSEM: case FIELD_ATTRIBUTE_ASSEMBLY: case FIELD_ATTRIBUTE_FAMILY: case FIELD_ATTRIBUTE_FAM_OR_ASSEM: case FIELD_ATTRIBUTE_PUBLIC: break; default: if (level & MONO_VERIFY_ERROR) ADD_ERROR (list, g_strdup_printf ("Invalid access mask in Field row %d", i + 1)); break; } if (level & MONO_VERIFY_ERROR) { if ((flags & FIELD_ATTRIBUTE_LITERAL) && (flags & FIELD_ATTRIBUTE_INIT_ONLY)) ADD_ERROR (list, g_strdup_printf ("Literal and InitOnly cannot be both set in Field row %d", i + 1)); if ((flags & FIELD_ATTRIBUTE_LITERAL) && !(flags & FIELD_ATTRIBUTE_STATIC)) ADD_ERROR (list, g_strdup_printf ("Literal needs also Static set in Field row %d", i + 1)); if ((flags & FIELD_ATTRIBUTE_RT_SPECIAL_NAME) && !(flags & FIELD_ATTRIBUTE_SPECIAL_NAME)) ADD_ERROR (list, g_strdup_printf ("RTSpecialName needs also SpecialName set in Field row %d", i + 1)); /* * FIXME: check there is only one owner in the respective table. * if (flags & FIELD_ATTRIBUTE_HAS_FIELD_MARSHAL) * if (flags & FIELD_ATTRIBUTE_HAS_DEFAULT) * if (flags & FIELD_ATTRIBUTE_HAS_FIELD_RVA) */ } if (!(p = is_valid_string (image, cols [MONO_FIELD_NAME], TRUE))) { if (level & MONO_VERIFY_ERROR) ADD_ERROR (list, g_strdup_printf ("Invalid name in Field row %d", i + 1)); } else { if (level & MONO_VERIFY_CLS) { if (!is_valid_cls_ident (p)) ADD_WARN (list, MONO_VERIFY_CLS, g_strdup_printf ("Invalid CLS name '%s` in Field row %d", p, i + 1)); } } /* * check signature. * if owner is module needs to be static, access mask needs to be compilercontrolled, * public or private (not allowed in cls mode). * if owner is an enum ... */ } return list; } static GSList* verify_file_table (MonoImage *image, GSList *list, int level) { MonoTableInfo *t = &image->tables [MONO_TABLE_FILE]; guint32 cols [MONO_FILE_SIZE]; const char *p; guint32 i; GHashTable *dups = g_hash_table_new (g_str_hash, g_str_equal); for (i = 0; i < t->rows; ++i) { mono_metadata_decode_row (t, i, cols, MONO_FILE_SIZE); if (level & MONO_VERIFY_ERROR) { if (cols [MONO_FILE_FLAGS] != FILE_CONTAINS_METADATA && cols [MONO_FILE_FLAGS] != FILE_CONTAINS_NO_METADATA) ADD_ERROR (list, g_strdup_printf ("Invalid flags in File row %d", i + 1)); if (!is_valid_blob (image, cols [MONO_FILE_HASH_VALUE], TRUE)) ADD_ERROR (list, g_strdup_printf ("File hash value in row %d is invalid or not null and empty", i + 1)); } if (!(p = is_valid_string (image, cols [MONO_FILE_NAME], TRUE))) { if (level & MONO_VERIFY_ERROR) ADD_ERROR (list, g_strdup_printf ("Invalid name in File row %d", i + 1)); } else { if (level & MONO_VERIFY_ERROR) { if (!is_valid_filename (p)) ADD_ERROR (list, g_strdup_printf ("Invalid name '%s` in File row %d", p, i + 1)); else if (g_hash_table_lookup (dups, p)) { ADD_ERROR (list, g_strdup_printf ("Duplicate name '%s` in File row %d", p, i + 1)); } g_hash_table_insert (dups, (gpointer)p, (gpointer)p); } } /* * FIXME: I don't understand what this means: * If this module contains a row in the Assembly table (that is, if this module "holds the manifest") * then there shall not be any row in the File table for this module - i.e., no self-reference [ERROR] */ } if (level & MONO_VERIFY_WARNING) { if (!t->rows && image->tables [MONO_TABLE_EXPORTEDTYPE].rows) ADD_WARN (list, MONO_VERIFY_WARNING, g_strdup ("ExportedType table should be empty if File table is empty")); } g_hash_table_destroy (dups); return list; } static GSList* verify_moduleref_table (MonoImage *image, GSList *list, int level) { MonoTableInfo *t = &image->tables [MONO_TABLE_MODULEREF]; MonoTableInfo *tfile = &image->tables [MONO_TABLE_FILE]; guint32 cols [MONO_MODULEREF_SIZE]; const char *p, *pf; guint32 found, i, j, value; GHashTable *dups = g_hash_table_new (g_str_hash, g_str_equal); for (i = 0; i < t->rows; ++i) { mono_metadata_decode_row (t, i, cols, MONO_MODULEREF_SIZE); if (!(p = is_valid_string (image, cols [MONO_MODULEREF_NAME], TRUE))) { if (level & MONO_VERIFY_ERROR) ADD_ERROR (list, g_strdup_printf ("Invalid name in ModuleRef row %d", i + 1)); } else { if (level & MONO_VERIFY_ERROR) { if (!is_valid_filename (p)) ADD_ERROR (list, g_strdup_printf ("Invalid name '%s` in ModuleRef row %d", p, i + 1)); else if (g_hash_table_lookup (dups, p)) { ADD_WARN (list, MONO_VERIFY_WARNING, g_strdup_printf ("Duplicate name '%s` in ModuleRef row %d", p, i + 1)); g_hash_table_insert (dups, (gpointer)p, (gpointer)p); found = 0; for (j = 0; j < tfile->rows; ++j) { value = mono_metadata_decode_row_col (tfile, j, MONO_FILE_NAME); if ((pf = is_valid_string (image, value, TRUE))) if (strcmp (p, pf) == 0) { found = 1; break; } } if (!found) ADD_ERROR (list, g_strdup_printf ("Name '%s` in ModuleRef row %d doesn't have a match in File table", p, i + 1)); } } } } g_hash_table_destroy (dups); return list; } static GSList* verify_standalonesig_table (MonoImage *image, GSList *list, int level) { MonoTableInfo *t = &image->tables [MONO_TABLE_STANDALONESIG]; guint32 cols [MONO_STAND_ALONE_SIGNATURE_SIZE]; const char *p; guint32 i; for (i = 0; i < t->rows; ++i) { mono_metadata_decode_row (t, i, cols, MONO_STAND_ALONE_SIGNATURE_SIZE); if (level & MONO_VERIFY_ERROR) { if (!is_valid_blob (image, cols [MONO_STAND_ALONE_SIGNATURE], TRUE)) { ADD_ERROR (list, g_strdup_printf ("Signature is invalid in StandAloneSig row %d", i + 1)); } else { p = mono_metadata_blob_heap (image, cols [MONO_STAND_ALONE_SIGNATURE]); /* FIXME: check it's a valid locals or method sig.*/ } } } return list; } GSList* mono_image_verify_tables (MonoImage *image, int level) { GSList *error_list = NULL; error_list = verify_assembly_table (image, error_list, level); /* * AssemblyOS, AssemblyProcessor, AssemblyRefOs and * AssemblyRefProcessor should be ignored, * though we may want to emit a warning, since it should not * be present in a PE file. */ error_list = verify_assemblyref_table (image, error_list, level); error_list = verify_class_layout_table (image, error_list, level); error_list = verify_constant_table (image, error_list, level); /* * cutom attribute, declsecurity */ error_list = verify_event_map_table (image, error_list, level); error_list = verify_event_table (image, error_list, level); error_list = verify_field_table (image, error_list, level); error_list = verify_file_table (image, error_list, level); error_list = verify_moduleref_table (image, error_list, level); error_list = verify_standalonesig_table (image, error_list, level); return g_slist_reverse (error_list); } #define ADD_INVALID(list,msg) \ do { \ MonoVerifyInfoExtended *vinfo = g_new (MonoVerifyInfoExtended, 1); \ vinfo->status = MONO_VERIFY_ERROR; \ vinfo->message = (msg); \ (list) = g_slist_prepend ((list), vinfo); \ /*G_BREAKPOINT ();*/ \ goto invalid_cil; \ } while (0) #define CHECK_STACK_UNDERFLOW(num) \ do { \ if (cur_stack < (num)) \ ADD_INVALID (list, g_strdup_printf ("Stack underflow at 0x%04x (%d items instead of %d)", ip_offset, cur_stack, (num))); \ } while (0) #define CHECK_STACK_OVERFLOW() \ do { \ if (cur_stack >= max_stack) \ ADD_INVALID (list, g_strdup_printf ("Maxstack exceeded at 0x%04x", ip_offset)); \ } while (0) static int in_any_block (MonoMethodHeader *header, guint offset) { int i; MonoExceptionClause *clause; for (i = 0; i < header->num_clauses; ++i) { clause = &header->clauses [i]; if (MONO_OFFSET_IN_CLAUSE (clause, offset)) return 1; if (MONO_OFFSET_IN_HANDLER (clause, offset)) return 1; if (MONO_OFFSET_IN_FILTER (clause, offset)) return 1; } return 0; } /* * in_any_exception_block: * * Returns TRUE is @offset is part of any exception clause (filter, handler, catch, finally or fault). */ static gboolean in_any_exception_block (MonoMethodHeader *header, guint offset) { int i; MonoExceptionClause *clause; for (i = 0; i < header->num_clauses; ++i) { clause = &header->clauses [i]; if (MONO_OFFSET_IN_HANDLER (clause, offset)) return TRUE; if (MONO_OFFSET_IN_FILTER (clause, offset)) return TRUE; } return FALSE; } /* * is_valid_branch_instruction: * * Verify if it's valid to perform a branch from @offset to @target. * This should be used with br and brtrue/false. * It returns 0 if valid, 1 for unverifiable and 2 for invalid. * The major diferent from other similiar functions is that branching into a * finally/fault block is invalid instead of just unverifiable. */ static int is_valid_branch_instruction (MonoMethodHeader *header, guint offset, guint target) { int i; MonoExceptionClause *clause; for (i = 0; i < header->num_clauses; ++i) { clause = &header->clauses [i]; /*branching into a finally block is invalid*/ if ((clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY || clause->flags == MONO_EXCEPTION_CLAUSE_FAULT) && !MONO_OFFSET_IN_HANDLER (clause, offset) && MONO_OFFSET_IN_HANDLER (clause, target)) return 2; if (clause->try_offset != target && (MONO_OFFSET_IN_CLAUSE (clause, offset) ^ MONO_OFFSET_IN_CLAUSE (clause, target))) return 1; if (MONO_OFFSET_IN_HANDLER (clause, offset) ^ MONO_OFFSET_IN_HANDLER (clause, target)) return 1; if (MONO_OFFSET_IN_FILTER (clause, offset) ^ MONO_OFFSET_IN_FILTER (clause, target)) return 1; } return 0; } /* * is_valid_cmp_branch_instruction: * * Verify if it's valid to perform a branch from @offset to @target. * This should be used with binary comparison branching instruction, like beq, bge and similars. * It returns 0 if valid, 1 for unverifiable and 2 for invalid. * * The major diferences from other similar functions are that most errors lead to invalid * code and only branching out of finally, filter or fault clauses is unverifiable. */ static int is_valid_cmp_branch_instruction (MonoMethodHeader *header, guint offset, guint target) { int i; MonoExceptionClause *clause; for (i = 0; i < header->num_clauses; ++i) { clause = &header->clauses [i]; /*branching out of a handler or finally*/ if (clause->flags != MONO_EXCEPTION_CLAUSE_NONE && MONO_OFFSET_IN_HANDLER (clause, offset) && !MONO_OFFSET_IN_HANDLER (clause, target)) return 1; if (clause->try_offset != target && (MONO_OFFSET_IN_CLAUSE (clause, offset) ^ MONO_OFFSET_IN_CLAUSE (clause, target))) return 2; if (MONO_OFFSET_IN_HANDLER (clause, offset) ^ MONO_OFFSET_IN_HANDLER (clause, target)) return 2; if (MONO_OFFSET_IN_FILTER (clause, offset) ^ MONO_OFFSET_IN_FILTER (clause, target)) return 2; } return 0; } /* * A leave can't escape a finally block */ static int is_correct_leave (MonoMethodHeader *header, guint offset, guint target) { int i; MonoExceptionClause *clause; for (i = 0; i < header->num_clauses; ++i) { clause = &header->clauses [i]; if (clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY && MONO_OFFSET_IN_HANDLER (clause, offset) && !MONO_OFFSET_IN_HANDLER (clause, target)) return 0; if (MONO_OFFSET_IN_FILTER (clause, offset)) return 0; } return 1; } /* * A rethrow can't happen outside of a catch handler. */ static int is_correct_rethrow (MonoMethodHeader *header, guint offset) { int i; MonoExceptionClause *clause; for (i = 0; i < header->num_clauses; ++i) { clause = &header->clauses [i]; if (MONO_OFFSET_IN_HANDLER (clause, offset)) return 1; if (MONO_OFFSET_IN_FILTER (clause, offset)) return 1; } return 0; } /* * An endfinally can't happen outside of a finally/fault handler. */ static int is_correct_endfinally (MonoMethodHeader *header, guint offset) { int i; MonoExceptionClause *clause; for (i = 0; i < header->num_clauses; ++i) { clause = &header->clauses [i]; if (MONO_OFFSET_IN_HANDLER (clause, offset) && (clause->flags == MONO_EXCEPTION_CLAUSE_FAULT || clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY)) return 1; } return 0; } /* * An endfilter can only happens inside a filter clause. * In non-strict mode filter is allowed inside the handler clause too */ static MonoExceptionClause * is_correct_endfilter (VerifyContext *ctx, guint offset) { int i; MonoExceptionClause *clause; for (i = 0; i < ctx->header->num_clauses; ++i) { clause = &ctx->header->clauses [i]; if (clause->flags != MONO_EXCEPTION_CLAUSE_FILTER) continue; if (MONO_OFFSET_IN_FILTER (clause, offset)) return clause; if (!IS_STRICT_MODE (ctx) && MONO_OFFSET_IN_HANDLER (clause, offset)) return clause; } return NULL; } /* * Non-strict endfilter can happens inside a try block or any handler block */ static int is_unverifiable_endfilter (VerifyContext *ctx, guint offset) { int i; MonoExceptionClause *clause; for (i = 0; i < ctx->header->num_clauses; ++i) { clause = &ctx->header->clauses [i]; if (MONO_OFFSET_IN_CLAUSE (clause, offset)) return 1; } return 0; } static gboolean is_valid_bool_arg (ILStackDesc *arg) { if (stack_slot_is_managed_pointer (arg) || stack_slot_is_boxed_value (arg) || stack_slot_is_null_literal (arg)) return TRUE; switch (stack_slot_get_underlying_type (arg)) { case TYPE_I4: case TYPE_I8: case TYPE_NATIVE_INT: case TYPE_PTR: return TRUE; case TYPE_COMPLEX: g_assert (arg->type); switch (arg->type->type) { case MONO_TYPE_CLASS: case MONO_TYPE_STRING: case MONO_TYPE_OBJECT: case MONO_TYPE_SZARRAY: case MONO_TYPE_ARRAY: case MONO_TYPE_FNPTR: case MONO_TYPE_PTR: return TRUE; case MONO_TYPE_GENERICINST: /*We need to check if the container class * of the generic type is a valuetype, iow: * is it a "class Foo<T>" or a "struct Foo<T>"? */ return !arg->type->data.generic_class->container_class->valuetype; } default: return FALSE; } } /*Type manipulation helper*/ /*Returns the byref version of the supplied MonoType*/ static MonoType* mono_type_get_type_byref (MonoType *type) { if (type->byref) return type; return &mono_class_from_mono_type (type)->this_arg; } /*Returns the byval version of the supplied MonoType*/ static MonoType* mono_type_get_type_byval (MonoType *type) { if (!type->byref) return type; return &mono_class_from_mono_type (type)->byval_arg; } static MonoType* mono_type_from_stack_slot (ILStackDesc *slot) { if (stack_slot_is_managed_pointer (slot)) return mono_type_get_type_byref (slot->type); return slot->type; } /*Stack manipulation code*/ static void stack_init (VerifyContext *ctx, ILCodeDesc *state) { if (state->flags & IL_CODE_FLAG_STACK_INITED) return; state->size = 0; state->flags |= IL_CODE_FLAG_STACK_INITED; if (!state->stack) state->stack = g_new0 (ILStackDesc, ctx->max_stack); } static void stack_copy (ILCodeDesc *to, ILCodeDesc *from) { to->size = from->size; memcpy (to->stack, from->stack, sizeof (ILStackDesc) * from->size); } static void copy_stack_value (ILStackDesc *to, ILStackDesc *from) { to->stype = from->stype; to->type = from->type; to->method = from->method; } static int check_underflow (VerifyContext *ctx, int size) { if (ctx->eval.size < size) { ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Stack underflow, required %d, but have %d at 0x%04x", size, ctx->eval.size, ctx->ip_offset)); return 0; } return 1; } static int check_overflow (VerifyContext *ctx) { if (ctx->eval.size >= ctx->max_stack) { ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Method doesn't have stack-depth %d at 0x%04x", ctx->eval.size + 1, ctx->ip_offset)); return 0; } return 1; } /*This reject out PTR, FNPTR and TYPEDBYREF*/ static gboolean check_unmanaged_pointer (VerifyContext *ctx, ILStackDesc *value) { if (stack_slot_get_type (value) == TYPE_PTR) { CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Unmanaged pointer is not a verifiable type at 0x%04x", ctx->ip_offset)); return 0; } return 1; } /*TODO verify if MONO_TYPE_TYPEDBYREF is not allowed here as well.*/ static gboolean check_unverifiable_type (VerifyContext *ctx, MonoType *type) { if (type->type == MONO_TYPE_PTR || type->type == MONO_TYPE_FNPTR) { CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Unmanaged pointer is not a verifiable type at 0x%04x", ctx->ip_offset)); return 0; } return 1; } static ILStackDesc * stack_push (VerifyContext *ctx) { g_assert (ctx->eval.size < ctx->max_stack); return & ctx->eval.stack [ctx->eval.size++]; } static ILStackDesc * stack_push_val (VerifyContext *ctx, int stype, MonoType *type) { ILStackDesc *top = stack_push (ctx); top->stype = stype; top->type = type; return top; } static ILStackDesc * stack_pop (VerifyContext *ctx) { ILStackDesc *ret; g_assert (ctx->eval.size > 0); ret = ctx->eval.stack + --ctx->eval.size; if ((ret->stype & UNINIT_THIS_MASK) == UNINIT_THIS_MASK) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Found use of uninitialized 'this ptr' ref at 0x%04x", ctx->ip_offset)); return ret; } /* This function allows to safely pop an unititialized this ptr from * the eval stack without marking the method as unverifiable. */ static ILStackDesc * stack_pop_safe (VerifyContext *ctx) { g_assert (ctx->eval.size > 0); return ctx->eval.stack + --ctx->eval.size; } static ILStackDesc * stack_push_stack_val (VerifyContext *ctx, ILStackDesc *value) { ILStackDesc *top = stack_push (ctx); copy_stack_value (top, value); return top; } /* Returns the MonoType associated with the token, or NULL if it is invalid. * * A boxable type can be either a reference or value type, but cannot be a byref type or an unmanaged pointer * */ static MonoType* get_boxable_mono_type (VerifyContext* ctx, int token, const char *opcode) { MonoType *type; MonoClass *class; if (!(type = verifier_load_type (ctx, token, opcode))) return NULL; if (type->byref && type->type != MONO_TYPE_TYPEDBYREF) { ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid use of byref type for %s at 0x%04x", opcode, ctx->ip_offset)); return NULL; } if (type->type == MONO_TYPE_VOID) { ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid use of void type for %s at 0x%04x", opcode, ctx->ip_offset)); return NULL; } if (type->type == MONO_TYPE_TYPEDBYREF) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid use of typedbyref for %s at 0x%04x", opcode, ctx->ip_offset)); if (!(class = mono_class_from_mono_type (type))) ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Could not retrieve type token for %s at 0x%04x", opcode, ctx->ip_offset)); if (class->generic_container && type->type != MONO_TYPE_GENERICINST) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use the generic type definition in a boxable type position for %s at 0x%04x", opcode, ctx->ip_offset)); check_unverifiable_type (ctx, type); return type; } /*operation result tables */ static const unsigned char bin_op_table [TYPE_MAX][TYPE_MAX] = { {TYPE_I4, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV}, {TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV}, {TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV}, {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_R8, TYPE_INV, TYPE_INV}, {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV}, {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV}, }; static const unsigned char add_table [TYPE_MAX][TYPE_MAX] = { {TYPE_I4, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV}, {TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV}, {TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV}, {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_R8, TYPE_INV, TYPE_INV}, {TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_INV, TYPE_INV}, {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV}, }; static const unsigned char sub_table [TYPE_MAX][TYPE_MAX] = { {TYPE_I4, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV}, {TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV}, {TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV}, {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_R8, TYPE_INV, TYPE_INV}, {TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_NATIVE_INT | NON_VERIFIABLE_RESULT, TYPE_INV}, {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV}, }; static const unsigned char int_bin_op_table [TYPE_MAX][TYPE_MAX] = { {TYPE_I4, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV}, {TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV}, {TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV}, {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV}, {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV}, {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV}, }; static const unsigned char shift_op_table [TYPE_MAX][TYPE_MAX] = { {TYPE_I4, TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV, TYPE_INV}, {TYPE_I8, TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV}, {TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV}, {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV}, {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV}, {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV}, }; static const unsigned char cmp_br_op [TYPE_MAX][TYPE_MAX] = { {TYPE_I4, TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV, TYPE_INV}, {TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV}, {TYPE_I4, TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV, TYPE_INV}, {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV}, {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_I4, TYPE_INV}, {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV}, }; static const unsigned char cmp_br_eq_op [TYPE_MAX][TYPE_MAX] = { {TYPE_I4, TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV, TYPE_INV}, {TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV}, {TYPE_I4, TYPE_INV, TYPE_I4, TYPE_INV, TYPE_I4 | NON_VERIFIABLE_RESULT, TYPE_INV}, {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV}, {TYPE_INV, TYPE_INV, TYPE_I4 | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_I4, TYPE_INV}, {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_I4}, }; static const unsigned char add_ovf_un_table [TYPE_MAX][TYPE_MAX] = { {TYPE_I4, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV}, {TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV}, {TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV}, {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV}, {TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_INV, TYPE_INV}, {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV}, }; static const unsigned char sub_ovf_un_table [TYPE_MAX][TYPE_MAX] = { {TYPE_I4, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV}, {TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV}, {TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV}, {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV}, {TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_NATIVE_INT | NON_VERIFIABLE_RESULT, TYPE_INV}, {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV}, }; static const unsigned char bin_ovf_table [TYPE_MAX][TYPE_MAX] = { {TYPE_I4, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV}, {TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV}, {TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV}, {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV}, {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV}, {TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV}, }; #ifdef MONO_VERIFIER_DEBUG /*debug helpers */ static void dump_stack_value (ILStackDesc *value) { printf ("[(%x)(%x)", value->type->type, value->stype); if (stack_slot_is_this_pointer (value)) printf ("[this] "); if (stack_slot_is_boxed_value (value)) printf ("[boxed] "); if (stack_slot_is_null_literal (value)) printf ("[null] "); if (stack_slot_is_managed_mutability_pointer (value)) printf ("Controled Mutability MP: "); if (stack_slot_is_managed_pointer (value)) printf ("Managed Pointer to: "); switch (stack_slot_get_underlying_type (value)) { case TYPE_INV: printf ("invalid type]"); return; case TYPE_I4: printf ("int32]"); return; case TYPE_I8: printf ("int64]"); return; case TYPE_NATIVE_INT: printf ("native int]"); return; case TYPE_R8: printf ("float64]"); return; case TYPE_PTR: printf ("unmanaged pointer]"); return; case TYPE_COMPLEX: switch (value->type->type) { case MONO_TYPE_CLASS: case MONO_TYPE_VALUETYPE: printf ("complex] (%s)", value->type->data.klass->name); return; case MONO_TYPE_STRING: printf ("complex] (string)"); return; case MONO_TYPE_OBJECT: printf ("complex] (object)"); return; case MONO_TYPE_SZARRAY: printf ("complex] (%s [])", value->type->data.klass->name); return; case MONO_TYPE_ARRAY: printf ("complex] (%s [%d %d %d])", value->type->data.array->eklass->name, value->type->data.array->rank, value->type->data.array->numsizes, value->type->data.array->numlobounds); return; case MONO_TYPE_GENERICINST: printf ("complex] (inst of %s )", value->type->data.generic_class->container_class->name); return; case MONO_TYPE_VAR: printf ("complex] (type generic param !%d - %s) ", value->type->data.generic_param->num, mono_generic_param_info (value->type->data.generic_param)->name); return; case MONO_TYPE_MVAR: printf ("complex] (method generic param !!%d - %s) ", value->type->data.generic_param->num, mono_generic_param_info (value->type->data.generic_param)->name); return; default: { //should be a boxed value char * name = mono_type_full_name (value->type); printf ("complex] %s", name); g_free (name); return; } } default: printf ("unknown stack %x type]\n", value->stype); g_assert_not_reached (); } } static void dump_stack_state (ILCodeDesc *state) { int i; printf ("(%d) ", state->size); for (i = 0; i < state->size; ++i) dump_stack_value (state->stack + i); printf ("\n"); } #endif /*Returns TRUE if candidate array type can be assigned to target. *Both parameters MUST be of type MONO_TYPE_ARRAY (target->type == MONO_TYPE_ARRAY) */ static gboolean is_array_type_compatible (MonoType *target, MonoType *candidate) { MonoArrayType *left = target->data.array; MonoArrayType *right = candidate->data.array; g_assert (target->type == MONO_TYPE_ARRAY); g_assert (candidate->type == MONO_TYPE_ARRAY); if (left->rank != right->rank) return FALSE; return mono_class_is_assignable_from (left->eklass, right->eklass); } static int get_stack_type (MonoType *type) { int mask = 0; int type_kind = type->type; if (type->byref) mask = POINTER_MASK; /*TODO handle CMMP_MASK */ handle_enum: switch (type_kind) { case MONO_TYPE_I1: case MONO_TYPE_U1: case MONO_TYPE_BOOLEAN: case MONO_TYPE_I2: case MONO_TYPE_U2: case MONO_TYPE_CHAR: case MONO_TYPE_I4: case MONO_TYPE_U4: return TYPE_I4 | mask; case MONO_TYPE_I: case MONO_TYPE_U: return TYPE_NATIVE_INT | mask; /* FIXME: the spec says that you cannot have a pointer to method pointer, do we need to check this here? */ case MONO_TYPE_FNPTR: case MONO_TYPE_PTR: case MONO_TYPE_TYPEDBYREF: return TYPE_PTR | mask; case MONO_TYPE_VAR: case MONO_TYPE_MVAR: case MONO_TYPE_CLASS: case MONO_TYPE_STRING: case MONO_TYPE_OBJECT: case MONO_TYPE_SZARRAY: case MONO_TYPE_ARRAY: return TYPE_COMPLEX | mask; case MONO_TYPE_I8: case MONO_TYPE_U8: return TYPE_I8 | mask; case MONO_TYPE_R4: case MONO_TYPE_R8: return TYPE_R8 | mask; case MONO_TYPE_GENERICINST: case MONO_TYPE_VALUETYPE: if (mono_type_is_enum_type (type)) { type = mono_type_get_underlying_type_any (type); if (!type) return FALSE; type_kind = type->type; goto handle_enum; } else { return TYPE_COMPLEX | mask; } default: return TYPE_INV; } } /* convert MonoType to ILStackDesc format (stype) */ static gboolean set_stack_value (VerifyContext *ctx, ILStackDesc *stack, MonoType *type, int take_addr) { int mask = 0; int type_kind = type->type; if (type->byref || take_addr) mask = POINTER_MASK; /* TODO handle CMMP_MASK */ handle_enum: stack->type = type; switch (type_kind) { case MONO_TYPE_I1: case MONO_TYPE_U1: case MONO_TYPE_BOOLEAN: case MONO_TYPE_I2: case MONO_TYPE_U2: case MONO_TYPE_CHAR: case MONO_TYPE_I4: case MONO_TYPE_U4: stack->stype = TYPE_I4 | mask; break; case MONO_TYPE_I: case MONO_TYPE_U: stack->stype = TYPE_NATIVE_INT | mask; break; /*FIXME: Do we need to check if it's a pointer to the method pointer? The spec says it' illegal to have that.*/ case MONO_TYPE_FNPTR: case MONO_TYPE_PTR: case MONO_TYPE_TYPEDBYREF: stack->stype = TYPE_PTR | mask; break; case MONO_TYPE_CLASS: case MONO_TYPE_STRING: case MONO_TYPE_OBJECT: case MONO_TYPE_SZARRAY: case MONO_TYPE_ARRAY: case MONO_TYPE_VAR: case MONO_TYPE_MVAR: stack->stype = TYPE_COMPLEX | mask; break; case MONO_TYPE_I8: case MONO_TYPE_U8: stack->stype = TYPE_I8 | mask; break; case MONO_TYPE_R4: case MONO_TYPE_R8: stack->stype = TYPE_R8 | mask; break; case MONO_TYPE_GENERICINST: case MONO_TYPE_VALUETYPE: if (mono_type_is_enum_type (type)) { MonoType *utype = mono_type_get_underlying_type_any (type); if (!utype) { ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Could not resolve underlying type of %x at %d", type->type, ctx->ip_offset)); return FALSE; } type = utype; type_kind = type->type; goto handle_enum; } else { stack->stype = TYPE_COMPLEX | mask; break; } default: VERIFIER_DEBUG ( printf ("unknown type 0x%02x in eval stack type\n", type->type); ); ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Illegal value set on stack 0x%02x at %d", type->type, ctx->ip_offset)); return FALSE; } return TRUE; } /* * init_stack_with_value_at_exception_boundary: * * Initialize the stack and push a given type. * The instruction is marked as been on the exception boundary. */ static void init_stack_with_value_at_exception_boundary (VerifyContext *ctx, ILCodeDesc *code, MonoClass *klass) { MonoError error; MonoType *type = mono_class_inflate_generic_type_checked (&klass->byval_arg, ctx->generic_context, &error); if (!mono_error_ok (&error)) { char *name = mono_type_get_full_name (klass); ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid class %s used for exception", name)); g_free (name); mono_error_cleanup (&error); return; } if (!ctx->max_stack) { ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Stack overflow at 0x%04x", ctx->ip_offset)); return; } stack_init (ctx, code); set_stack_value (ctx, code->stack, type, FALSE); ctx->exception_types = g_slist_prepend (ctx->exception_types, type); code->size = 1; code->flags |= IL_CODE_FLAG_WAS_TARGET; if (mono_type_is_generic_argument (type)) code->stack->stype |= BOXED_MASK; } /*Verify if type 'candidate' can be stored in type 'target'. * * If strict, check for the underlying type and not the verification stack types */ static gboolean verify_type_compatibility_full (VerifyContext *ctx, MonoType *target, MonoType *candidate, gboolean strict) { #define IS_ONE_OF3(T, A, B, C) (T == A || T == B || T == C) #define IS_ONE_OF2(T, A, B) (T == A || T == B) MonoType *original_candidate = candidate; VERIFIER_DEBUG ( printf ("checking type compatibility %s x %s strict %d\n", mono_type_full_name (target), mono_type_full_name (candidate), strict); ); /*only one is byref */ if (candidate->byref ^ target->byref) { /* converting from native int to byref*/ if (get_stack_type (candidate) == TYPE_NATIVE_INT && target->byref) { CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("using byref native int at 0x%04x", ctx->ip_offset)); return TRUE; } return FALSE; } strict |= target->byref; /*From now on we don't care about byref anymore, so it's ok to discard it here*/ candidate = mono_type_get_underlying_type_any (candidate); handle_enum: switch (target->type) { case MONO_TYPE_VOID: return candidate->type == MONO_TYPE_VOID; case MONO_TYPE_I1: case MONO_TYPE_U1: case MONO_TYPE_BOOLEAN: if (strict) return IS_ONE_OF3 (candidate->type, MONO_TYPE_I1, MONO_TYPE_U1, MONO_TYPE_BOOLEAN); case MONO_TYPE_I2: case MONO_TYPE_U2: case MONO_TYPE_CHAR: if (strict) return IS_ONE_OF3 (candidate->type, MONO_TYPE_I2, MONO_TYPE_U2, MONO_TYPE_CHAR); case MONO_TYPE_I4: case MONO_TYPE_U4: { gboolean is_native_int = IS_ONE_OF2 (candidate->type, MONO_TYPE_I, MONO_TYPE_U); gboolean is_int4 = IS_ONE_OF2 (candidate->type, MONO_TYPE_I4, MONO_TYPE_U4); if (strict) return is_native_int || is_int4; return is_native_int || get_stack_type (candidate) == TYPE_I4; } case MONO_TYPE_I8: case MONO_TYPE_U8: return IS_ONE_OF2 (candidate->type, MONO_TYPE_I8, MONO_TYPE_U8); case MONO_TYPE_R4: case MONO_TYPE_R8: if (strict) return candidate->type == target->type; return IS_ONE_OF2 (candidate->type, MONO_TYPE_R4, MONO_TYPE_R8); case MONO_TYPE_I: case MONO_TYPE_U: { gboolean is_native_int = IS_ONE_OF2 (candidate->type, MONO_TYPE_I, MONO_TYPE_U); gboolean is_int4 = IS_ONE_OF2 (candidate->type, MONO_TYPE_I4, MONO_TYPE_U4); if (strict) return is_native_int || is_int4; return is_native_int || get_stack_type (candidate) == TYPE_I4; } case MONO_TYPE_PTR: if (candidate->type != MONO_TYPE_PTR) return FALSE; /* check the underlying type */ return verify_type_compatibility_full (ctx, target->data.type, candidate->data.type, TRUE); case MONO_TYPE_FNPTR: { MonoMethodSignature *left, *right; if (candidate->type != MONO_TYPE_FNPTR) return FALSE; left = mono_type_get_signature (target); right = mono_type_get_signature (candidate); return mono_metadata_signature_equal (left, right) && left->call_convention == right->call_convention; } case MONO_TYPE_GENERICINST: { MonoClass *target_klass; MonoClass *candidate_klass; if (mono_type_is_enum_type (target)) { target = mono_type_get_underlying_type_any (target); if (!target) return FALSE; goto handle_enum; } /* * VAR / MVAR compatibility must be checked by verify_stack_type_compatibility * to take boxing status into account. */ if (mono_type_is_generic_argument (original_candidate)) return FALSE; target_klass = mono_class_from_mono_type (target); candidate_klass = mono_class_from_mono_type (candidate); if (mono_class_is_nullable (target_klass)) { if (!mono_class_is_nullable (candidate_klass)) return FALSE; return target_klass == candidate_klass; } return mono_class_is_assignable_from (target_klass, candidate_klass); } case MONO_TYPE_STRING: return candidate->type == MONO_TYPE_STRING; case MONO_TYPE_CLASS: /* * VAR / MVAR compatibility must be checked by verify_stack_type_compatibility * to take boxing status into account. */ if (mono_type_is_generic_argument (original_candidate)) return FALSE; if (candidate->type == MONO_TYPE_VALUETYPE) return FALSE; /* If candidate is an enum it should return true for System.Enum and supertypes. * That's why here we use the original type and not the underlying type. */ return mono_class_is_assignable_from (target->data.klass, mono_class_from_mono_type (original_candidate)); case MONO_TYPE_OBJECT: return MONO_TYPE_IS_REFERENCE (candidate); case MONO_TYPE_SZARRAY: { MonoClass *left; MonoClass *right; if (candidate->type != MONO_TYPE_SZARRAY) return FALSE; left = mono_class_from_mono_type (target)->element_class; right = mono_class_from_mono_type (candidate)->element_class; return mono_class_is_assignable_from (left, right); } case MONO_TYPE_ARRAY: if (candidate->type != MONO_TYPE_ARRAY) return FALSE; return is_array_type_compatible (target, candidate); case MONO_TYPE_TYPEDBYREF: return candidate->type == MONO_TYPE_TYPEDBYREF; case MONO_TYPE_VALUETYPE: { MonoClass *target_klass; MonoClass *candidate_klass; if (candidate->type == MONO_TYPE_CLASS) return FALSE; target_klass = mono_class_from_mono_type (target); candidate_klass = mono_class_from_mono_type (candidate); if (target_klass == candidate_klass) return TRUE; if (mono_type_is_enum_type (target)) { target = mono_type_get_underlying_type_any (target); if (!target) return FALSE; goto handle_enum; } return FALSE; } case MONO_TYPE_VAR: if (candidate->type != MONO_TYPE_VAR) return FALSE; return mono_type_get_generic_param_num (candidate) == mono_type_get_generic_param_num (target); case MONO_TYPE_MVAR: if (candidate->type != MONO_TYPE_MVAR) return FALSE; return mono_type_get_generic_param_num (candidate) == mono_type_get_generic_param_num (target); default: VERIFIER_DEBUG ( printf ("unknown store type %d\n", target->type); ); g_assert_not_reached (); return FALSE; } return 1; #undef IS_ONE_OF3 #undef IS_ONE_OF2 } static gboolean verify_type_compatibility (VerifyContext *ctx, MonoType *target, MonoType *candidate) { return verify_type_compatibility_full (ctx, target, candidate, FALSE); } /* * Returns the generic param bound to the context been verified. * */ static MonoGenericParam* get_generic_param (VerifyContext *ctx, MonoType *param) { guint16 param_num = mono_type_get_generic_param_num (param); if (param->type == MONO_TYPE_VAR) { if (!ctx->generic_context->class_inst || ctx->generic_context->class_inst->type_argc <= param_num) { ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid generic type argument %d", param_num)); return NULL; } return ctx->generic_context->class_inst->type_argv [param_num]->data.generic_param; } /*param must be a MVAR */ if (!ctx->generic_context->method_inst || ctx->generic_context->method_inst->type_argc <= param_num) { ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid generic method argument %d", param_num)); return NULL; } return ctx->generic_context->method_inst->type_argv [param_num]->data.generic_param; } static gboolean recursive_boxed_constraint_type_check (VerifyContext *ctx, MonoType *type, MonoClass *constraint_class, int recursion_level) { MonoType *constraint_type = &constraint_class->byval_arg; if (recursion_level <= 0) return FALSE; if (verify_type_compatibility_full (ctx, type, mono_type_get_type_byval (constraint_type), FALSE)) return TRUE; if (mono_type_is_generic_argument (constraint_type)) { MonoGenericParam *param = get_generic_param (ctx, constraint_type); MonoClass **class; if (!param) return FALSE; for (class = mono_generic_param_info (param)->constraints; class && *class; ++class) { if (recursive_boxed_constraint_type_check (ctx, type, *class, recursion_level - 1)) return TRUE; } } return FALSE; } /* * is_compatible_boxed_valuetype: * * Returns TRUE if @candidate / @stack is a valid boxed valuetype. * * @type The source type. It it tested to be of the proper type. * @candidate type of the boxed valuetype. * @stack stack slot of the boxed valuetype, separate from @candidade since one could be changed before calling this function * @strict if TRUE candidate must be boxed compatible to the target type * */ static gboolean is_compatible_boxed_valuetype (VerifyContext *ctx, MonoType *type, MonoType *candidate, ILStackDesc *stack, gboolean strict) { if (!stack_slot_is_boxed_value (stack)) return FALSE; if (type->byref || candidate->byref) return FALSE; if (mono_type_is_generic_argument (candidate)) { MonoGenericParam *param = get_generic_param (ctx, candidate); MonoClass **class; if (!param) return FALSE; for (class = mono_generic_param_info (param)->constraints; class && *class; ++class) { /*256 should be enough since there can't be more than 255 generic arguments.*/ if (recursive_boxed_constraint_type_check (ctx, type, *class, 256)) return TRUE; } } if (mono_type_is_generic_argument (type)) return FALSE; if (!strict) return TRUE; return MONO_TYPE_IS_REFERENCE (type) && mono_class_is_assignable_from (mono_class_from_mono_type (type), mono_class_from_mono_type (candidate)); } static int verify_stack_type_compatibility_full (VerifyContext *ctx, MonoType *type, ILStackDesc *stack, gboolean drop_byref, gboolean valuetype_must_be_boxed) { MonoType *candidate = mono_type_from_stack_slot (stack); if (MONO_TYPE_IS_REFERENCE (type) && !type->byref && stack_slot_is_null_literal (stack)) return TRUE; if (is_compatible_boxed_valuetype (ctx, type, candidate, stack, TRUE)) return TRUE; if (valuetype_must_be_boxed && !stack_slot_is_boxed_value (stack) && !MONO_TYPE_IS_REFERENCE (candidate)) return FALSE; if (!valuetype_must_be_boxed && stack_slot_is_boxed_value (stack)) return FALSE; if (drop_byref) return verify_type_compatibility_full (ctx, type, mono_type_get_type_byval (candidate), FALSE); return verify_type_compatibility_full (ctx, type, candidate, FALSE); } static int verify_stack_type_compatibility (VerifyContext *ctx, MonoType *type, ILStackDesc *stack) { return verify_stack_type_compatibility_full (ctx, type, stack, FALSE, FALSE); } static gboolean mono_delegate_type_equal (MonoType *target, MonoType *candidate) { if (candidate->byref ^ target->byref) return FALSE; switch (target->type) { case MONO_TYPE_VOID: case MONO_TYPE_I1: case MONO_TYPE_U1: case MONO_TYPE_BOOLEAN: case MONO_TYPE_I2: case MONO_TYPE_U2: case MONO_TYPE_CHAR: case MONO_TYPE_I4: case MONO_TYPE_U4: case MONO_TYPE_I8: case MONO_TYPE_U8: case MONO_TYPE_R4: case MONO_TYPE_R8: case MONO_TYPE_I: case MONO_TYPE_U: case MONO_TYPE_STRING: case MONO_TYPE_TYPEDBYREF: return candidate->type == target->type; case MONO_TYPE_PTR: return mono_delegate_type_equal (target->data.type, candidate->data.type); case MONO_TYPE_FNPTR: if (candidate->type != MONO_TYPE_FNPTR) return FALSE; return mono_delegate_signature_equal (mono_type_get_signature (target), mono_type_get_signature (candidate), FALSE); case MONO_TYPE_GENERICINST: { MonoClass *target_klass; MonoClass *candidate_klass; target_klass = mono_class_from_mono_type (target); candidate_klass = mono_class_from_mono_type (candidate); /*FIXME handle nullables and enum*/ return mono_class_is_assignable_from (target_klass, candidate_klass); } case MONO_TYPE_OBJECT: return MONO_TYPE_IS_REFERENCE (candidate); case MONO_TYPE_CLASS: return mono_class_is_assignable_from(target->data.klass, mono_class_from_mono_type (candidate)); case MONO_TYPE_SZARRAY: if (candidate->type != MONO_TYPE_SZARRAY) return FALSE; return mono_class_is_assignable_from (mono_class_from_mono_type (target)->element_class, mono_class_from_mono_type (candidate)->element_class); case MONO_TYPE_ARRAY: if (candidate->type != MONO_TYPE_ARRAY) return FALSE; return is_array_type_compatible (target, candidate); case MONO_TYPE_VALUETYPE: /*FIXME handle nullables and enum*/ return mono_class_from_mono_type (candidate) == mono_class_from_mono_type (target); case MONO_TYPE_VAR: return candidate->type == MONO_TYPE_VAR && mono_type_get_generic_param_num (target) == mono_type_get_generic_param_num (candidate); return FALSE; case MONO_TYPE_MVAR: return candidate->type == MONO_TYPE_MVAR && mono_type_get_generic_param_num (target) == mono_type_get_generic_param_num (candidate); return FALSE; default: VERIFIER_DEBUG ( printf ("Unknown type %d. Implement me!\n", target->type); ); g_assert_not_reached (); return FALSE; } } static gboolean mono_delegate_param_equal (MonoType *delegate, MonoType *method) { if (mono_metadata_type_equal_full (delegate, method, TRUE)) return TRUE; return mono_delegate_type_equal (method, delegate); } static gboolean mono_delegate_ret_equal (MonoType *delegate, MonoType *method) { if (mono_metadata_type_equal_full (delegate, method, TRUE)) return TRUE; return mono_delegate_type_equal (delegate, method); } /* * mono_delegate_signature_equal: * * Compare two signatures in the way expected by delegates. * * This function only exists due to the fact that it should ignore the 'has_this' part of the signature. * * FIXME can this function be eliminated and proper metadata functionality be used? */ static gboolean mono_delegate_signature_equal (MonoMethodSignature *delegate_sig, MonoMethodSignature *method_sig, gboolean is_static_ldftn) { int i; int method_offset = is_static_ldftn ? 1 : 0; if (delegate_sig->param_count + method_offset != method_sig->param_count) return FALSE; if (delegate_sig->call_convention != method_sig->call_convention) return FALSE; for (i = 0; i < delegate_sig->param_count; i++) { MonoType *p1 = delegate_sig->params [i]; MonoType *p2 = method_sig->params [i + method_offset]; if (!mono_delegate_param_equal (p1, p2)) return FALSE; } if (!mono_delegate_ret_equal (delegate_sig->ret, method_sig->ret)) return FALSE; return TRUE; } /* * verify_ldftn_delegate: * * Verify properties of ldftn based delegates. */ static void verify_ldftn_delegate (VerifyContext *ctx, MonoClass *delegate, ILStackDesc *value, ILStackDesc *funptr) { MonoMethod *method = funptr->method; /*ldftn non-final virtuals only allowed if method is not static, * the object is a this arg (comes from a ldarg.0), and there is no starg.0. * This rules doesn't apply if the object on stack is a boxed valuetype. */ if ((method->flags & METHOD_ATTRIBUTE_VIRTUAL) && !(method->flags & METHOD_ATTRIBUTE_FINAL) && !(method->klass->flags & TYPE_ATTRIBUTE_SEALED) && !stack_slot_is_boxed_value (value)) { /*A stdarg 0 must not happen, we fail here only in fail fast mode to avoid double error reports*/ if (IS_FAIL_FAST_MODE (ctx) && ctx->has_this_store) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid ldftn with virtual function in method with stdarg 0 at 0x%04x", ctx->ip_offset)); /*current method must not be static*/ if (ctx->method->flags & METHOD_ATTRIBUTE_STATIC) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid ldftn with virtual function at 0x%04x", ctx->ip_offset)); /*value is the this pointer, loaded using ldarg.0 */ if (!stack_slot_is_this_pointer (value)) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid object argument, it is not the this pointer, to ldftn with virtual method at 0x%04x", ctx->ip_offset)); ctx->code [ctx->ip_offset].flags |= IL_CODE_LDFTN_DELEGATE_NONFINAL_VIRTUAL; } } /* * verify_delegate_compatibility: * * Verify delegate creation sequence. * */ static void verify_delegate_compatibility (VerifyContext *ctx, MonoClass *delegate, ILStackDesc *value, ILStackDesc *funptr) { #define IS_VALID_OPCODE(offset, opcode) (ip [ip_offset - offset] == opcode && (ctx->code [ip_offset - offset].flags & IL_CODE_FLAG_SEEN)) #define IS_LOAD_FUN_PTR(kind) (IS_VALID_OPCODE (6, CEE_PREFIX1) && ip [ip_offset - 5] == kind) MonoMethod *invoke, *method; const guint8 *ip = ctx->header->code; guint32 ip_offset = ctx->ip_offset; gboolean is_static_ldftn = FALSE, is_first_arg_bound = FALSE; if (stack_slot_get_type (funptr) != TYPE_PTR || !funptr->method) { CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid function pointer parameter for delegate constructor at 0x%04x", ctx->ip_offset)); return; } invoke = mono_get_delegate_invoke (delegate); method = funptr->method; if (!method || !mono_method_signature (method)) { char *name = mono_type_get_full_name (delegate); ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid method on stack to create delegate %s construction at 0x%04x", name, ctx->ip_offset)); g_free (name); return; } if (!invoke || !mono_method_signature (invoke)) { char *name = mono_type_get_full_name (delegate); ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Delegate type %s with bad Invoke method at 0x%04x", name, ctx->ip_offset)); g_free (name); return; } is_static_ldftn = (ip_offset > 5 && IS_LOAD_FUN_PTR (CEE_LDFTN)) && method->flags & METHOD_ATTRIBUTE_STATIC; if (is_static_ldftn) is_first_arg_bound = mono_method_signature (invoke)->param_count + 1 == mono_method_signature (method)->param_count; if (!mono_delegate_signature_equal (mono_method_signature (invoke), mono_method_signature (method), is_first_arg_bound)) { char *fun_sig = mono_signature_get_desc (mono_method_signature (method), FALSE); char *invoke_sig = mono_signature_get_desc (mono_method_signature (invoke), FALSE); CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Function pointer signature '%s' doesn't match delegate's signature '%s' at 0x%04x", fun_sig, invoke_sig, ctx->ip_offset)); g_free (fun_sig); g_free (invoke_sig); } /* * Delegate code sequences: * [-6] ldftn token * newobj ... * * * [-7] dup * [-6] ldvirtftn token * newobj ... * * ldftn sequence:*/ if (ip_offset > 5 && IS_LOAD_FUN_PTR (CEE_LDFTN)) { verify_ldftn_delegate (ctx, delegate, value, funptr); } else if (ip_offset > 6 && IS_VALID_OPCODE (7, CEE_DUP) && IS_LOAD_FUN_PTR (CEE_LDVIRTFTN)) { ctx->code [ip_offset - 6].flags |= IL_CODE_DELEGATE_SEQUENCE; }else { CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid code sequence for delegate creation at 0x%04x", ctx->ip_offset)); } ctx->code [ip_offset].flags |= IL_CODE_DELEGATE_SEQUENCE; //general tests if (is_first_arg_bound) { if (mono_method_signature (method)->param_count == 0 || !verify_stack_type_compatibility_full (ctx, mono_method_signature (method)->params [0], value, FALSE, TRUE)) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("This object not compatible with function pointer for delegate creation at 0x%04x", ctx->ip_offset)); } else { if (method->flags & METHOD_ATTRIBUTE_STATIC) { if (!stack_slot_is_null_literal (value) && !is_first_arg_bound) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Non-null this args used with static function for delegate creation at 0x%04x", ctx->ip_offset)); } else { if (!verify_stack_type_compatibility_full (ctx, &method->klass->byval_arg, value, FALSE, TRUE) && !stack_slot_is_null_literal (value)) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("This object not compatible with function pointer for delegate creation at 0x%04x", ctx->ip_offset)); } } if (stack_slot_get_type (value) != TYPE_COMPLEX) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid first parameter for delegate creation at 0x%04x", ctx->ip_offset)); #undef IS_VALID_OPCODE #undef IS_LOAD_FUN_PTR } /* implement the opcode checks*/ static void push_arg (VerifyContext *ctx, unsigned int arg, int take_addr) { ILStackDesc *top; if (arg >= ctx->max_args) { if (take_addr) ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Method doesn't have argument %d", arg + 1)); else { CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Method doesn't have argument %d", arg + 1)); if (check_overflow (ctx)) //FIXME: what sane value could we ever push? stack_push_val (ctx, TYPE_I4, &mono_defaults.int32_class->byval_arg); } } else if (check_overflow (ctx)) { /*We must let the value be pushed, otherwise we would get an underflow error*/ check_unverifiable_type (ctx, ctx->params [arg]); if (ctx->params [arg]->byref && take_addr) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("ByRef of ByRef at 0x%04x", ctx->ip_offset)); top = stack_push (ctx); if (!set_stack_value (ctx, top, ctx->params [arg], take_addr)) return; if (arg == 0 && !(ctx->method->flags & METHOD_ATTRIBUTE_STATIC)) { if (take_addr) ctx->has_this_store = TRUE; else top->stype |= THIS_POINTER_MASK; if (mono_method_is_constructor (ctx->method) && !ctx->super_ctor_called && !ctx->method->klass->valuetype) top->stype |= UNINIT_THIS_MASK; } } } static void push_local (VerifyContext *ctx, guint32 arg, int take_addr) { if (arg >= ctx->num_locals) { ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Method doesn't have local %d", arg + 1)); } else if (check_overflow (ctx)) { /*We must let the value be pushed, otherwise we would get an underflow error*/ check_unverifiable_type (ctx, ctx->locals [arg]); if (ctx->locals [arg]->byref && take_addr) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("ByRef of ByRef at 0x%04x", ctx->ip_offset)); set_stack_value (ctx, stack_push (ctx), ctx->locals [arg], take_addr); } } static void store_arg (VerifyContext *ctx, guint32 arg) { ILStackDesc *value; if (arg >= ctx->max_args) { CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Method doesn't have argument %d at 0x%04x", arg + 1, ctx->ip_offset)); if (check_underflow (ctx, 1)) stack_pop (ctx); return; } if (check_underflow (ctx, 1)) { value = stack_pop (ctx); if (!verify_stack_type_compatibility (ctx, ctx->params [arg], value)) { CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible type %s in argument store at 0x%04x", stack_slot_get_name (value), ctx->ip_offset)); } } if (arg == 0 && !(ctx->method->flags & METHOD_ATTRIBUTE_STATIC)) ctx->has_this_store = 1; } static void store_local (VerifyContext *ctx, guint32 arg) { ILStackDesc *value; if (arg >= ctx->num_locals) { ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Method doesn't have local var %d at 0x%04x", arg + 1, ctx->ip_offset)); return; } /*TODO verify definite assigment */ if (check_underflow (ctx, 1)) { value = stack_pop(ctx); if (!verify_stack_type_compatibility (ctx, ctx->locals [arg], value)) { char *expected = mono_type_full_name (ctx->locals [arg]); char *found = stack_slot_full_name (value); CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible type '%s' on stack cannot be stored to local %d with type '%s' at 0x%04x", found, arg, expected, ctx->ip_offset)); g_free (expected); g_free (found); } } } /*FIXME add and sub needs special care here*/ static void do_binop (VerifyContext *ctx, unsigned int opcode, const unsigned char table [TYPE_MAX][TYPE_MAX]) { ILStackDesc *a, *b, *top; int idxa, idxb, complexMerge = 0; unsigned char res; if (!check_underflow (ctx, 2)) return; b = stack_pop (ctx); a = stack_pop (ctx); idxa = stack_slot_get_underlying_type (a); if (stack_slot_is_managed_pointer (a)) { idxa = TYPE_PTR; complexMerge = 1; } idxb = stack_slot_get_underlying_type (b); if (stack_slot_is_managed_pointer (b)) { idxb = TYPE_PTR; complexMerge = 2; } --idxa; --idxb; res = table [idxa][idxb]; VERIFIER_DEBUG ( printf ("binop res %d\n", res); ); VERIFIER_DEBUG ( printf ("idxa %d idxb %d\n", idxa, idxb); ); top = stack_push (ctx); if (res == TYPE_INV) { CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Binary instruction applyed to ill formed stack (%s x %s)", stack_slot_get_name (a), stack_slot_get_name (b))); copy_stack_value (top, a); return; } if (res & NON_VERIFIABLE_RESULT) { CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Binary instruction is not verifiable (%s x %s)", stack_slot_get_name (a), stack_slot_get_name (b))); res = res & ~NON_VERIFIABLE_RESULT; } if (complexMerge && res == TYPE_PTR) { if (complexMerge == 1) copy_stack_value (top, a); else if (complexMerge == 2) copy_stack_value (top, b); /* * There is no need to merge the type of two pointers. * The only valid operation is subtraction, that returns a native * int as result and can be used with any 2 pointer kinds. * This is valid acording to Patition III 1.1.4 */ } else top->stype = res; } static void do_boolean_branch_op (VerifyContext *ctx, int delta) { int target = ctx->ip_offset + delta; ILStackDesc *top; VERIFIER_DEBUG ( printf ("boolean branch offset %d delta %d target %d\n", ctx->ip_offset, delta, target); ); if (target < 0 || target >= ctx->code_size) { ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Boolean branch target out of code at 0x%04x", ctx->ip_offset)); return; } switch (is_valid_branch_instruction (ctx->header, ctx->ip_offset, target)) { case 1: CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Branch target escapes out of exception block at 0x%04x", ctx->ip_offset)); break; case 2: ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Branch target escapes out of exception block at 0x%04x", ctx->ip_offset)); return; } ctx->target = target; if (!check_underflow (ctx, 1)) return; top = stack_pop (ctx); if (!is_valid_bool_arg (top)) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Argument type %s not valid for brtrue/brfalse at 0x%04x", stack_slot_get_name (top), ctx->ip_offset)); check_unmanaged_pointer (ctx, top); } static gboolean stack_slot_is_complex_type_not_reference_type (ILStackDesc *slot) { return stack_slot_get_type (slot) == TYPE_COMPLEX && !MONO_TYPE_IS_REFERENCE (slot->type) && !stack_slot_is_boxed_value (slot); } static void do_branch_op (VerifyContext *ctx, signed int delta, const unsigned char table [TYPE_MAX][TYPE_MAX]) { ILStackDesc *a, *b; int idxa, idxb; unsigned char res; int target = ctx->ip_offset + delta; VERIFIER_DEBUG ( printf ("branch offset %d delta %d target %d\n", ctx->ip_offset, delta, target); ); if (target < 0 || target >= ctx->code_size) { ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Branch target out of code at 0x%04x", ctx->ip_offset)); return; } switch (is_valid_cmp_branch_instruction (ctx->header, ctx->ip_offset, target)) { case 1: /*FIXME use constants and not magic numbers.*/ CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Branch target escapes out of exception block at 0x%04x", ctx->ip_offset)); break; case 2: ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Branch target escapes out of exception block at 0x%04x", ctx->ip_offset)); return; } ctx->target = target; if (!check_underflow (ctx, 2)) return; b = stack_pop (ctx); a = stack_pop (ctx); idxa = stack_slot_get_underlying_type (a); if (stack_slot_is_managed_pointer (a)) idxa = TYPE_PTR; idxb = stack_slot_get_underlying_type (b); if (stack_slot_is_managed_pointer (b)) idxb = TYPE_PTR; if (stack_slot_is_complex_type_not_reference_type (a) || stack_slot_is_complex_type_not_reference_type (b)) { res = TYPE_INV; } else { --idxa; --idxb; res = table [idxa][idxb]; } VERIFIER_DEBUG ( printf ("branch res %d\n", res); ); VERIFIER_DEBUG ( printf ("idxa %d idxb %d\n", idxa, idxb); ); if (res == TYPE_INV) { CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Compare and Branch instruction applyed to ill formed stack (%s x %s) at 0x%04x", stack_slot_get_name (a), stack_slot_get_name (b), ctx->ip_offset)); } else if (res & NON_VERIFIABLE_RESULT) { CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Compare and Branch instruction is not verifiable (%s x %s) at 0x%04x", stack_slot_get_name (a), stack_slot_get_name (b), ctx->ip_offset)); res = res & ~NON_VERIFIABLE_RESULT; } } static void do_cmp_op (VerifyContext *ctx, const unsigned char table [TYPE_MAX][TYPE_MAX], guint32 opcode) { ILStackDesc *a, *b; int idxa, idxb; unsigned char res; if (!check_underflow (ctx, 2)) return; b = stack_pop (ctx); a = stack_pop (ctx); if (opcode == CEE_CGT_UN) { if (stack_slot_get_type (a) == TYPE_COMPLEX && stack_slot_get_type (b) == TYPE_COMPLEX) { stack_push_val (ctx, TYPE_I4, &mono_defaults.int32_class->byval_arg); return; } } idxa = stack_slot_get_underlying_type (a); if (stack_slot_is_managed_pointer (a)) idxa = TYPE_PTR; idxb = stack_slot_get_underlying_type (b); if (stack_slot_is_managed_pointer (b)) idxb = TYPE_PTR; if (stack_slot_is_complex_type_not_reference_type (a) || stack_slot_is_complex_type_not_reference_type (b)) { res = TYPE_INV; } else { --idxa; --idxb; res = table [idxa][idxb]; } if(res == TYPE_INV) { CODE_NOT_VERIFIABLE (ctx, g_strdup_printf("Compare instruction applyed to ill formed stack (%s x %s) at 0x%04x", stack_slot_get_name (a), stack_slot_get_name (b), ctx->ip_offset)); } else if (res & NON_VERIFIABLE_RESULT) { CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Compare instruction is not verifiable (%s x %s) at 0x%04x", stack_slot_get_name (a), stack_slot_get_name (b), ctx->ip_offset)); res = res & ~NON_VERIFIABLE_RESULT; } stack_push_val (ctx, TYPE_I4, &mono_defaults.int32_class->byval_arg); } static void do_ret (VerifyContext *ctx) { MonoType *ret = ctx->signature->ret; VERIFIER_DEBUG ( printf ("checking ret\n"); ); if (ret->type != MONO_TYPE_VOID) { ILStackDesc *top; if (!check_underflow (ctx, 1)) return; top = stack_pop(ctx); if (!verify_stack_type_compatibility (ctx, ctx->signature->ret, top)) { CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible return value on stack with method signature ret at 0x%04x", ctx->ip_offset)); return; } if (ret->byref || ret->type == MONO_TYPE_TYPEDBYREF || mono_type_is_value_type (ret, "System", "ArgIterator") || mono_type_is_value_type (ret, "System", "RuntimeArgumentHandle")) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Method returns byref, TypedReference, ArgIterator or RuntimeArgumentHandle at 0x%04x", ctx->ip_offset)); } if (ctx->eval.size > 0) { CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Stack not empty (%d) after ret at 0x%04x", ctx->eval.size, ctx->ip_offset)); } if (in_any_block (ctx->header, ctx->ip_offset)) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("ret cannot escape exception blocks at 0x%04x", ctx->ip_offset)); } /* * FIXME we need to fix the case of a non-virtual instance method defined in the parent but call using a token pointing to a subclass. * This is illegal but mono_get_method_full decoded it. * TODO handle calling .ctor outside one or calling the .ctor for other class but super */ static void do_invoke_method (VerifyContext *ctx, int method_token, gboolean virtual) { int param_count, i; MonoMethodSignature *sig; ILStackDesc *value; MonoMethod *method; gboolean virt_check_this = FALSE; gboolean constrained = ctx->prefix_set & PREFIX_CONSTRAINED; if (!(method = verifier_load_method (ctx, method_token, virtual ? "callvirt" : "call"))) return; if (virtual) { CLEAR_PREFIX (ctx, PREFIX_CONSTRAINED); if (method->klass->valuetype) // && !constrained ??? CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use callvirtual with valuetype method at 0x%04x", ctx->ip_offset)); if ((method->flags & METHOD_ATTRIBUTE_STATIC)) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use callvirtual with static method at 0x%04x", ctx->ip_offset)); } else { if (method->flags & METHOD_ATTRIBUTE_ABSTRACT) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use call with an abstract method at 0x%04x", ctx->ip_offset)); if ((method->flags & METHOD_ATTRIBUTE_VIRTUAL) && !(method->flags & METHOD_ATTRIBUTE_FINAL) && !(method->klass->flags & TYPE_ATTRIBUTE_SEALED)) { virt_check_this = TRUE; ctx->code [ctx->ip_offset].flags |= IL_CODE_CALL_NONFINAL_VIRTUAL; } } if (!(sig = mono_method_get_signature_full (method, ctx->image, method_token, ctx->generic_context))) sig = mono_method_get_signature (method, ctx->image, method_token); if (!sig) { char *name = mono_type_get_full_name (method->klass); ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Could not resolve signature of %s:%s at 0x%04x", name, method->name, ctx->ip_offset)); g_free (name); return; } param_count = sig->param_count + sig->hasthis; if (!check_underflow (ctx, param_count)) return; for (i = sig->param_count - 1; i >= 0; --i) { VERIFIER_DEBUG ( printf ("verifying argument %d\n", i); ); value = stack_pop (ctx); if (!verify_stack_type_compatibility (ctx, sig->params[i], value)) { char *stack_name = stack_slot_full_name (value); char *sig_name = mono_type_full_name (sig->params [i]); CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible parameter with function signature: Calling method with signature (%s) but for argument %d there is a (%s) on stack at 0x%04x", sig_name, i, stack_name, ctx->ip_offset)); g_free (stack_name); g_free (sig_name); } if (stack_slot_is_managed_mutability_pointer (value)) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer as argument of %s at 0x%04x", virtual ? "callvirt" : "call", ctx->ip_offset)); if ((ctx->prefix_set & PREFIX_TAIL) && stack_slot_is_managed_pointer (value)) { ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Cannot pass a byref argument to a tail %s at 0x%04x", virtual ? "callvirt" : "call", ctx->ip_offset)); return; } } if (sig->hasthis) { MonoType *type = &method->klass->byval_arg; ILStackDesc copy; if (mono_method_is_constructor (method) && !method->klass->valuetype) { if (!mono_method_is_constructor (ctx->method)) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot call a constructor outside one at 0x%04x", ctx->ip_offset)); if (method->klass != ctx->method->klass->parent && method->klass != ctx->method->klass) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot call a constructor to a type diferent that this or super at 0x%04x", ctx->ip_offset)); ctx->super_ctor_called = TRUE; value = stack_pop_safe (ctx); if ((value->stype & THIS_POINTER_MASK) != THIS_POINTER_MASK) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid 'this ptr' argument for constructor at 0x%04x", ctx->ip_offset)); } else { value = stack_pop (ctx); } copy_stack_value (&copy, value); //TODO we should extract this to a 'drop_byref_argument' and use everywhere //Other parts of the code suffer from the same issue of copy.type = mono_type_get_type_byval (copy.type); copy.stype &= ~POINTER_MASK; if (virt_check_this && !stack_slot_is_this_pointer (value) && !(method->klass->valuetype || stack_slot_is_boxed_value (value))) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot call a non-final virtual method from an objet diferent thant the this pointer at 0x%04x", ctx->ip_offset)); if (constrained && virtual) { if (!stack_slot_is_managed_pointer (value)) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Object is not a managed pointer for a constrained call at 0x%04x", ctx->ip_offset)); if (!mono_metadata_type_equal_full (mono_type_get_type_byval (value->type), ctx->constrained_type, TRUE)) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Object not compatible with constrained type at 0x%04x", ctx->ip_offset)); copy.stype |= BOXED_MASK; } else { if (stack_slot_is_managed_pointer (value) && !mono_class_from_mono_type (value->type)->valuetype) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot call a reference type using a managed pointer to the this arg at 0x%04x", ctx->ip_offset)); if (!virtual && mono_class_from_mono_type (value->type)->valuetype && !method->klass->valuetype && !stack_slot_is_boxed_value (value)) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot call a valuetype baseclass at 0x%04x", ctx->ip_offset)); if (virtual && mono_class_from_mono_type (value->type)->valuetype && !stack_slot_is_boxed_value (value)) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a valuetype with callvirt at 0x%04x", ctx->ip_offset)); if (method->klass->valuetype && (stack_slot_is_boxed_value (value) || !stack_slot_is_managed_pointer (value))) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a boxed or literal valuetype to call a valuetype method at 0x%04x", ctx->ip_offset)); } if (!verify_stack_type_compatibility (ctx, type, &copy)) { char *expected = mono_type_full_name (type); char *effective = stack_slot_full_name (&copy); char *method_name = mono_method_full_name (method, TRUE); CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible this argument on stack with method signature expected '%s' but got '%s' for a call to '%s' at 0x%04x", expected, effective, method_name, ctx->ip_offset)); g_free (method_name); g_free (effective); g_free (expected); } if (!IS_SKIP_VISIBILITY (ctx) && !mono_method_can_access_method_full (ctx->method, method, mono_class_from_mono_type (value->type))) { char *name = mono_method_full_name (method, TRUE); CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Method %s is not accessible at 0x%04x", name, ctx->ip_offset), MONO_EXCEPTION_METHOD_ACCESS); g_free (name); } } else if (!IS_SKIP_VISIBILITY (ctx) && !mono_method_can_access_method_full (ctx->method, method, NULL)) { char *name = mono_method_full_name (method, TRUE); CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Method %s is not accessible at 0x%04x", name, ctx->ip_offset), MONO_EXCEPTION_METHOD_ACCESS); g_free (name); } if (sig->ret->type != MONO_TYPE_VOID) { if (check_overflow (ctx)) { value = stack_push (ctx); set_stack_value (ctx, value, sig->ret, FALSE); if ((ctx->prefix_set & PREFIX_READONLY) && method->klass->rank && !strcmp (method->name, "Address")) { ctx->prefix_set &= ~PREFIX_READONLY; value->stype |= CMMP_MASK; } } } if ((ctx->prefix_set & PREFIX_TAIL)) { if (!mono_delegate_ret_equal (mono_method_signature (ctx->method)->ret, sig->ret)) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Tail call with incompatible return type at 0x%04x", ctx->ip_offset)); if (ctx->header->code [ctx->ip_offset + 5] != CEE_RET) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Tail call not followed by ret at 0x%04x", ctx->ip_offset)); } } static void do_push_static_field (VerifyContext *ctx, int token, gboolean take_addr) { MonoClassField *field; MonoClass *klass; if (!check_overflow (ctx)) return; if (!take_addr) CLEAR_PREFIX (ctx, PREFIX_VOLATILE); if (!(field = verifier_load_field (ctx, token, &klass, take_addr ? "ldsflda" : "ldsfld"))) return; if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) { ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Cannot load non static field at 0x%04x", ctx->ip_offset)); return; } /*taking the address of initonly field only works from the static constructor */ if (take_addr && (field->type->attrs & FIELD_ATTRIBUTE_INIT_ONLY) && !(field->parent == ctx->method->klass && (ctx->method->flags & (METHOD_ATTRIBUTE_SPECIAL_NAME | METHOD_ATTRIBUTE_STATIC)) && !strcmp (".cctor", ctx->method->name))) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot take the address of a init-only field at 0x%04x", ctx->ip_offset)); if (!IS_SKIP_VISIBILITY (ctx) && !mono_method_can_access_field_full (ctx->method, field, NULL)) CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Type at stack is not accessible at 0x%04x", ctx->ip_offset), MONO_EXCEPTION_FIELD_ACCESS); set_stack_value (ctx, stack_push (ctx), field->type, take_addr); } static void do_store_static_field (VerifyContext *ctx, int token) { MonoClassField *field; MonoClass *klass; ILStackDesc *value; CLEAR_PREFIX (ctx, PREFIX_VOLATILE); if (!check_underflow (ctx, 1)) return; value = stack_pop (ctx); if (!(field = verifier_load_field (ctx, token, &klass, "stsfld"))) return; if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) { ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Cannot store non static field at 0x%04x", ctx->ip_offset)); return; } if (field->type->type == MONO_TYPE_TYPEDBYREF) { ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Typedbyref field is an unverfiable type in store static field at 0x%04x", ctx->ip_offset)); return; } if (!IS_SKIP_VISIBILITY (ctx) && !mono_method_can_access_field_full (ctx->method, field, NULL)) CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Type at stack is not accessible at 0x%04x", ctx->ip_offset), MONO_EXCEPTION_FIELD_ACCESS); if (!verify_stack_type_compatibility (ctx, field->type, value)) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible type %s in static field store at 0x%04x", stack_slot_get_name (value), ctx->ip_offset)); } static gboolean check_is_valid_type_for_field_ops (VerifyContext *ctx, int token, ILStackDesc *obj, MonoClassField **ret_field, const char *opcode) { MonoClassField *field; MonoClass *klass; gboolean is_pointer; /*must be a reference type, a managed pointer, an unamanaged pointer, or a valuetype*/ if (!(field = verifier_load_field (ctx, token, &klass, opcode))) return FALSE; *ret_field = field; //the value on stack is going to be used as a pointer is_pointer = stack_slot_get_type (obj) == TYPE_PTR || (stack_slot_get_type (obj) == TYPE_NATIVE_INT && !get_stack_type (&field->parent->byval_arg)); if (field->type->type == MONO_TYPE_TYPEDBYREF) { ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Typedbyref field is an unverfiable type at 0x%04x", ctx->ip_offset)); return FALSE; } g_assert (obj->type); /*The value on the stack must be a subclass of the defining type of the field*/ /* we need to check if we can load the field from the stack value*/ if (is_pointer) { if (stack_slot_get_underlying_type (obj) == TYPE_NATIVE_INT) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Native int is not a verifiable type to reference a field at 0x%04x", ctx->ip_offset)); if (!IS_SKIP_VISIBILITY (ctx) && !mono_method_can_access_field_full (ctx->method, field, NULL)) CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Type at stack is not accessible at 0x%04x", ctx->ip_offset), MONO_EXCEPTION_FIELD_ACCESS); } else { if (!field->parent->valuetype && stack_slot_is_managed_pointer (obj)) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Type at stack is a managed pointer to a reference type and is not compatible to reference the field at 0x%04x", ctx->ip_offset)); /*a value type can be loaded from a value or a managed pointer, but not a boxed object*/ if (field->parent->valuetype && stack_slot_is_boxed_value (obj)) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Type at stack is a boxed valuetype and is not compatible to reference the field at 0x%04x", ctx->ip_offset)); if (!stack_slot_is_null_literal (obj) && !verify_stack_type_compatibility_full (ctx, &field->parent->byval_arg, obj, TRUE, FALSE)) { char *found = stack_slot_full_name (obj); char *expected = mono_type_full_name (&field->parent->byval_arg); CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Expected type '%s' but found '%s' referencing the 'this' argument at 0x%04x", expected, found, ctx->ip_offset)); g_free (found); g_free (expected); } if (!IS_SKIP_VISIBILITY (ctx) && !mono_method_can_access_field_full (ctx->method, field, mono_class_from_mono_type (obj->type))) CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Type at stack is not accessible at 0x%04x", ctx->ip_offset), MONO_EXCEPTION_FIELD_ACCESS); } check_unmanaged_pointer (ctx, obj); return TRUE; } static void do_push_field (VerifyContext *ctx, int token, gboolean take_addr) { ILStackDesc *obj; MonoClassField *field; if (!take_addr) CLEAR_PREFIX (ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE); if (!check_underflow (ctx, 1)) return; obj = stack_pop_safe (ctx); if (!check_is_valid_type_for_field_ops (ctx, token, obj, &field, take_addr ? "ldflda" : "ldfld")) return; if (take_addr && field->parent->valuetype && !stack_slot_is_managed_pointer (obj)) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot take the address of a temporary value-type at 0x%04x", ctx->ip_offset)); if (take_addr && (field->type->attrs & FIELD_ATTRIBUTE_INIT_ONLY) && !(field->parent == ctx->method->klass && mono_method_is_constructor (ctx->method))) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot take the address of a init-only field at 0x%04x", ctx->ip_offset)); set_stack_value (ctx, stack_push (ctx), field->type, take_addr); } static void do_store_field (VerifyContext *ctx, int token) { ILStackDesc *value, *obj; MonoClassField *field; CLEAR_PREFIX (ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE); if (!check_underflow (ctx, 2)) return; value = stack_pop (ctx); obj = stack_pop_safe (ctx); if (!check_is_valid_type_for_field_ops (ctx, token, obj, &field, "stfld")) return; if (!verify_stack_type_compatibility (ctx, field->type, value)) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible type %s in field store at 0x%04x", stack_slot_get_name (value), ctx->ip_offset)); } /*TODO proper handle for Nullable<T>*/ static void do_box_value (VerifyContext *ctx, int klass_token) { ILStackDesc *value; MonoType *type = get_boxable_mono_type (ctx, klass_token, "box"); MonoClass *klass; if (!type) return; if (!check_underflow (ctx, 1)) return; value = stack_pop (ctx); /*box is a nop for reference types*/ if (stack_slot_get_underlying_type (value) == TYPE_COMPLEX && MONO_TYPE_IS_REFERENCE (value->type) && MONO_TYPE_IS_REFERENCE (type)) { stack_push_stack_val (ctx, value)->stype |= BOXED_MASK; return; } if (!verify_stack_type_compatibility (ctx, type, value)) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type at stack for boxing operation at 0x%04x", ctx->ip_offset)); klass = mono_class_from_mono_type (type); if (mono_class_is_nullable (klass)) type = &mono_class_get_nullable_param (klass)->byval_arg; stack_push_val (ctx, TYPE_COMPLEX | BOXED_MASK, type); } static void do_unbox_value (VerifyContext *ctx, int klass_token) { ILStackDesc *value; MonoType *type = get_boxable_mono_type (ctx, klass_token, "unbox"); if (!type) return; if (!check_underflow (ctx, 1)) return; if (!mono_class_from_mono_type (type)->valuetype) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid reference type for unbox at 0x%04x", ctx->ip_offset)); value = stack_pop (ctx); /*Value should be: a boxed valuetype or a reference type*/ if (!(stack_slot_get_type (value) == TYPE_COMPLEX && (stack_slot_is_boxed_value (value) || !mono_class_from_mono_type (value->type)->valuetype))) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type %s at stack for unbox operation at 0x%04x", stack_slot_get_name (value), ctx->ip_offset)); set_stack_value (ctx, value = stack_push (ctx), mono_type_get_type_byref (type), FALSE); value->stype |= CMMP_MASK; } static void do_unbox_any (VerifyContext *ctx, int klass_token) { ILStackDesc *value; MonoType *type = get_boxable_mono_type (ctx, klass_token, "unbox.any"); if (!type) return; if (!check_underflow (ctx, 1)) return; value = stack_pop (ctx); /*Value should be: a boxed valuetype or a reference type*/ if (!(stack_slot_get_type (value) == TYPE_COMPLEX && (stack_slot_is_boxed_value (value) || !mono_class_from_mono_type (value->type)->valuetype))) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type %s at stack for unbox.any operation at 0x%04x", stack_slot_get_name (value), ctx->ip_offset)); set_stack_value (ctx, stack_push (ctx), type, FALSE); } static void do_unary_math_op (VerifyContext *ctx, int op) { ILStackDesc *value; if (!check_underflow (ctx, 1)) return; value = stack_pop (ctx); switch (stack_slot_get_type (value)) { case TYPE_I4: case TYPE_I8: case TYPE_NATIVE_INT: break; case TYPE_R8: if (op == CEE_NEG) break; case TYPE_COMPLEX: /*only enums are ok*/ if (mono_type_is_enum_type (value->type)) break; default: CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type at stack for unary not at 0x%04x", ctx->ip_offset)); } stack_push_stack_val (ctx, value); } static void do_conversion (VerifyContext *ctx, int kind) { ILStackDesc *value; if (!check_underflow (ctx, 1)) return; value = stack_pop (ctx); switch (stack_slot_get_type (value)) { case TYPE_I4: case TYPE_I8: case TYPE_NATIVE_INT: case TYPE_R8: break; default: CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type (%s) at stack for conversion operation. Numeric type expected at 0x%04x", stack_slot_get_name (value), ctx->ip_offset)); } switch (kind) { case TYPE_I4: stack_push_val (ctx, TYPE_I4, &mono_defaults.int32_class->byval_arg); break; case TYPE_I8: stack_push_val (ctx,TYPE_I8, &mono_defaults.int64_class->byval_arg); break; case TYPE_R8: stack_push_val (ctx, TYPE_R8, &mono_defaults.double_class->byval_arg); break; case TYPE_NATIVE_INT: stack_push_val (ctx, TYPE_NATIVE_INT, &mono_defaults.int_class->byval_arg); break; default: g_error ("unknown type %02x in conversion", kind); } } static void do_load_token (VerifyContext *ctx, int token) { gpointer handle; MonoClass *handle_class; if (!check_overflow (ctx)) return; switch (token & 0xff000000) { case MONO_TOKEN_TYPE_DEF: case MONO_TOKEN_TYPE_REF: case MONO_TOKEN_TYPE_SPEC: case MONO_TOKEN_FIELD_DEF: case MONO_TOKEN_METHOD_DEF: case MONO_TOKEN_METHOD_SPEC: case MONO_TOKEN_MEMBER_REF: if (!token_bounds_check (ctx->image, token)) { ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Table index out of range 0x%x for token %x for ldtoken at 0x%04x", mono_metadata_token_index (token), token, ctx->ip_offset)); return; } break; default: ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid table 0x%x for token 0x%x for ldtoken at 0x%04x", mono_metadata_token_table (token), token, ctx->ip_offset)); return; } handle = mono_ldtoken (ctx->image, token, &handle_class, ctx->generic_context); if (!handle) { ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid token 0x%x for ldtoken at 0x%04x", token, ctx->ip_offset)); return; } if (handle_class == mono_defaults.typehandle_class) { mono_type_is_valid_in_context (ctx, (MonoType*)handle); } else if (handle_class == mono_defaults.methodhandle_class) { mono_method_is_valid_in_context (ctx, (MonoMethod*)handle); } else if (handle_class == mono_defaults.fieldhandle_class) { mono_type_is_valid_in_context (ctx, &((MonoClassField*)handle)->parent->byval_arg); } else { ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid ldtoken type %x at 0x%04x", token, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE); } stack_push_val (ctx, TYPE_COMPLEX, mono_class_get_type (handle_class)); } static void do_ldobj_value (VerifyContext *ctx, int token) { ILStackDesc *value; MonoType *type = get_boxable_mono_type (ctx, token, "ldobj"); CLEAR_PREFIX (ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE); if (!type) return; if (!check_underflow (ctx, 1)) return; value = stack_pop (ctx); if (!stack_slot_is_managed_pointer (value) && stack_slot_get_type (value) != TYPE_NATIVE_INT && !(stack_slot_get_type (value) == TYPE_PTR && value->type->type != MONO_TYPE_FNPTR)) { ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid argument %s to ldobj at 0x%04x", stack_slot_get_name (value), ctx->ip_offset)); return; } if (stack_slot_get_type (value) == TYPE_NATIVE_INT) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Using native pointer to ldobj at 0x%04x", ctx->ip_offset)); /*We have a byval on the stack, but the comparison must be strict. */ if (!verify_type_compatibility_full (ctx, type, mono_type_get_type_byval (value->type), TRUE)) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type at stack for ldojb operation at 0x%04x", ctx->ip_offset)); set_stack_value (ctx, stack_push (ctx), type, FALSE); } static void do_stobj (VerifyContext *ctx, int token) { ILStackDesc *dest, *src; MonoType *type = get_boxable_mono_type (ctx, token, "stobj"); CLEAR_PREFIX (ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE); if (!type) return; if (!check_underflow (ctx, 2)) return; src = stack_pop (ctx); dest = stack_pop (ctx); if (stack_slot_is_managed_mutability_pointer (dest)) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer with stobj at 0x%04x", ctx->ip_offset)); if (!stack_slot_is_managed_pointer (dest)) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid destination of stobj operation at 0x%04x", ctx->ip_offset)); if (stack_slot_is_boxed_value (src) && !MONO_TYPE_IS_REFERENCE (src->type) && !MONO_TYPE_IS_REFERENCE (type)) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use stobj with a boxed source value that is not a reference type at 0x%04x", ctx->ip_offset)); if (!verify_stack_type_compatibility (ctx, type, src)) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Token and source types of stobj don't match at 0x%04x", ctx->ip_offset)); if (!verify_type_compatibility (ctx, mono_type_get_type_byval (dest->type), type)) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Destination and token types of stobj don't match at 0x%04x", ctx->ip_offset)); } static void do_cpobj (VerifyContext *ctx, int token) { ILStackDesc *dest, *src; MonoType *type = get_boxable_mono_type (ctx, token, "cpobj"); if (!type) return; if (!check_underflow (ctx, 2)) return; src = stack_pop (ctx); dest = stack_pop (ctx); if (!stack_slot_is_managed_pointer (src)) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid source of cpobj operation at 0x%04x", ctx->ip_offset)); if (!stack_slot_is_managed_pointer (dest)) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid destination of cpobj operation at 0x%04x", ctx->ip_offset)); if (stack_slot_is_managed_mutability_pointer (dest)) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer with cpobj at 0x%04x", ctx->ip_offset)); if (!verify_type_compatibility (ctx, type, mono_type_get_type_byval (src->type))) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Token and source types of cpobj don't match at 0x%04x", ctx->ip_offset)); if (!verify_type_compatibility (ctx, mono_type_get_type_byval (dest->type), type)) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Destination and token types of cpobj don't match at 0x%04x", ctx->ip_offset)); } static void do_initobj (VerifyContext *ctx, int token) { ILStackDesc *obj; MonoType *stack, *type = get_boxable_mono_type (ctx, token, "initobj"); if (!type) return; if (!check_underflow (ctx, 1)) return; obj = stack_pop (ctx); if (!stack_slot_is_managed_pointer (obj)) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid object address for initobj at 0x%04x", ctx->ip_offset)); if (stack_slot_is_managed_mutability_pointer (obj)) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer with initobj at 0x%04x", ctx->ip_offset)); stack = mono_type_get_type_byval (obj->type); if (MONO_TYPE_IS_REFERENCE (stack)) { if (!verify_type_compatibility (ctx, stack, type)) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Type token of initobj not compatible with value on stack at 0x%04x", ctx->ip_offset)); else if (IS_STRICT_MODE (ctx) && !mono_metadata_type_equal (type, stack)) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Type token of initobj not compatible with value on stack at 0x%04x", ctx->ip_offset)); } else if (!verify_type_compatibility (ctx, stack, type)) { char *expected_name = mono_type_full_name (type); char *stack_name = mono_type_full_name (stack); CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Initobj %s not compatible with value on stack %s at 0x%04x", expected_name, stack_name, ctx->ip_offset)); g_free (expected_name); g_free (stack_name); } } static void do_newobj (VerifyContext *ctx, int token) { ILStackDesc *value; int i; MonoMethodSignature *sig; MonoMethod *method; gboolean is_delegate = FALSE; if (!(method = verifier_load_method (ctx, token, "newobj"))) return; if (!mono_method_is_constructor (method)) { ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Method from token 0x%08x not a constructor at 0x%04x", token, ctx->ip_offset)); return; } if (method->klass->flags & (TYPE_ATTRIBUTE_ABSTRACT | TYPE_ATTRIBUTE_INTERFACE)) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Trying to instantiate an abstract or interface type at 0x%04x", ctx->ip_offset)); if (!mono_method_can_access_method_full (ctx->method, method, NULL)) { char *from = mono_method_full_name (ctx->method, TRUE); char *to = mono_method_full_name (method, TRUE); CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Constructor %s not visible from %s at 0x%04x", to, from, ctx->ip_offset), MONO_EXCEPTION_METHOD_ACCESS); g_free (from); g_free (to); } //FIXME use mono_method_get_signature_full sig = mono_method_signature (method); if (!sig) { ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid constructor signature to newobj at 0x%04x", ctx->ip_offset)); return; } if (!check_underflow (ctx, sig->param_count)) return; is_delegate = method->klass->parent == mono_defaults.multicastdelegate_class; if (is_delegate) { ILStackDesc *funptr; //first arg is object, second arg is fun ptr if (sig->param_count != 2) { ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid delegate constructor at 0x%04x", ctx->ip_offset)); return; } funptr = stack_pop (ctx); value = stack_pop (ctx); verify_delegate_compatibility (ctx, method->klass, value, funptr); } else { for (i = sig->param_count - 1; i >= 0; --i) { VERIFIER_DEBUG ( printf ("verifying constructor argument %d\n", i); ); value = stack_pop (ctx); if (!verify_stack_type_compatibility (ctx, sig->params [i], value)) { char *stack_name = stack_slot_full_name (value); char *sig_name = mono_type_full_name (sig->params [i]); CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible parameter value with constructor signature: %s X %s at 0x%04x", sig_name, stack_name, ctx->ip_offset)); g_free (stack_name); g_free (sig_name); } if (stack_slot_is_managed_mutability_pointer (value)) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer as argument of newobj at 0x%04x", ctx->ip_offset)); } } if (check_overflow (ctx)) set_stack_value (ctx, stack_push (ctx), &method->klass->byval_arg, FALSE); } static void do_cast (VerifyContext *ctx, int token, const char *opcode) { ILStackDesc *value; MonoType *type; gboolean is_boxed; gboolean do_box; if (!check_underflow (ctx, 1)) return; if (!(type = verifier_load_type (ctx, token, opcode))) return; if (type->byref) { ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid %s type at 0x%04x", opcode, ctx->ip_offset)); return; } value = stack_pop (ctx); is_boxed = stack_slot_is_boxed_value (value); if (stack_slot_is_managed_pointer (value)) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid value for %s at 0x%04x", opcode, ctx->ip_offset)); else if (!MONO_TYPE_IS_REFERENCE (value->type) && !is_boxed) { char *name = stack_slot_full_name (value); CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Expected a reference type on stack for %s but found %s at 0x%04x", opcode, name, ctx->ip_offset)); g_free (name); } switch (value->type->type) { case MONO_TYPE_FNPTR: case MONO_TYPE_PTR: case MONO_TYPE_TYPEDBYREF: CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid value for %s at 0x%04x", opcode, ctx->ip_offset)); } do_box = is_boxed || mono_type_is_generic_argument(type) || mono_class_from_mono_type (type)->valuetype; stack_push_val (ctx, TYPE_COMPLEX | (do_box ? BOXED_MASK : 0), type); } static MonoType * mono_type_from_opcode (int opcode) { switch (opcode) { case CEE_LDIND_I1: case CEE_LDIND_U1: case CEE_STIND_I1: case CEE_LDELEM_I1: case CEE_LDELEM_U1: case CEE_STELEM_I1: return &mono_defaults.sbyte_class->byval_arg; case CEE_LDIND_I2: case CEE_LDIND_U2: case CEE_STIND_I2: case CEE_LDELEM_I2: case CEE_LDELEM_U2: case CEE_STELEM_I2: return &mono_defaults.int16_class->byval_arg; case CEE_LDIND_I4: case CEE_LDIND_U4: case CEE_STIND_I4: case CEE_LDELEM_I4: case CEE_LDELEM_U4: case CEE_STELEM_I4: return &mono_defaults.int32_class->byval_arg; case CEE_LDIND_I8: case CEE_STIND_I8: case CEE_LDELEM_I8: case CEE_STELEM_I8: return &mono_defaults.int64_class->byval_arg; case CEE_LDIND_R4: case CEE_STIND_R4: case CEE_LDELEM_R4: case CEE_STELEM_R4: return &mono_defaults.single_class->byval_arg; case CEE_LDIND_R8: case CEE_STIND_R8: case CEE_LDELEM_R8: case CEE_STELEM_R8: return &mono_defaults.double_class->byval_arg; case CEE_LDIND_I: case CEE_STIND_I: case CEE_LDELEM_I: case CEE_STELEM_I: return &mono_defaults.int_class->byval_arg; case CEE_LDIND_REF: case CEE_STIND_REF: case CEE_LDELEM_REF: case CEE_STELEM_REF: return &mono_defaults.object_class->byval_arg; default: g_error ("unknown opcode %02x in mono_type_from_opcode ", opcode); return NULL; } } static void do_load_indirect (VerifyContext *ctx, int opcode) { ILStackDesc *value; CLEAR_PREFIX (ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE); if (!check_underflow (ctx, 1)) return; value = stack_pop (ctx); if (!stack_slot_is_managed_pointer (value)) { CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Load indirect not using a manager pointer at 0x%04x", ctx->ip_offset)); set_stack_value (ctx, stack_push (ctx), mono_type_from_opcode (opcode), FALSE); return; } if (opcode == CEE_LDIND_REF) { if (stack_slot_get_underlying_type (value) != TYPE_COMPLEX || mono_class_from_mono_type (value->type)->valuetype) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type at stack for ldind_ref expected object byref operation at 0x%04x", ctx->ip_offset)); set_stack_value (ctx, stack_push (ctx), mono_type_get_type_byval (value->type), FALSE); } else { if (!verify_type_compatibility_full (ctx, mono_type_from_opcode (opcode), mono_type_get_type_byval (value->type), TRUE)) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type at stack for ldind 0x%x operation at 0x%04x", opcode, ctx->ip_offset)); set_stack_value (ctx, stack_push (ctx), mono_type_from_opcode (opcode), FALSE); } } static void do_store_indirect (VerifyContext *ctx, int opcode) { ILStackDesc *addr, *val; CLEAR_PREFIX (ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE); if (!check_underflow (ctx, 2)) return; val = stack_pop (ctx); addr = stack_pop (ctx); check_unmanaged_pointer (ctx, addr); if (!stack_slot_is_managed_pointer (addr) && stack_slot_get_type (addr) != TYPE_PTR) { CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid non-pointer argument to stind at 0x%04x", ctx->ip_offset)); return; } if (stack_slot_is_managed_mutability_pointer (addr)) { CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer with stind at 0x%04x", ctx->ip_offset)); return; } if (!verify_type_compatibility_full (ctx, mono_type_from_opcode (opcode), mono_type_get_type_byval (addr->type), TRUE)) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid addr type at stack for stind 0x%x operation at 0x%04x", opcode, ctx->ip_offset)); if (!verify_stack_type_compatibility (ctx, mono_type_from_opcode (opcode), val)) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid value type at stack for stind 0x%x operation at 0x%04x", opcode, ctx->ip_offset)); } static void do_newarr (VerifyContext *ctx, int token) { ILStackDesc *value; MonoType *type = get_boxable_mono_type (ctx, token, "newarr"); if (!type) return; if (!check_underflow (ctx, 1)) return; value = stack_pop (ctx); if (stack_slot_get_type (value) != TYPE_I4 && stack_slot_get_type (value) != TYPE_NATIVE_INT) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Array size type on stack (%s) is not a verifiable type at 0x%04x", stack_slot_get_name (value), ctx->ip_offset)); set_stack_value (ctx, stack_push (ctx), mono_class_get_type (mono_array_class_get (mono_class_from_mono_type (type), 1)), FALSE); } /*FIXME handle arrays that are not 0-indexed*/ static void do_ldlen (VerifyContext *ctx) { ILStackDesc *value; if (!check_underflow (ctx, 1)) return; value = stack_pop (ctx); if (stack_slot_get_type (value) != TYPE_COMPLEX || value->type->type != MONO_TYPE_SZARRAY) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type for ldlen at 0x%04x", ctx->ip_offset)); stack_push_val (ctx, TYPE_NATIVE_INT, &mono_defaults.int_class->byval_arg); } /*FIXME handle arrays that are not 0-indexed*/ /*FIXME handle readonly prefix and CMMP*/ static void do_ldelema (VerifyContext *ctx, int klass_token) { ILStackDesc *index, *array, *res; MonoType *type = get_boxable_mono_type (ctx, klass_token, "ldelema"); gboolean valid; if (!type) return; if (!check_underflow (ctx, 2)) return; index = stack_pop (ctx); array = stack_pop (ctx); if (stack_slot_get_type (index) != TYPE_I4 && stack_slot_get_type (index) != TYPE_NATIVE_INT) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Index type(%s) for ldelema is not an int or a native int at 0x%04x", stack_slot_get_name (index), ctx->ip_offset)); if (!stack_slot_is_null_literal (array)) { if (stack_slot_get_type (array) != TYPE_COMPLEX || array->type->type != MONO_TYPE_SZARRAY) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type(%s) for ldelema at 0x%04x", stack_slot_get_name (array), ctx->ip_offset)); else { if (get_stack_type (type) == TYPE_I4 || get_stack_type (type) == TYPE_NATIVE_INT) { valid = verify_type_compatibility_full (ctx, type, &array->type->data.klass->byval_arg, TRUE); } else { valid = mono_metadata_type_equal (type, &array->type->data.klass->byval_arg); } if (!valid) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type on stack for ldelema at 0x%04x", ctx->ip_offset)); } } res = stack_push (ctx); set_stack_value (ctx, res, type, TRUE); if (ctx->prefix_set & PREFIX_READONLY) { ctx->prefix_set &= ~PREFIX_READONLY; res->stype |= CMMP_MASK; } } /* * FIXME handle arrays that are not 0-indexed * FIXME handle readonly prefix and CMMP */ static void do_ldelem (VerifyContext *ctx, int opcode, int token) { #define IS_ONE_OF2(T, A, B) (T == A || T == B) ILStackDesc *index, *array; MonoType *type; if (!check_underflow (ctx, 2)) return; if (opcode == CEE_LDELEM) { if (!(type = verifier_load_type (ctx, token, "ldelem.any"))) { ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Type (0x%08x) not found at 0x%04x", token, ctx->ip_offset)); return; } } else { type = mono_type_from_opcode (opcode); } index = stack_pop (ctx); array = stack_pop (ctx); if (stack_slot_get_type (index) != TYPE_I4 && stack_slot_get_type (index) != TYPE_NATIVE_INT) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Index type(%s) for ldelem.X is not an int or a native int at 0x%04x", stack_slot_get_name (index), ctx->ip_offset)); if (!stack_slot_is_null_literal (array)) { if (stack_slot_get_type (array) != TYPE_COMPLEX || array->type->type != MONO_TYPE_SZARRAY) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type(%s) for ldelem.X at 0x%04x", stack_slot_get_name (array), ctx->ip_offset)); else { if (opcode == CEE_LDELEM_REF) { if (array->type->data.klass->valuetype) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type is not a reference type for ldelem.ref 0x%04x", ctx->ip_offset)); type = &array->type->data.klass->byval_arg; } else { MonoType *candidate = &array->type->data.klass->byval_arg; if (IS_STRICT_MODE (ctx)) { MonoType *underlying_type = mono_type_get_underlying_type_any (type); MonoType *underlying_candidate = mono_type_get_underlying_type_any (candidate); if ((IS_ONE_OF2 (underlying_type->type, MONO_TYPE_I4, MONO_TYPE_U4) && IS_ONE_OF2 (underlying_candidate->type, MONO_TYPE_I, MONO_TYPE_U)) || (IS_ONE_OF2 (underlying_candidate->type, MONO_TYPE_I4, MONO_TYPE_U4) && IS_ONE_OF2 (underlying_type->type, MONO_TYPE_I, MONO_TYPE_U))) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type on stack for ldelem.X at 0x%04x", ctx->ip_offset)); } if (!verify_type_compatibility_full (ctx, type, candidate, TRUE)) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type on stack for ldelem.X at 0x%04x", ctx->ip_offset)); } } } set_stack_value (ctx, stack_push (ctx), type, FALSE); #undef IS_ONE_OF2 } /* * FIXME handle arrays that are not 0-indexed */ static void do_stelem (VerifyContext *ctx, int opcode, int token) { ILStackDesc *index, *array, *value; MonoType *type; if (!check_underflow (ctx, 3)) return; if (opcode == CEE_STELEM) { if (!(type = verifier_load_type (ctx, token, "stelem.any"))) { ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Type (0x%08x) not found at 0x%04x", token, ctx->ip_offset)); return; } } else { type = mono_type_from_opcode (opcode); } value = stack_pop (ctx); index = stack_pop (ctx); array = stack_pop (ctx); if (stack_slot_get_type (index) != TYPE_I4 && stack_slot_get_type (index) != TYPE_NATIVE_INT) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Index type(%s) for stdelem.X is not an int or a native int at 0x%04x", stack_slot_get_name (index), ctx->ip_offset)); if (!stack_slot_is_null_literal (array)) { if (stack_slot_get_type (array) != TYPE_COMPLEX || array->type->type != MONO_TYPE_SZARRAY) { CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type(%s) for stelem.X at 0x%04x", stack_slot_get_name (array), ctx->ip_offset)); } else { if (opcode == CEE_STELEM_REF) { if (array->type->data.klass->valuetype) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type is not a reference type for stelem.ref 0x%04x", ctx->ip_offset)); } else if (!verify_type_compatibility_full (ctx, &array->type->data.klass->byval_arg, type, TRUE)) { CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type on stack for stdelem.X at 0x%04x", ctx->ip_offset)); } } } if (opcode == CEE_STELEM_REF) { if (!stack_slot_is_boxed_value (value) && mono_class_from_mono_type (value->type)->valuetype) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid value is not a reference type for stelem.ref 0x%04x", ctx->ip_offset)); } else if (opcode != CEE_STELEM_REF) { if (!verify_stack_type_compatibility (ctx, type, value)) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid value on stack for stdelem.X at 0x%04x", ctx->ip_offset)); if (stack_slot_is_boxed_value (value) && !MONO_TYPE_IS_REFERENCE (value->type) && !MONO_TYPE_IS_REFERENCE (type)) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use stobj with a boxed source value that is not a reference type at 0x%04x", ctx->ip_offset)); } } static void do_throw (VerifyContext *ctx) { ILStackDesc *exception; if (!check_underflow (ctx, 1)) return; exception = stack_pop (ctx); if (!stack_slot_is_null_literal (exception) && !(stack_slot_get_type (exception) == TYPE_COMPLEX && !mono_class_from_mono_type (exception->type)->valuetype)) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type on stack for throw, expected reference type at 0x%04x", ctx->ip_offset)); if (mono_type_is_generic_argument (exception->type) && !stack_slot_is_boxed_value (exception)) { char *name = mono_type_full_name (exception->type); CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type on stack for throw, expected reference type but found unboxed %s at 0x%04x ", name, ctx->ip_offset)); g_free (name); } /*The stack is left empty after a throw*/ ctx->eval.size = 0; } static void do_endfilter (VerifyContext *ctx) { MonoExceptionClause *clause; if (IS_STRICT_MODE (ctx)) { if (ctx->eval.size != 1) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Stack size must have one item for endfilter at 0x%04x", ctx->ip_offset)); if (ctx->eval.size >= 1 && stack_slot_get_type (stack_pop (ctx)) != TYPE_I4) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Stack item type is not an int32 for endfilter at 0x%04x", ctx->ip_offset)); } if ((clause = is_correct_endfilter (ctx, ctx->ip_offset))) { if (IS_STRICT_MODE (ctx)) { if (ctx->ip_offset != clause->handler_offset - 2) ADD_VERIFY_ERROR (ctx, g_strdup_printf ("endfilter is not the last instruction of the filter clause at 0x%04x", ctx->ip_offset)); } else { if ((ctx->ip_offset != clause->handler_offset - 2) && !MONO_OFFSET_IN_HANDLER (clause, ctx->ip_offset)) ADD_VERIFY_ERROR (ctx, g_strdup_printf ("endfilter is not the last instruction of the filter clause at 0x%04x", ctx->ip_offset)); } } else { if (IS_STRICT_MODE (ctx) && !is_unverifiable_endfilter (ctx, ctx->ip_offset)) ADD_VERIFY_ERROR (ctx, g_strdup_printf ("endfilter outside filter clause at 0x%04x", ctx->ip_offset)); else CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("endfilter outside filter clause at 0x%04x", ctx->ip_offset)); } ctx->eval.size = 0; } static void do_leave (VerifyContext *ctx, int delta) { int target = ((gint32)ctx->ip_offset) + delta; if (target >= ctx->code_size || target < 0) ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Branch target out of code at 0x%04x", ctx->ip_offset)); if (!is_correct_leave (ctx->header, ctx->ip_offset, target)) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Leave not allowed in finally block at 0x%04x", ctx->ip_offset)); ctx->eval.size = 0; ctx->target = target; } /* * do_static_branch: * * Verify br and br.s opcodes. */ static void do_static_branch (VerifyContext *ctx, int delta) { int target = ctx->ip_offset + delta; if (target < 0 || target >= ctx->code_size) { ADD_VERIFY_ERROR (ctx, g_strdup_printf ("branch target out of code at 0x%04x", ctx->ip_offset)); return; } switch (is_valid_branch_instruction (ctx->header, ctx->ip_offset, target)) { case 1: CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Branch target escapes out of exception block at 0x%04x", ctx->ip_offset)); break; case 2: ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Branch target escapes out of exception block at 0x%04x", ctx->ip_offset)); break; } ctx->target = target; } static void do_switch (VerifyContext *ctx, int count, const unsigned char *data) { int i, base = ctx->ip_offset + 5 + count * 4; ILStackDesc *value; if (!check_underflow (ctx, 1)) return; value = stack_pop (ctx); if (stack_slot_get_type (value) != TYPE_I4 && stack_slot_get_type (value) != TYPE_NATIVE_INT) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid argument to switch at 0x%04x", ctx->ip_offset)); for (i = 0; i < count; ++i) { int target = base + read32 (data + i * 4); if (target < 0 || target >= ctx->code_size) { ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Switch target %x out of code at 0x%04x", i, ctx->ip_offset)); return; } switch (is_valid_branch_instruction (ctx->header, ctx->ip_offset, target)) { case 1: CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Switch target %x escapes out of exception block at 0x%04x", i, ctx->ip_offset)); break; case 2: ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Switch target %x escapes out of exception block at 0x%04x", i, ctx->ip_offset)); return; } merge_stacks (ctx, &ctx->eval, &ctx->code [target], FALSE, TRUE); } } static void do_load_function_ptr (VerifyContext *ctx, guint32 token, gboolean virtual) { ILStackDesc *top; MonoMethod *method; if (virtual && !check_underflow (ctx, 1)) return; if (!virtual && !check_overflow (ctx)) return; if (!IS_METHOD_DEF_OR_REF_OR_SPEC (token) || !token_bounds_check (ctx->image, token)) { ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid token %x for ldftn at 0x%04x", token, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE); return; } if (!(method = verifier_load_method (ctx, token, virtual ? "ldvirtfrn" : "ldftn"))) return; if (mono_method_is_constructor (method)) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use ldftn with a constructor at 0x%04x", ctx->ip_offset)); if (virtual) { ILStackDesc *top = stack_pop (ctx); if (stack_slot_get_type (top) != TYPE_COMPLEX || top->type->type == MONO_TYPE_VALUETYPE) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid argument to ldvirtftn at 0x%04x", ctx->ip_offset)); if (method->flags & METHOD_ATTRIBUTE_STATIC) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use ldvirtftn with a constructor at 0x%04x", ctx->ip_offset)); if (!verify_stack_type_compatibility (ctx, &method->klass->byval_arg, top)) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Unexpected object for ldvirtftn at 0x%04x", ctx->ip_offset)); } if (!mono_method_can_access_method_full (ctx->method, method, NULL)) CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Loaded method is not visible for ldftn/ldvirtftn at 0x%04x", ctx->ip_offset), MONO_EXCEPTION_METHOD_ACCESS); top = stack_push_val(ctx, TYPE_PTR, mono_type_create_fnptr_from_mono_method (ctx, method)); top->method = method; } static void do_sizeof (VerifyContext *ctx, int token) { MonoType *type; if (!IS_TYPE_DEF_OR_REF_OR_SPEC (token) || !token_bounds_check (ctx->image, token)) { ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid type token %x at 0x%04x", token, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE); return; } if (!(type = verifier_load_type (ctx, token, "sizeof"))) return; if (type->byref && type->type != MONO_TYPE_TYPEDBYREF) { ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid use of byref type at 0x%04x", ctx->ip_offset)); return; } if (type->type == MONO_TYPE_VOID) { ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid use of void type at 0x%04x", ctx->ip_offset)); return; } if (check_overflow (ctx)) set_stack_value (ctx, stack_push (ctx), &mono_defaults.uint32_class->byval_arg, FALSE); } /* Stack top can be of any type, the runtime doesn't care and treat everything as an int. */ static void do_localloc (VerifyContext *ctx) { ILStackDesc *top; if (ctx->eval.size != 1) { ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Stack must have only size item in localloc at 0x%04x", ctx->ip_offset)); return; } if (in_any_exception_block (ctx->header, ctx->ip_offset)) { ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Stack must have only size item in localloc at 0x%04x", ctx->ip_offset)); return; } /*TODO verify top type*/ top = stack_pop (ctx); set_stack_value (ctx, stack_push (ctx), &mono_defaults.int_class->byval_arg, FALSE); CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Instruction localloc in never verifiable at 0x%04x", ctx->ip_offset)); } static void do_ldstr (VerifyContext *ctx, guint32 token) { GSList *error = NULL; if (mono_metadata_token_code (token) != MONO_TOKEN_STRING) { ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid string token %x at 0x%04x", token, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE); return; } if (!ctx->image->dynamic && !mono_verifier_verify_string_signature (ctx->image, mono_metadata_token_index (token), &error)) { if (error) ctx->list = g_slist_concat (ctx->list, error); ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid string index %x at 0x%04x", token, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE); return; } if (check_overflow (ctx)) stack_push_val (ctx, TYPE_COMPLEX, &mono_defaults.string_class->byval_arg); } static void do_refanyval (VerifyContext *ctx, int token) { ILStackDesc *top; MonoType *type; if (!check_underflow (ctx, 1)) return; if (!(type = get_boxable_mono_type (ctx, token, "refanyval"))) return; top = stack_pop (ctx); if (top->stype != TYPE_PTR || top->type->type != MONO_TYPE_TYPEDBYREF) ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Expected a typedref as argument for refanyval, but found %s at 0x%04x", stack_slot_get_name (top), ctx->ip_offset)); set_stack_value (ctx, stack_push (ctx), type, TRUE); } static void do_refanytype (VerifyContext *ctx) { ILStackDesc *top; if (!check_underflow (ctx, 1)) return; top = stack_pop (ctx); if (top->stype != TYPE_PTR || top->type->type != MONO_TYPE_TYPEDBYREF) ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Expected a typedref as argument for refanytype, but found %s at 0x%04x", stack_slot_get_name (top), ctx->ip_offset)); set_stack_value (ctx, stack_push (ctx), &mono_defaults.typehandle_class->byval_arg, FALSE); } static void do_mkrefany (VerifyContext *ctx, int token) { ILStackDesc *top; MonoType *type; if (!check_underflow (ctx, 1)) return; if (!(type = get_boxable_mono_type (ctx, token, "refanyval"))) return; top = stack_pop (ctx); if (stack_slot_is_managed_mutability_pointer (top)) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer with mkrefany at 0x%04x", ctx->ip_offset)); if (!stack_slot_is_managed_pointer (top)) { CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Expected a managed pointer for mkrefany, but found %s at 0x%04x", stack_slot_get_name (top), ctx->ip_offset)); }else { MonoType *stack_type = mono_type_get_type_byval (top->type); if (MONO_TYPE_IS_REFERENCE (type) && !mono_metadata_type_equal (type, stack_type)) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Type not compatible for mkrefany at 0x%04x", ctx->ip_offset)); if (!MONO_TYPE_IS_REFERENCE (type) && !verify_type_compatibility_full (ctx, type, stack_type, TRUE)) CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Type not compatible for mkrefany at 0x%04x", ctx->ip_offset)); } set_stack_value (ctx, stack_push (ctx), &mono_defaults.typed_reference_class->byval_arg, FALSE); } static void do_ckfinite (VerifyContext *ctx) { ILStackDesc *top; if (!check_underflow (ctx, 1)) return; top = stack_pop (ctx); if (stack_slot_get_underlying_type (top) != TYPE_R8) ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Expected float32 or float64 on stack for ckfinit but found %s at 0x%04x", stack_slot_get_name (top), ctx->ip_offset)); stack_push_stack_val (ctx, top); } /* * merge_stacks: * Merge the stacks and perform compat checks. The merge check if types of @from are mergeable with type of @to * * @from holds new values for a given control path * @to holds the current values of a given control path * * TODO we can eliminate the from argument as all callers pass &ctx->eval */ static void merge_stacks (VerifyContext *ctx, ILCodeDesc *from, ILCodeDesc *to, gboolean start, gboolean external) { MonoError error; int i, j, k; stack_init (ctx, to); if (start) { if (to->flags == IL_CODE_FLAG_NOT_PROCESSED) from->size = 0; else stack_copy (&ctx->eval, to); goto end_verify; } else if (!(to->flags & IL_CODE_STACK_MERGED)) { stack_copy (to, &ctx->eval); goto end_verify; } VERIFIER_DEBUG ( printf ("performing stack merge %d x %d\n", from->size, to->size); ); if (from->size != to->size) { VERIFIER_DEBUG ( printf ("different stack sizes %d x %d at 0x%04x\n", from->size, to->size, ctx->ip_offset); ); ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Could not merge stacks, different sizes (%d x %d) at 0x%04x", from->size, to->size, ctx->ip_offset)); goto end_verify; } //FIXME we need to preserve CMMP attributes //FIXME we must take null literals into consideration. for (i = 0; i < from->size; ++i) { ILStackDesc *new_slot = from->stack + i; ILStackDesc *old_slot = to->stack + i; MonoType *new_type = mono_type_from_stack_slot (new_slot); MonoType *old_type = mono_type_from_stack_slot (old_slot); MonoClass *old_class = mono_class_from_mono_type (old_type); MonoClass *new_class = mono_class_from_mono_type (new_type); MonoClass *match_class = NULL; // S := T then U = S (new value is compatible with current value, keep current) if (verify_stack_type_compatibility (ctx, old_type, new_slot)) { copy_stack_value (new_slot, old_slot); continue; } // T := S then U = T (old value is compatible with current value, use new) if (verify_stack_type_compatibility (ctx, new_type, old_slot)) { copy_stack_value (old_slot, new_slot); continue; } if (mono_type_is_generic_argument (old_type) || mono_type_is_generic_argument (new_type)) { char *old_name = stack_slot_full_name (old_slot); char *new_name = stack_slot_full_name (new_slot); CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Could not merge stack at depth %d, types not compatible: %s X %s at 0x%04x", i, old_name, new_name, ctx->ip_offset)); g_free (old_name); g_free (new_name); goto end_verify; } //both are reference types, use closest common super type if (!mono_class_from_mono_type (old_type)->valuetype && !mono_class_from_mono_type (new_type)->valuetype && !stack_slot_is_managed_pointer (old_slot) && !stack_slot_is_managed_pointer (new_slot)) { for (j = MIN (old_class->idepth, new_class->idepth) - 1; j > 0; --j) { if (mono_metadata_type_equal (&old_class->supertypes [j]->byval_arg, &new_class->supertypes [j]->byval_arg)) { match_class = old_class->supertypes [j]; goto match_found; } } mono_class_setup_interfaces (old_class, &error); if (!mono_error_ok (&error)) { CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot merge stacks due to a TypeLoadException %s at 0x%04x", mono_error_get_message (&error), ctx->ip_offset)); mono_error_cleanup (&error); goto end_verify; } for (j = 0; j < old_class->interface_count; ++j) { for (k = 0; k < new_class->interface_count; ++k) { if (mono_metadata_type_equal (&old_class->interfaces [j]->byval_arg, &new_class->interfaces [k]->byval_arg)) { match_class = old_class->interfaces [j]; goto match_found; } } } //No decent super type found, use object match_class = mono_defaults.object_class; goto match_found; } else if (is_compatible_boxed_valuetype (ctx,old_type, new_type, new_slot, FALSE) || is_compatible_boxed_valuetype (ctx, new_type, old_type, old_slot, FALSE)) { match_class = mono_defaults.object_class; goto match_found; } { char *old_name = stack_slot_full_name (old_slot); char *new_name = stack_slot_full_name (new_slot); CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Could not merge stack at depth %d, types not compatible: %s X %s at 0x%04x", i, old_name, new_name, ctx->ip_offset)); g_free (old_name); g_free (new_name); } set_stack_value (ctx, old_slot, &new_class->byval_arg, stack_slot_is_managed_pointer (old_slot)); goto end_verify; match_found: g_assert (match_class); set_stack_value (ctx, old_slot, &match_class->byval_arg, stack_slot_is_managed_pointer (old_slot)); set_stack_value (ctx, new_slot, &match_class->byval_arg, stack_slot_is_managed_pointer (old_slot)); continue; } end_verify: if (external) to->flags |= IL_CODE_FLAG_WAS_TARGET; to->flags |= IL_CODE_STACK_MERGED; } #define HANDLER_START(clause) ((clause)->flags == MONO_EXCEPTION_CLAUSE_FILTER ? (clause)->data.filter_offset : clause->handler_offset) #define IS_CATCH_OR_FILTER(clause) ((clause)->flags == MONO_EXCEPTION_CLAUSE_FILTER || (clause)->flags == MONO_EXCEPTION_CLAUSE_NONE) /* * is_clause_in_range : * * Returns TRUE if either the protected block or the handler of @clause is in the @start - @end range. */ static gboolean is_clause_in_range (MonoExceptionClause *clause, guint32 start, guint32 end) { if (clause->try_offset >= start && clause->try_offset < end) return TRUE; if (HANDLER_START (clause) >= start && HANDLER_START (clause) < end) return TRUE; return FALSE; } /* * is_clause_inside_range : * * Returns TRUE if @clause lies completely inside the @start - @end range. */ static gboolean is_clause_inside_range (MonoExceptionClause *clause, guint32 start, guint32 end) { if (clause->try_offset < start || (clause->try_offset + clause->try_len) > end) return FALSE; if (HANDLER_START (clause) < start || (clause->handler_offset + clause->handler_len) > end) return FALSE; return TRUE; } /* * is_clause_nested : * * Returns TRUE if @nested is nested in @clause. */ static gboolean is_clause_nested (MonoExceptionClause *clause, MonoExceptionClause *nested) { if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER && is_clause_inside_range (nested, clause->data.filter_offset, clause->handler_offset)) return TRUE; return is_clause_inside_range (nested, clause->try_offset, clause->try_offset + clause->try_len) || is_clause_inside_range (nested, clause->handler_offset, clause->handler_offset + clause->handler_len); } /* Test the relationship between 2 exception clauses. Follow P.1 12.4.2.7 of ECMA * the each pair of exception must have the following properties: * - one is fully nested on another (the outer must not be a filter clause) (the nested one must come earlier) * - completely disjoin (none of the 3 regions of each entry overlap with the other 3) * - mutual protection (protected block is EXACT the same, handlers are disjoin and all handler are catch or all handler are filter) */ static void verify_clause_relationship (VerifyContext *ctx, MonoExceptionClause *clause, MonoExceptionClause *to_test) { /*clause is nested*/ if (to_test->flags == MONO_EXCEPTION_CLAUSE_FILTER && is_clause_inside_range (clause, to_test->data.filter_offset, to_test->handler_offset)) { ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Exception clause inside filter")); return; } /*wrong nesting order.*/ if (is_clause_nested (clause, to_test)) { ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Nested exception clause appears after enclosing clause")); return; } /*mutual protection*/ if (clause->try_offset == to_test->try_offset && clause->try_len == to_test->try_len) { /*handlers are not disjoint*/ if (is_clause_in_range (to_test, HANDLER_START (clause), clause->handler_offset + clause->handler_len)) { ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Exception handlers overlap")); return; } /* handlers are not catch or filter */ if (!IS_CATCH_OR_FILTER (clause) || !IS_CATCH_OR_FILTER (to_test)) { ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Exception clauses with shared protected block are neither catch or filter")); return; } /*OK*/ return; } /*not completelly disjoint*/ if ((is_clause_in_range (to_test, clause->try_offset, clause->try_offset + clause->try_len) || is_clause_in_range (to_test, HANDLER_START (clause), clause->handler_offset + clause->handler_len)) && !is_clause_nested (to_test, clause)) ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Exception clauses overlap")); } #define code_bounds_check(size) \ if (ADDP_IS_GREATER_OR_OVF (ip, size, end)) {\ ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Code overrun starting with 0x%x at 0x%04x", *ip, ctx.ip_offset)); \ break; \ } \ static gboolean mono_opcode_is_prefix (int op) { switch (op) { case MONO_CEE_UNALIGNED_: case MONO_CEE_VOLATILE_: case MONO_CEE_TAIL_: case MONO_CEE_CONSTRAINED_: case MONO_CEE_READONLY_: return TRUE; } return FALSE; } /* * FIXME: need to distinguish between valid and verifiable. * Need to keep track of types on the stack. * Verify types for opcodes. */ GSList* mono_method_verify (MonoMethod *method, int level) { MonoError error; const unsigned char *ip, *code_start; const unsigned char *end; MonoSimpleBasicBlock *bb = NULL, *original_bb = NULL; int i, n, need_merge = 0, start = 0; guint token, ip_offset = 0, prefix = 0; MonoGenericContext *generic_context = NULL; MonoImage *image; VerifyContext ctx; GSList *tmp; VERIFIER_DEBUG ( printf ("Verify IL for method %s %s %s\n", method->klass->name_space, method->klass->name, method->name); ); if (method->iflags & (METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL | METHOD_IMPL_ATTRIBUTE_RUNTIME) || (method->flags & (METHOD_ATTRIBUTE_PINVOKE_IMPL | METHOD_ATTRIBUTE_ABSTRACT))) { return NULL; } memset (&ctx, 0, sizeof (VerifyContext)); //FIXME use mono_method_get_signature_full ctx.signature = mono_method_signature (method); if (!ctx.signature) { ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Could not decode method signature")); return ctx.list; } ctx.header = mono_method_get_header (method); if (!ctx.header) { ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Could not decode method header")); return ctx.list; } ctx.method = method; code_start = ip = ctx.header->code; end = ip + ctx.header->code_size; ctx.image = image = method->klass->image; ctx.max_args = ctx.signature->param_count + ctx.signature->hasthis; ctx.max_stack = ctx.header->max_stack; ctx.verifiable = ctx.valid = 1; ctx.level = level; ctx.code = g_new (ILCodeDesc, ctx.header->code_size); ctx.code_size = ctx.header->code_size; memset(ctx.code, 0, sizeof (ILCodeDesc) * ctx.header->code_size); ctx.num_locals = ctx.header->num_locals; ctx.locals = g_memdup (ctx.header->locals, sizeof (MonoType*) * ctx.header->num_locals); if (ctx.num_locals > 0 && !ctx.header->init_locals) CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Method with locals variable but without init locals set")); ctx.params = g_new (MonoType*, ctx.max_args); if (ctx.signature->hasthis) ctx.params [0] = method->klass->valuetype ? &method->klass->this_arg : &method->klass->byval_arg; memcpy (ctx.params + ctx.signature->hasthis, ctx.signature->params, sizeof (MonoType *) * ctx.signature->param_count); if (ctx.signature->is_inflated) ctx.generic_context = generic_context = mono_method_get_context (method); if (!generic_context && (method->klass->generic_container || method->is_generic)) { if (method->is_generic) ctx.generic_context = generic_context = &(mono_method_get_generic_container (method)->context); else ctx.generic_context = generic_context = &method->klass->generic_container->context; } for (i = 0; i < ctx.num_locals; ++i) { MonoType *uninflated = ctx.locals [i]; ctx.locals [i] = mono_class_inflate_generic_type_checked (ctx.locals [i], ctx.generic_context, &error); if (!mono_error_ok (&error)) { char *name = mono_type_full_name (ctx.locals [i] ? ctx.locals [i] : uninflated); ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid local %d of type %s", i, name)); g_free (name); mono_error_cleanup (&error); /* we must not free (in cleanup) what was not yet allocated (but only copied) */ ctx.num_locals = i; ctx.max_args = 0; goto cleanup; } } for (i = 0; i < ctx.max_args; ++i) { MonoType *uninflated = ctx.params [i]; ctx.params [i] = mono_class_inflate_generic_type_checked (ctx.params [i], ctx.generic_context, &error); if (!mono_error_ok (&error)) { char *name = mono_type_full_name (ctx.params [i] ? ctx.params [i] : uninflated); ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid parameter %d of type %s", i, name)); g_free (name); mono_error_cleanup (&error); /* we must not free (in cleanup) what was not yet allocated (but only copied) */ ctx.max_args = i; goto cleanup; } } stack_init (&ctx, &ctx.eval); for (i = 0; i < ctx.num_locals; ++i) { if (!mono_type_is_valid_in_context (&ctx, ctx.locals [i])) break; if (get_stack_type (ctx.locals [i]) == TYPE_INV) { char *name = mono_type_full_name (ctx.locals [i]); ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid local %i of type %s", i, name)); g_free (name); break; } } for (i = 0; i < ctx.max_args; ++i) { if (!mono_type_is_valid_in_context (&ctx, ctx.params [i])) break; if (get_stack_type (ctx.params [i]) == TYPE_INV) { char *name = mono_type_full_name (ctx.params [i]); ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid parameter %i of type %s", i, name)); g_free (name); break; } } if (!ctx.valid) goto cleanup; for (i = 0; i < ctx.header->num_clauses && ctx.valid; ++i) { MonoExceptionClause *clause = ctx.header->clauses + i; VERIFIER_DEBUG (printf ("clause try %x len %x filter at %x handler at %x len %x\n", clause->try_offset, clause->try_len, clause->data.filter_offset, clause->handler_offset, clause->handler_len); ); if (clause->try_offset > ctx.code_size || ADD_IS_GREATER_OR_OVF (clause->try_offset, clause->try_len, ctx.code_size)) ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("try clause out of bounds at 0x%04x", clause->try_offset)); if (clause->try_len <= 0) ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("try clause len <= 0 at 0x%04x", clause->try_offset)); if (clause->handler_offset > ctx.code_size || ADD_IS_GREATER_OR_OVF (clause->handler_offset, clause->handler_len, ctx.code_size)) ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("handler clause out of bounds at 0x%04x", clause->try_offset)); if (clause->handler_len <= 0) ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("handler clause len <= 0 at 0x%04x", clause->try_offset)); if (clause->try_offset < clause->handler_offset && ADD_IS_GREATER_OR_OVF (clause->try_offset, clause->try_len, HANDLER_START (clause))) ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("try block (at 0x%04x) includes handler block (at 0x%04x)", clause->try_offset, clause->handler_offset)); if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) { if (clause->data.filter_offset > ctx.code_size) ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("filter clause out of bounds at 0x%04x", clause->try_offset)); if (clause->data.filter_offset >= clause->handler_offset) ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("filter clause must come before the handler clause at 0x%04x", clause->data.filter_offset)); } for (n = i + 1; n < ctx.header->num_clauses && ctx.valid; ++n) verify_clause_relationship (&ctx, clause, ctx.header->clauses + n); if (!ctx.valid) break; ctx.code [clause->try_offset].flags |= IL_CODE_FLAG_WAS_TARGET; if (clause->try_offset + clause->try_len < ctx.code_size) ctx.code [clause->try_offset + clause->try_len].flags |= IL_CODE_FLAG_WAS_TARGET; if (clause->handler_offset + clause->handler_len < ctx.code_size) ctx.code [clause->handler_offset + clause->handler_len].flags |= IL_CODE_FLAG_WAS_TARGET; if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE) { if (!clause->data.catch_class) { ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Catch clause %d with invalid type", i)); break; } init_stack_with_value_at_exception_boundary (&ctx, ctx.code + clause->handler_offset, clause->data.catch_class); } else if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) { init_stack_with_value_at_exception_boundary (&ctx, ctx.code + clause->data.filter_offset, mono_defaults.exception_class); init_stack_with_value_at_exception_boundary (&ctx, ctx.code + clause->handler_offset, mono_defaults.exception_class); } } original_bb = bb = mono_basic_block_split (method, &error); if (!mono_error_ok (&error)) { ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid branch target: %s", mono_error_get_message (&error))); mono_error_cleanup (&error); goto cleanup; } g_assert (bb); while (ip < end && ctx.valid) { int op_size; ip_offset = ip - code_start; { const unsigned char *ip_copy = ip; int op; if (ip_offset > bb->end) { ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Branch or EH block at [0x%04x] targets middle instruction at 0x%04x", bb->end, ip_offset)); goto cleanup; } if (ip_offset == bb->end) bb = bb->next; op_size = mono_opcode_value_and_size (&ip_copy, end, &op); if (op_size == -1) { ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction %x at 0x%04x", *ip, ip_offset)); goto cleanup; } if (ADD_IS_GREATER_OR_OVF (ip_offset, op_size, bb->end)) { ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Branch or EH block targets middle of instruction at 0x%04x", ip_offset)); goto cleanup; } /*Last Instruction*/ if (ip_offset + op_size == bb->end && mono_opcode_is_prefix (op)) { ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Branch or EH block targets between prefix '%s' and instruction at 0x%04x", mono_opcode_name (op), ip_offset)); goto cleanup; } } ctx.ip_offset = ip_offset = ip - code_start; /*We need to check against fallthrou in and out of protected blocks. * For fallout we check the once a protected block ends, if the start flag is not set. * Likewise for fallthru in, we check if ip is the start of a protected block and start is not set * TODO convert these checks to be done using flags and not this loop */ for (i = 0; i < ctx.header->num_clauses && ctx.valid; ++i) { MonoExceptionClause *clause = ctx.header->clauses + i; if ((clause->try_offset + clause->try_len == ip_offset) && start == 0) { CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("fallthru off try block at 0x%04x", ip_offset)); start = 1; } if ((clause->handler_offset + clause->handler_len == ip_offset) && start == 0) { if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("fallout of handler block at 0x%04x", ip_offset)); else CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("fallout of handler block at 0x%04x", ip_offset)); start = 1; } if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER && clause->handler_offset == ip_offset && start == 0) { ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("fallout of filter block at 0x%04x", ip_offset)); start = 1; } if (clause->handler_offset == ip_offset && start == 0) { CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("fallthru handler block at 0x%04x", ip_offset)); start = 1; } if (clause->try_offset == ip_offset && ctx.eval.size > 0 && start == 0) { ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Try to enter try block with a non-empty stack at 0x%04x", ip_offset)); start = 1; } } /*This must be done after fallthru detection otherwise it won't happen.*/ if (bb->dead) { /*FIXME remove this once we move all bad branch checking code to use BB only*/ ctx.code [ip_offset].flags |= IL_CODE_FLAG_SEEN; ip += op_size; continue; } if (!ctx.valid) break; if (need_merge) { VERIFIER_DEBUG ( printf ("extra merge needed! 0x%04x \n", ctx.target); ); merge_stacks (&ctx, &ctx.eval, &ctx.code [ctx.target], FALSE, TRUE); need_merge = 0; } merge_stacks (&ctx, &ctx.eval, &ctx.code[ip_offset], start, FALSE); start = 0; /*TODO we can fast detect a forward branch or exception block targeting code after prefix, we should fail fast*/ #ifdef MONO_VERIFIER_DEBUG { char *discode; discode = mono_disasm_code_one (NULL, method, ip, NULL); discode [strlen (discode) - 1] = 0; /* no \n */ g_print ("[%d] %-29s (%d)\n", ip_offset, discode, ctx.eval.size); g_free (discode); } dump_stack_state (&ctx.code [ip_offset]); dump_stack_state (&ctx.eval); #endif switch (*ip) { case CEE_NOP: case CEE_BREAK: ++ip; break; case CEE_LDARG_0: case CEE_LDARG_1: case CEE_LDARG_2: case CEE_LDARG_3: push_arg (&ctx, *ip - CEE_LDARG_0, FALSE); ++ip; break; case CEE_LDARG_S: case CEE_LDARGA_S: code_bounds_check (2); push_arg (&ctx, ip [1], *ip == CEE_LDARGA_S); ip += 2; break; case CEE_ADD_OVF_UN: do_binop (&ctx, *ip, add_ovf_un_table); ++ip; break; case CEE_SUB_OVF_UN: do_binop (&ctx, *ip, sub_ovf_un_table); ++ip; break; case CEE_ADD_OVF: case CEE_SUB_OVF: case CEE_MUL_OVF: case CEE_MUL_OVF_UN: do_binop (&ctx, *ip, bin_ovf_table); ++ip; break; case CEE_ADD: do_binop (&ctx, *ip, add_table); ++ip; break; case CEE_SUB: do_binop (&ctx, *ip, sub_table); ++ip; break; case CEE_MUL: case CEE_DIV: case CEE_REM: do_binop (&ctx, *ip, bin_op_table); ++ip; break; case CEE_AND: case CEE_DIV_UN: case CEE_OR: case CEE_REM_UN: case CEE_XOR: do_binop (&ctx, *ip, int_bin_op_table); ++ip; break; case CEE_SHL: case CEE_SHR: case CEE_SHR_UN: do_binop (&ctx, *ip, shift_op_table); ++ip; break; case CEE_POP: if (!check_underflow (&ctx, 1)) break; stack_pop_safe (&ctx); ++ip; break; case CEE_RET: do_ret (&ctx); ++ip; start = 1; break; case CEE_LDLOC_0: case CEE_LDLOC_1: case CEE_LDLOC_2: case CEE_LDLOC_3: /*TODO support definite assignment verification? */ push_local (&ctx, *ip - CEE_LDLOC_0, FALSE); ++ip; break; case CEE_STLOC_0: case CEE_STLOC_1: case CEE_STLOC_2: case CEE_STLOC_3: store_local (&ctx, *ip - CEE_STLOC_0); ++ip; break; case CEE_STLOC_S: code_bounds_check (2); store_local (&ctx, ip [1]); ip += 2; break; case CEE_STARG_S: code_bounds_check (2); store_arg (&ctx, ip [1]); ip += 2; break; case CEE_LDC_I4_M1: case CEE_LDC_I4_0: case CEE_LDC_I4_1: case CEE_LDC_I4_2: case CEE_LDC_I4_3: case CEE_LDC_I4_4: case CEE_LDC_I4_5: case CEE_LDC_I4_6: case CEE_LDC_I4_7: case CEE_LDC_I4_8: if (check_overflow (&ctx)) stack_push_val (&ctx, TYPE_I4, &mono_defaults.int32_class->byval_arg); ++ip; break; case CEE_LDC_I4_S: code_bounds_check (2); if (check_overflow (&ctx)) stack_push_val (&ctx, TYPE_I4, &mono_defaults.int32_class->byval_arg); ip += 2; break; case CEE_LDC_I4: code_bounds_check (5); if (check_overflow (&ctx)) stack_push_val (&ctx,TYPE_I4, &mono_defaults.int32_class->byval_arg); ip += 5; break; case CEE_LDC_I8: code_bounds_check (9); if (check_overflow (&ctx)) stack_push_val (&ctx,TYPE_I8, &mono_defaults.int64_class->byval_arg); ip += 9; break; case CEE_LDC_R4: code_bounds_check (5); if (check_overflow (&ctx)) stack_push_val (&ctx, TYPE_R8, &mono_defaults.double_class->byval_arg); ip += 5; break; case CEE_LDC_R8: code_bounds_check (9); if (check_overflow (&ctx)) stack_push_val (&ctx, TYPE_R8, &mono_defaults.double_class->byval_arg); ip += 9; break; case CEE_LDNULL: if (check_overflow (&ctx)) stack_push_val (&ctx, TYPE_COMPLEX | NULL_LITERAL_MASK, &mono_defaults.object_class->byval_arg); ++ip; break; case CEE_BEQ_S: case CEE_BNE_UN_S: code_bounds_check (2); do_branch_op (&ctx, (signed char)ip [1] + 2, cmp_br_eq_op); ip += 2; need_merge = 1; break; case CEE_BGE_S: case CEE_BGT_S: case CEE_BLE_S: case CEE_BLT_S: case CEE_BGE_UN_S: case CEE_BGT_UN_S: case CEE_BLE_UN_S: case CEE_BLT_UN_S: code_bounds_check (2); do_branch_op (&ctx, (signed char)ip [1] + 2, cmp_br_op); ip += 2; need_merge = 1; break; case CEE_BEQ: case CEE_BNE_UN: code_bounds_check (5); do_branch_op (&ctx, (gint32)read32 (ip + 1) + 5, cmp_br_eq_op); ip += 5; need_merge = 1; break; case CEE_BGE: case CEE_BGT: case CEE_BLE: case CEE_BLT: case CEE_BGE_UN: case CEE_BGT_UN: case CEE_BLE_UN: case CEE_BLT_UN: code_bounds_check (5); do_branch_op (&ctx, (gint32)read32 (ip + 1) + 5, cmp_br_op); ip += 5; need_merge = 1; break; case CEE_LDLOC_S: case CEE_LDLOCA_S: code_bounds_check (2); push_local (&ctx, ip[1], *ip == CEE_LDLOCA_S); ip += 2; break; case CEE_UNUSED99: ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Use of the `unused' opcode")); ++ip; break; case CEE_DUP: { ILStackDesc * top; if (!check_underflow (&ctx, 1)) break; if (!check_overflow (&ctx)) break; top = stack_pop_safe (&ctx); copy_stack_value (stack_push (&ctx), top); copy_stack_value (stack_push (&ctx), top); ++ip; break; } case CEE_JMP: code_bounds_check (5); if (ctx.eval.size) ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Eval stack must be empty in jmp at 0x%04x", ip_offset)); token = read32 (ip + 1); if (in_any_block (ctx.header, ip_offset)) ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("jmp cannot escape exception blocks at 0x%04x", ip_offset)); CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Intruction jmp is not verifiable at 0x%04x", ctx.ip_offset)); /* * FIXME: check signature, retval, arguments etc. */ ip += 5; break; case CEE_CALL: case CEE_CALLVIRT: code_bounds_check (5); do_invoke_method (&ctx, read32 (ip + 1), *ip == CEE_CALLVIRT); ip += 5; break; case CEE_CALLI: code_bounds_check (5); token = read32 (ip + 1); /* * FIXME: check signature, retval, arguments etc. * FIXME: check requirements for tail call */ CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Intruction calli is not verifiable at 0x%04x", ctx.ip_offset)); ip += 5; break; case CEE_BR_S: code_bounds_check (2); do_static_branch (&ctx, (signed char)ip [1] + 2); need_merge = 1; ip += 2; start = 1; break; case CEE_BRFALSE_S: case CEE_BRTRUE_S: code_bounds_check (2); do_boolean_branch_op (&ctx, (signed char)ip [1] + 2); ip += 2; need_merge = 1; break; case CEE_BR: code_bounds_check (5); do_static_branch (&ctx, (gint32)read32 (ip + 1) + 5); need_merge = 1; ip += 5; start = 1; break; case CEE_BRFALSE: case CEE_BRTRUE: code_bounds_check (5); do_boolean_branch_op (&ctx, (gint32)read32 (ip + 1) + 5); ip += 5; need_merge = 1; break; case CEE_SWITCH: { guint32 entries; code_bounds_check (5); entries = read32 (ip + 1); if (entries > 0xFFFFFFFFU / sizeof (guint32)) ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Too many switch entries %x at 0x%04x", entries, ctx.ip_offset)); ip += 5; code_bounds_check (sizeof (guint32) * entries); do_switch (&ctx, entries, ip); ip += sizeof (guint32) * entries; break; } case CEE_LDIND_I1: case CEE_LDIND_U1: case CEE_LDIND_I2: case CEE_LDIND_U2: case CEE_LDIND_I4: case CEE_LDIND_U4: case CEE_LDIND_I8: case CEE_LDIND_I: case CEE_LDIND_R4: case CEE_LDIND_R8: case CEE_LDIND_REF: do_load_indirect (&ctx, *ip); ++ip; break; case CEE_STIND_REF: case CEE_STIND_I1: case CEE_STIND_I2: case CEE_STIND_I4: case CEE_STIND_I8: case CEE_STIND_R4: case CEE_STIND_R8: case CEE_STIND_I: do_store_indirect (&ctx, *ip); ++ip; break; case CEE_NOT: case CEE_NEG: do_unary_math_op (&ctx, *ip); ++ip; break; case CEE_CONV_I1: case CEE_CONV_I2: case CEE_CONV_I4: case CEE_CONV_U1: case CEE_CONV_U2: case CEE_CONV_U4: do_conversion (&ctx, TYPE_I4); ++ip; break; case CEE_CONV_I8: case CEE_CONV_U8: do_conversion (&ctx, TYPE_I8); ++ip; break; case CEE_CONV_R4: case CEE_CONV_R8: case CEE_CONV_R_UN: do_conversion (&ctx, TYPE_R8); ++ip; break; case CEE_CONV_I: case CEE_CONV_U: do_conversion (&ctx, TYPE_NATIVE_INT); ++ip; break; case CEE_CPOBJ: code_bounds_check (5); do_cpobj (&ctx, read32 (ip + 1)); ip += 5; break; case CEE_LDOBJ: code_bounds_check (5); do_ldobj_value (&ctx, read32 (ip + 1)); ip += 5; break; case CEE_LDSTR: code_bounds_check (5); do_ldstr (&ctx, read32 (ip + 1)); ip += 5; break; case CEE_NEWOBJ: code_bounds_check (5); do_newobj (&ctx, read32 (ip + 1)); ip += 5; break; case CEE_CASTCLASS: case CEE_ISINST: code_bounds_check (5); do_cast (&ctx, read32 (ip + 1), *ip == CEE_CASTCLASS ? "castclass" : "isinst"); ip += 5; break; case CEE_UNUSED58: case CEE_UNUSED1: ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Use of the `unused' opcode")); ++ip; break; case CEE_UNBOX: code_bounds_check (5); do_unbox_value (&ctx, read32 (ip + 1)); ip += 5; break; case CEE_THROW: do_throw (&ctx); start = 1; ++ip; break; case CEE_LDFLD: case CEE_LDFLDA: code_bounds_check (5); do_push_field (&ctx, read32 (ip + 1), *ip == CEE_LDFLDA); ip += 5; break; case CEE_LDSFLD: case CEE_LDSFLDA: code_bounds_check (5); do_push_static_field (&ctx, read32 (ip + 1), *ip == CEE_LDSFLDA); ip += 5; break; case CEE_STFLD: code_bounds_check (5); do_store_field (&ctx, read32 (ip + 1)); ip += 5; break; case CEE_STSFLD: code_bounds_check (5); do_store_static_field (&ctx, read32 (ip + 1)); ip += 5; break; case CEE_STOBJ: code_bounds_check (5); do_stobj (&ctx, read32 (ip + 1)); ip += 5; break; case CEE_CONV_OVF_I1_UN: case CEE_CONV_OVF_I2_UN: case CEE_CONV_OVF_I4_UN: case CEE_CONV_OVF_U1_UN: case CEE_CONV_OVF_U2_UN: case CEE_CONV_OVF_U4_UN: do_conversion (&ctx, TYPE_I4); ++ip; break; case CEE_CONV_OVF_I8_UN: case CEE_CONV_OVF_U8_UN: do_conversion (&ctx, TYPE_I8); ++ip; break; case CEE_CONV_OVF_I_UN: case CEE_CONV_OVF_U_UN: do_conversion (&ctx, TYPE_NATIVE_INT); ++ip; break; case CEE_BOX: code_bounds_check (5); do_box_value (&ctx, read32 (ip + 1)); ip += 5; break; case CEE_NEWARR: code_bounds_check (5); do_newarr (&ctx, read32 (ip + 1)); ip += 5; break; case CEE_LDLEN: do_ldlen (&ctx); ++ip; break; case CEE_LDELEMA: code_bounds_check (5); do_ldelema (&ctx, read32 (ip + 1)); ip += 5; break; case CEE_LDELEM_I1: case CEE_LDELEM_U1: case CEE_LDELEM_I2: case CEE_LDELEM_U2: case CEE_LDELEM_I4: case CEE_LDELEM_U4: case CEE_LDELEM_I8: case CEE_LDELEM_I: case CEE_LDELEM_R4: case CEE_LDELEM_R8: case CEE_LDELEM_REF: do_ldelem (&ctx, *ip, 0); ++ip; break; case CEE_STELEM_I: case CEE_STELEM_I1: case CEE_STELEM_I2: case CEE_STELEM_I4: case CEE_STELEM_I8: case CEE_STELEM_R4: case CEE_STELEM_R8: case CEE_STELEM_REF: do_stelem (&ctx, *ip, 0); ++ip; break; case CEE_LDELEM: code_bounds_check (5); do_ldelem (&ctx, *ip, read32 (ip + 1)); ip += 5; break; case CEE_STELEM: code_bounds_check (5); do_stelem (&ctx, *ip, read32 (ip + 1)); ip += 5; break; case CEE_UNBOX_ANY: code_bounds_check (5); do_unbox_any (&ctx, read32 (ip + 1)); ip += 5; break; case CEE_CONV_OVF_I1: case CEE_CONV_OVF_U1: case CEE_CONV_OVF_I2: case CEE_CONV_OVF_U2: case CEE_CONV_OVF_I4: case CEE_CONV_OVF_U4: do_conversion (&ctx, TYPE_I4); ++ip; break; case CEE_CONV_OVF_I8: case CEE_CONV_OVF_U8: do_conversion (&ctx, TYPE_I8); ++ip; break; case CEE_CONV_OVF_I: case CEE_CONV_OVF_U: do_conversion (&ctx, TYPE_NATIVE_INT); ++ip; break; case CEE_REFANYVAL: code_bounds_check (5); do_refanyval (&ctx, read32 (ip + 1)); ip += 5; break; case CEE_CKFINITE: do_ckfinite (&ctx); ++ip; break; case CEE_MKREFANY: code_bounds_check (5); do_mkrefany (&ctx, read32 (ip + 1)); ip += 5; break; case CEE_LDTOKEN: code_bounds_check (5); do_load_token (&ctx, read32 (ip + 1)); ip += 5; break; case CEE_ENDFINALLY: if (!is_correct_endfinally (ctx.header, ip_offset)) ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("endfinally must be used inside a finally/fault handler at 0x%04x", ctx.ip_offset)); ctx.eval.size = 0; start = 1; ++ip; break; case CEE_LEAVE: code_bounds_check (5); do_leave (&ctx, read32 (ip + 1) + 5); ip += 5; start = 1; need_merge = 1; break; case CEE_LEAVE_S: code_bounds_check (2); do_leave (&ctx, (signed char)ip [1] + 2); ip += 2; start = 1; need_merge = 1; break; case CEE_PREFIX1: code_bounds_check (2); ++ip; switch (*ip) { case CEE_STLOC: code_bounds_check (3); store_local (&ctx, read16 (ip + 1)); ip += 3; break; case CEE_CEQ: do_cmp_op (&ctx, cmp_br_eq_op, *ip); ++ip; break; case CEE_CGT: case CEE_CGT_UN: case CEE_CLT: case CEE_CLT_UN: do_cmp_op (&ctx, cmp_br_op, *ip); ++ip; break; case CEE_STARG: code_bounds_check (3); store_arg (&ctx, read16 (ip + 1) ); ip += 3; break; case CEE_ARGLIST: if (!check_overflow (&ctx)) break; if (ctx.signature->call_convention != MONO_CALL_VARARG) ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Cannot use arglist on method without VARGARG calling convention at 0x%04x", ctx.ip_offset)); set_stack_value (&ctx, stack_push (&ctx), &mono_defaults.argumenthandle_class->byval_arg, FALSE); ++ip; break; case CEE_LDFTN: code_bounds_check (5); do_load_function_ptr (&ctx, read32 (ip + 1), FALSE); ip += 5; break; case CEE_LDVIRTFTN: code_bounds_check (5); do_load_function_ptr (&ctx, read32 (ip + 1), TRUE); ip += 5; break; case CEE_LDARG: case CEE_LDARGA: code_bounds_check (3); push_arg (&ctx, read16 (ip + 1), *ip == CEE_LDARGA); ip += 3; break; case CEE_LDLOC: case CEE_LDLOCA: code_bounds_check (3); push_local (&ctx, read16 (ip + 1), *ip == CEE_LDLOCA); ip += 3; break; case CEE_LOCALLOC: do_localloc (&ctx); ++ip; break; case CEE_UNUSED56: case CEE_UNUSED57: case CEE_UNUSED70: case CEE_UNUSED: ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Use of the `unused' opcode")); ++ip; break; case CEE_ENDFILTER: do_endfilter (&ctx); start = 1; ++ip; break; case CEE_UNALIGNED_: code_bounds_check (2); prefix |= PREFIX_UNALIGNED; ip += 2; break; case CEE_VOLATILE_: prefix |= PREFIX_VOLATILE; ++ip; break; case CEE_TAIL_: prefix |= PREFIX_TAIL; ++ip; if (ip < end && (*ip != CEE_CALL && *ip != CEE_CALLI && *ip != CEE_CALLVIRT)) ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("tail prefix must be used only with call opcodes at 0x%04x", ip_offset)); break; case CEE_INITOBJ: code_bounds_check (5); do_initobj (&ctx, read32 (ip + 1)); ip += 5; break; case CEE_CONSTRAINED_: code_bounds_check (5); ctx.constrained_type = get_boxable_mono_type (&ctx, read32 (ip + 1), "constrained."); prefix |= PREFIX_CONSTRAINED; ip += 5; break; case CEE_READONLY_: prefix |= PREFIX_READONLY; ip++; break; case CEE_CPBLK: CLEAR_PREFIX (&ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE); if (!check_underflow (&ctx, 3)) break; CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Instruction cpblk is not verifiable at 0x%04x", ctx.ip_offset)); ip++; break; case CEE_INITBLK: CLEAR_PREFIX (&ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE); if (!check_underflow (&ctx, 3)) break; CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Instruction initblk is not verifiable at 0x%04x", ctx.ip_offset)); ip++; break; case CEE_NO_: ip += 2; break; case CEE_RETHROW: if (!is_correct_rethrow (ctx.header, ip_offset)) ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("rethrow must be used inside a catch handler at 0x%04x", ctx.ip_offset)); ctx.eval.size = 0; start = 1; ++ip; break; case CEE_SIZEOF: code_bounds_check (5); do_sizeof (&ctx, read32 (ip + 1)); ip += 5; break; case CEE_REFANYTYPE: do_refanytype (&ctx); ++ip; break; default: ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction FE %x at 0x%04x", *ip, ctx.ip_offset)); ++ip; } break; default: ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction %x at 0x%04x", *ip, ctx.ip_offset)); ++ip; } /*TODO we can fast detect a forward branch or exception block targeting code after prefix, we should fail fast*/ if (prefix) { if (!ctx.prefix_set) //first prefix ctx.code [ctx.ip_offset].flags |= IL_CODE_FLAG_SEEN; ctx.prefix_set |= prefix; ctx.has_flags = TRUE; prefix = 0; } else { if (!ctx.has_flags) ctx.code [ctx.ip_offset].flags |= IL_CODE_FLAG_SEEN; if (ctx.prefix_set & PREFIX_CONSTRAINED) ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction after constrained prefix at 0x%04x", ctx.ip_offset)); if (ctx.prefix_set & PREFIX_READONLY) ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction after readonly prefix at 0x%04x", ctx.ip_offset)); if (ctx.prefix_set & PREFIX_VOLATILE) ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction after volatile prefix at 0x%04x", ctx.ip_offset)); if (ctx.prefix_set & PREFIX_UNALIGNED) ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction after unaligned prefix at 0x%04x", ctx.ip_offset)); ctx.prefix_set = prefix = 0; ctx.has_flags = FALSE; } } /* * if ip != end we overflowed: mark as error. */ if ((ip != end || !start) && ctx.verifiable && !ctx.list) { ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Run ahead of method code at 0x%04x", ip_offset)); } /*We should guard against the last decoded opcode, otherwise we might add errors that doesn't make sense.*/ for (i = 0; i < ctx.code_size && i < ip_offset; ++i) { if (ctx.code [i].flags & IL_CODE_FLAG_WAS_TARGET) { if (!(ctx.code [i].flags & IL_CODE_FLAG_SEEN)) ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Branch or exception block target middle of intruction at 0x%04x", i)); if (ctx.code [i].flags & IL_CODE_DELEGATE_SEQUENCE) CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Branch to delegate code sequence at 0x%04x", i)); } if ((ctx.code [i].flags & IL_CODE_LDFTN_DELEGATE_NONFINAL_VIRTUAL) && ctx.has_this_store) CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Invalid ldftn with virtual function in method with stdarg 0 at 0x%04x", i)); if ((ctx.code [i].flags & IL_CODE_CALL_NONFINAL_VIRTUAL) && ctx.has_this_store) CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Invalid call to a non-final virtual function in method with stdarg.0 or ldarga.0 at 0x%04x", i)); } if (mono_method_is_constructor (ctx.method) && !ctx.super_ctor_called && !ctx.method->klass->valuetype && ctx.method->klass != mono_defaults.object_class) CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Constructor not calling super\n")); cleanup: if (ctx.code) { for (i = 0; i < ctx.header->code_size; ++i) { if (ctx.code [i].stack) g_free (ctx.code [i].stack); } } for (tmp = ctx.funptrs; tmp; tmp = tmp->next) g_free (tmp->data); g_slist_free (ctx.funptrs); for (tmp = ctx.exception_types; tmp; tmp = tmp->next) mono_metadata_free_type (tmp->data); g_slist_free (ctx.exception_types); for (i = 0; i < ctx.num_locals; ++i) { if (ctx.locals [i]) mono_metadata_free_type (ctx.locals [i]); } for (i = 0; i < ctx.max_args; ++i) { if (ctx.params [i]) mono_metadata_free_type (ctx.params [i]); } if (ctx.eval.stack) g_free (ctx.eval.stack); if (ctx.code) g_free (ctx.code); g_free (ctx.locals); g_free (ctx.params); mono_basic_block_free (original_bb); return ctx.list; } char* mono_verify_corlib () { /* This is a public API function so cannot be removed */ return NULL; } /* * Returns true if @method needs to be verified. * */ gboolean mono_verifier_is_enabled_for_method (MonoMethod *method) { return mono_verifier_is_enabled_for_class (method->klass) && method->wrapper_type == MONO_WRAPPER_NONE; } /* * Returns true if @klass need to be verified. * */ gboolean mono_verifier_is_enabled_for_class (MonoClass *klass) { return verify_all || (verifier_mode > MONO_VERIFIER_MODE_OFF && !klass->image->assembly->in_gac && klass->image != mono_defaults.corlib); } gboolean mono_verifier_is_enabled_for_image (MonoImage *image) { return verify_all || verifier_mode > MONO_VERIFIER_MODE_OFF; } gboolean mono_verifier_is_method_full_trust (MonoMethod *method) { return mono_verifier_is_class_full_trust (method->klass); } /* * Returns if @klass is under full trust or not. * * TODO This code doesn't take CAS into account. * * Under verify_all all user code must be verifiable if no security option was set * */ gboolean mono_verifier_is_class_full_trust (MonoClass *klass) { /* under CoreCLR code is trusted if it is part of the "platform" otherwise all code inside the GAC is trusted */ gboolean trusted_location = (mono_security_get_mode () != MONO_SECURITY_MODE_CORE_CLR) ? klass->image->assembly->in_gac : mono_security_core_clr_is_platform_image (klass->image); if (verify_all && verifier_mode == MONO_VERIFIER_MODE_OFF) return trusted_location || klass->image == mono_defaults.corlib; return verifier_mode < MONO_VERIFIER_MODE_VERIFIABLE || trusted_location || klass->image == mono_defaults.corlib; } GSList* mono_method_verify_with_current_settings (MonoMethod *method, gboolean skip_visibility) { return mono_method_verify (method, (verifier_mode != MONO_VERIFIER_MODE_STRICT ? MONO_VERIFY_NON_STRICT: 0) | (!mono_verifier_is_method_full_trust (method) ? MONO_VERIFY_FAIL_FAST : 0) | (skip_visibility ? MONO_VERIFY_SKIP_VISIBILITY : 0)); } static int get_field_end (MonoClassField *field) { int align; int size = mono_type_size (field->type, &align); if (size == 0) size = 4; /*FIXME Is this a safe bet?*/ return size + field->offset; } static gboolean verify_class_for_overlapping_reference_fields (MonoClass *class) { int i = 0, j; gpointer iter = NULL; MonoClassField *field; gboolean is_fulltrust = mono_verifier_is_class_full_trust (class); /*We can't skip types with !has_references since this is calculated after we have run.*/ if (!((class->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT)) return TRUE; /*We must check for stuff overlapping reference fields. The outer loop uses mono_class_get_fields to ensure that MonoClass:fields get inited. */ while ((field = mono_class_get_fields (class, &iter))) { int fieldEnd = get_field_end (field); gboolean is_valuetype = !MONO_TYPE_IS_REFERENCE (field->type); ++i; if (mono_field_is_deleted (field) || (field->type->attrs & FIELD_ATTRIBUTE_STATIC)) continue; for (j = i; j < class->field.count; ++j) { MonoClassField *other = &class->fields [j]; int otherEnd = get_field_end (other); if (mono_field_is_deleted (other) || (is_valuetype && !MONO_TYPE_IS_REFERENCE (other->type)) || (other->type->attrs & FIELD_ATTRIBUTE_STATIC)) continue; if (!is_valuetype && MONO_TYPE_IS_REFERENCE (other->type) && field->offset == other->offset && is_fulltrust) continue; if ((otherEnd > field->offset && otherEnd <= fieldEnd) || (other->offset >= field->offset && other->offset < fieldEnd)) return FALSE; } } return TRUE; } static guint field_hash (gconstpointer key) { const MonoClassField *field = key; return g_str_hash (field->name) ^ mono_metadata_type_hash (field->type); /**/ } static gboolean field_equals (gconstpointer _a, gconstpointer _b) { const MonoClassField *a = _a; const MonoClassField *b = _b; return !strcmp (a->name, b->name) && mono_metadata_type_equal (a->type, b->type); } static gboolean verify_class_fields (MonoClass *class) { gpointer iter = NULL; MonoClassField *field; MonoGenericContext *context = mono_class_get_context (class); GHashTable *unique_fields = g_hash_table_new_full (&field_hash, &field_equals, NULL, NULL); if (class->generic_container) context = &class->generic_container->context; while ((field = mono_class_get_fields (class, &iter)) != NULL) { if (!mono_type_is_valid_type_in_context (field->type, context)) { g_hash_table_destroy (unique_fields); return FALSE; } if (g_hash_table_lookup (unique_fields, field)) { g_hash_table_destroy (unique_fields); return FALSE; } g_hash_table_insert (unique_fields, field, field); } g_hash_table_destroy (unique_fields); return TRUE; } static gboolean verify_interfaces (MonoClass *class) { int i; for (i = 0; i < class->interface_count; ++i) { MonoClass *iface = class->interfaces [i]; if (!(iface->flags & TYPE_ATTRIBUTE_INTERFACE)) return FALSE; } return TRUE; } static gboolean verify_valuetype_layout_with_target (MonoClass *class, MonoClass *target_class) { int type; gpointer iter = NULL; MonoClassField *field; MonoClass *field_class; if (!class->valuetype) return TRUE; type = class->byval_arg.type; /*primitive type fields are not properly decoded*/ if ((type >= MONO_TYPE_BOOLEAN && type <= MONO_TYPE_R8) || (type >= MONO_TYPE_I && type <= MONO_TYPE_U)) return TRUE; while ((field = mono_class_get_fields (class, &iter)) != NULL) { if (!field->type) return FALSE; if (field->type->attrs & (FIELD_ATTRIBUTE_STATIC | FIELD_ATTRIBUTE_HAS_FIELD_RVA)) continue; field_class = mono_class_get_generic_type_definition (mono_class_from_mono_type (field->type)); if (field_class == target_class || class == field_class || !verify_valuetype_layout_with_target (field_class, target_class)) return FALSE; } return TRUE; } static gboolean verify_valuetype_layout (MonoClass *class) { gboolean res; res = verify_valuetype_layout_with_target (class, class); return res; } static gboolean recursive_mark_constraint_args (MonoBitSet *used_args, MonoGenericContainer *gc, MonoType *type) { int idx; MonoClass **constraints; MonoGenericParamInfo *param_info; g_assert (mono_type_is_generic_argument (type)); idx = mono_type_get_generic_param_num (type); if (mono_bitset_test_fast (used_args, idx)) return FALSE; mono_bitset_set_fast (used_args, idx); param_info = mono_generic_container_get_param_info (gc, idx); if (!param_info->constraints) return TRUE; for (constraints = param_info->constraints; *constraints; ++constraints) { MonoClass *ctr = *constraints; MonoType *constraint_type = &ctr->byval_arg; if (mono_type_is_generic_argument (constraint_type) && !recursive_mark_constraint_args (used_args, gc, constraint_type)) return FALSE; } return TRUE; } static gboolean verify_generic_parameters (MonoClass *class) { int i; MonoGenericContainer *gc = class->generic_container; MonoBitSet *used_args = mono_bitset_new (gc->type_argc, 0); for (i = 0; i < gc->type_argc; ++i) { MonoGenericParamInfo *param_info = mono_generic_container_get_param_info (gc, i); MonoClass **constraints; if (!param_info->constraints) continue; mono_bitset_clear_all (used_args); mono_bitset_set_fast (used_args, i); for (constraints = param_info->constraints; *constraints; ++constraints) { MonoClass *ctr = *constraints; MonoType *constraint_type = &ctr->byval_arg; if (!mono_type_is_valid_type_in_context (constraint_type, &gc->context)) goto fail; if (mono_type_is_generic_argument (constraint_type) && !recursive_mark_constraint_args (used_args, gc, constraint_type)) goto fail; } } mono_bitset_free (used_args); return TRUE; fail: mono_bitset_free (used_args); return FALSE; } /* * Check if the class is verifiable. * * Right now there are no conditions that make a class a valid but not verifiable. Both overlapping reference * field and invalid generic instantiation are fatal errors. * * This method must be safe to be called from mono_class_init and all code must be carefull about that. * */ gboolean mono_verifier_verify_class (MonoClass *class) { /*Neither <Module>, object or ifaces have parent.*/ if (!class->parent && class != mono_defaults.object_class && !MONO_CLASS_IS_INTERFACE (class) && (!class->image->dynamic && class->type_token != 0x2000001)) /*<Module> is the first type in the assembly*/ return FALSE; if (class->parent && MONO_CLASS_IS_INTERFACE (class->parent)) return FALSE; if (class->generic_container && (class->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) return FALSE; if (class->generic_container && !verify_generic_parameters (class)) return FALSE; if (!verify_class_for_overlapping_reference_fields (class)) return FALSE; if (class->generic_class && !mono_class_is_valid_generic_instantiation (NULL, class)) return FALSE; if (class->generic_class == NULL && !verify_class_fields (class)) return FALSE; if (class->valuetype && !verify_valuetype_layout (class)) return FALSE; if (!verify_interfaces (class)) return FALSE; return TRUE; } gboolean mono_verifier_class_is_valid_generic_instantiation (MonoClass *class) { return mono_class_is_valid_generic_instantiation (NULL, class); } gboolean mono_verifier_is_method_valid_generic_instantiation (MonoMethod *method) { if (!method->is_inflated) return TRUE; return mono_method_is_valid_generic_instantiation (NULL, method); } #else gboolean mono_verifier_verify_class (MonoClass *class) { /* The verifier was disabled at compile time */ return TRUE; } GSList* mono_method_verify_with_current_settings (MonoMethod *method, gboolean skip_visibility) { /* The verifier was disabled at compile time */ return NULL; } gboolean mono_verifier_is_class_full_trust (MonoClass *klass) { /* The verifier was disabled at compile time */ return TRUE; } gboolean mono_verifier_is_method_full_trust (MonoMethod *method) { /* The verifier was disabled at compile time */ return TRUE; } gboolean mono_verifier_is_enabled_for_image (MonoImage *image) { /* The verifier was disabled at compile time */ return FALSE; } gboolean mono_verifier_is_enabled_for_class (MonoClass *klass) { /* The verifier was disabled at compile time */ return FALSE; } gboolean mono_verifier_is_enabled_for_method (MonoMethod *method) { /* The verifier was disabled at compile time */ return FALSE; } GSList* mono_method_verify (MonoMethod *method, int level) { /* The verifier was disabled at compile time */ return NULL; } void mono_free_verify_list (GSList *list) { /* The verifier was disabled at compile time */ /* will always be null if verifier is disabled */ } GSList* mono_image_verify_tables (MonoImage *image, int level) { /* The verifier was disabled at compile time */ return NULL; } gboolean mono_verifier_class_is_valid_generic_instantiation (MonoClass *class) { return TRUE; } gboolean mono_verifier_is_method_valid_generic_instantiation (MonoMethod *method) { return TRUE; } #endif
./CrossVul/dataset_final_sorted/CWE-20/c/good_4716_2
crossvul-cpp_data_bad_2891_2
/* Large capacity key type * * Copyright (C) 2017 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved. * Copyright (C) 2013 Red Hat, Inc. All Rights Reserved. * Written by David Howells (dhowells@redhat.com) * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public Licence * as published by the Free Software Foundation; either version * 2 of the Licence, or (at your option) any later version. */ #define pr_fmt(fmt) "big_key: "fmt #include <linux/init.h> #include <linux/seq_file.h> #include <linux/file.h> #include <linux/shmem_fs.h> #include <linux/err.h> #include <linux/scatterlist.h> #include <linux/random.h> #include <keys/user-type.h> #include <keys/big_key-type.h> #include <crypto/aead.h> /* * Layout of key payload words. */ enum { big_key_data, big_key_path, big_key_path_2nd_part, big_key_len, }; /* * Crypto operation with big_key data */ enum big_key_op { BIG_KEY_ENC, BIG_KEY_DEC, }; /* * If the data is under this limit, there's no point creating a shm file to * hold it as the permanently resident metadata for the shmem fs will be at * least as large as the data. */ #define BIG_KEY_FILE_THRESHOLD (sizeof(struct inode) + sizeof(struct dentry)) /* * Key size for big_key data encryption */ #define ENC_KEY_SIZE 32 /* * Authentication tag length */ #define ENC_AUTHTAG_SIZE 16 /* * big_key defined keys take an arbitrary string as the description and an * arbitrary blob of data as the payload */ struct key_type key_type_big_key = { .name = "big_key", .preparse = big_key_preparse, .free_preparse = big_key_free_preparse, .instantiate = generic_key_instantiate, .revoke = big_key_revoke, .destroy = big_key_destroy, .describe = big_key_describe, .read = big_key_read, /* no ->update(); don't add it without changing big_key_crypt() nonce */ }; /* * Crypto names for big_key data authenticated encryption */ static const char big_key_alg_name[] = "gcm(aes)"; /* * Crypto algorithms for big_key data authenticated encryption */ static struct crypto_aead *big_key_aead; /* * Since changing the key affects the entire object, we need a mutex. */ static DEFINE_MUTEX(big_key_aead_lock); /* * Encrypt/decrypt big_key data */ static int big_key_crypt(enum big_key_op op, u8 *data, size_t datalen, u8 *key) { int ret; struct scatterlist sgio; struct aead_request *aead_req; /* We always use a zero nonce. The reason we can get away with this is * because we're using a different randomly generated key for every * different encryption. Notably, too, key_type_big_key doesn't define * an .update function, so there's no chance we'll wind up reusing the * key to encrypt updated data. Simply put: one key, one encryption. */ u8 zero_nonce[crypto_aead_ivsize(big_key_aead)]; aead_req = aead_request_alloc(big_key_aead, GFP_KERNEL); if (!aead_req) return -ENOMEM; memset(zero_nonce, 0, sizeof(zero_nonce)); sg_init_one(&sgio, data, datalen + (op == BIG_KEY_ENC ? ENC_AUTHTAG_SIZE : 0)); aead_request_set_crypt(aead_req, &sgio, &sgio, datalen, zero_nonce); aead_request_set_callback(aead_req, CRYPTO_TFM_REQ_MAY_SLEEP, NULL, NULL); aead_request_set_ad(aead_req, 0); mutex_lock(&big_key_aead_lock); if (crypto_aead_setkey(big_key_aead, key, ENC_KEY_SIZE)) { ret = -EAGAIN; goto error; } if (op == BIG_KEY_ENC) ret = crypto_aead_encrypt(aead_req); else ret = crypto_aead_decrypt(aead_req); error: mutex_unlock(&big_key_aead_lock); aead_request_free(aead_req); return ret; } /* * Preparse a big key */ int big_key_preparse(struct key_preparsed_payload *prep) { struct path *path = (struct path *)&prep->payload.data[big_key_path]; struct file *file; u8 *enckey; u8 *data = NULL; ssize_t written; size_t datalen = prep->datalen; int ret; ret = -EINVAL; if (datalen <= 0 || datalen > 1024 * 1024 || !prep->data) goto error; /* Set an arbitrary quota */ prep->quotalen = 16; prep->payload.data[big_key_len] = (void *)(unsigned long)datalen; if (datalen > BIG_KEY_FILE_THRESHOLD) { /* Create a shmem file to store the data in. This will permit the data * to be swapped out if needed. * * File content is stored encrypted with randomly generated key. */ size_t enclen = datalen + ENC_AUTHTAG_SIZE; loff_t pos = 0; data = kmalloc(enclen, GFP_KERNEL); if (!data) return -ENOMEM; memcpy(data, prep->data, datalen); /* generate random key */ enckey = kmalloc(ENC_KEY_SIZE, GFP_KERNEL); if (!enckey) { ret = -ENOMEM; goto error; } ret = get_random_bytes_wait(enckey, ENC_KEY_SIZE); if (unlikely(ret)) goto err_enckey; /* encrypt aligned data */ ret = big_key_crypt(BIG_KEY_ENC, data, datalen, enckey); if (ret) goto err_enckey; /* save aligned data to file */ file = shmem_kernel_file_setup("", enclen, 0); if (IS_ERR(file)) { ret = PTR_ERR(file); goto err_enckey; } written = kernel_write(file, data, enclen, &pos); if (written != enclen) { ret = written; if (written >= 0) ret = -ENOMEM; goto err_fput; } /* Pin the mount and dentry to the key so that we can open it again * later */ prep->payload.data[big_key_data] = enckey; *path = file->f_path; path_get(path); fput(file); kzfree(data); } else { /* Just store the data in a buffer */ void *data = kmalloc(datalen, GFP_KERNEL); if (!data) return -ENOMEM; prep->payload.data[big_key_data] = data; memcpy(data, prep->data, prep->datalen); } return 0; err_fput: fput(file); err_enckey: kzfree(enckey); error: kzfree(data); return ret; } /* * Clear preparsement. */ void big_key_free_preparse(struct key_preparsed_payload *prep) { if (prep->datalen > BIG_KEY_FILE_THRESHOLD) { struct path *path = (struct path *)&prep->payload.data[big_key_path]; path_put(path); } kzfree(prep->payload.data[big_key_data]); } /* * dispose of the links from a revoked keyring * - called with the key sem write-locked */ void big_key_revoke(struct key *key) { struct path *path = (struct path *)&key->payload.data[big_key_path]; /* clear the quota */ key_payload_reserve(key, 0); if (key_is_instantiated(key) && (size_t)key->payload.data[big_key_len] > BIG_KEY_FILE_THRESHOLD) vfs_truncate(path, 0); } /* * dispose of the data dangling from the corpse of a big_key key */ void big_key_destroy(struct key *key) { size_t datalen = (size_t)key->payload.data[big_key_len]; if (datalen > BIG_KEY_FILE_THRESHOLD) { struct path *path = (struct path *)&key->payload.data[big_key_path]; path_put(path); path->mnt = NULL; path->dentry = NULL; } kzfree(key->payload.data[big_key_data]); key->payload.data[big_key_data] = NULL; } /* * describe the big_key key */ void big_key_describe(const struct key *key, struct seq_file *m) { size_t datalen = (size_t)key->payload.data[big_key_len]; seq_puts(m, key->description); if (key_is_instantiated(key)) seq_printf(m, ": %zu [%s]", datalen, datalen > BIG_KEY_FILE_THRESHOLD ? "file" : "buff"); } /* * read the key data * - the key's semaphore is read-locked */ long big_key_read(const struct key *key, char __user *buffer, size_t buflen) { size_t datalen = (size_t)key->payload.data[big_key_len]; long ret; if (!buffer || buflen < datalen) return datalen; if (datalen > BIG_KEY_FILE_THRESHOLD) { struct path *path = (struct path *)&key->payload.data[big_key_path]; struct file *file; u8 *data; u8 *enckey = (u8 *)key->payload.data[big_key_data]; size_t enclen = datalen + ENC_AUTHTAG_SIZE; loff_t pos = 0; data = kmalloc(enclen, GFP_KERNEL); if (!data) return -ENOMEM; file = dentry_open(path, O_RDONLY, current_cred()); if (IS_ERR(file)) { ret = PTR_ERR(file); goto error; } /* read file to kernel and decrypt */ ret = kernel_read(file, data, enclen, &pos); if (ret >= 0 && ret != enclen) { ret = -EIO; goto err_fput; } ret = big_key_crypt(BIG_KEY_DEC, data, enclen, enckey); if (ret) goto err_fput; ret = datalen; /* copy decrypted data to user */ if (copy_to_user(buffer, data, datalen) != 0) ret = -EFAULT; err_fput: fput(file); error: kzfree(data); } else { ret = datalen; if (copy_to_user(buffer, key->payload.data[big_key_data], datalen) != 0) ret = -EFAULT; } return ret; } /* * Register key type */ static int __init big_key_init(void) { int ret; /* init block cipher */ big_key_aead = crypto_alloc_aead(big_key_alg_name, 0, CRYPTO_ALG_ASYNC); if (IS_ERR(big_key_aead)) { ret = PTR_ERR(big_key_aead); pr_err("Can't alloc crypto: %d\n", ret); return ret; } ret = crypto_aead_setauthsize(big_key_aead, ENC_AUTHTAG_SIZE); if (ret < 0) { pr_err("Can't set crypto auth tag len: %d\n", ret); goto free_aead; } ret = register_key_type(&key_type_big_key); if (ret < 0) { pr_err("Can't register type: %d\n", ret); goto free_aead; } return 0; free_aead: crypto_free_aead(big_key_aead); return ret; } late_initcall(big_key_init);
./CrossVul/dataset_final_sorted/CWE-20/c/bad_2891_2
crossvul-cpp_data_good_3480_0
// TODO some minor issues /* * This file is subject to the terms and conditions of the GNU General Public * License. See the file "COPYING" in the main directory of this archive * for more details. * * Copyright (C) 2001 - 2007 Tensilica Inc. * * Joe Taylor <joe@tensilica.com, joetylr@yahoo.com> * Chris Zankel <chris@zankel.net> * Scott Foehner<sfoehner@yahoo.com>, * Kevin Chea * Marc Gauthier<marc@tensilica.com> <marc@alumni.uwaterloo.ca> */ #include <linux/kernel.h> #include <linux/sched.h> #include <linux/mm.h> #include <linux/errno.h> #include <linux/ptrace.h> #include <linux/smp.h> #include <linux/security.h> #include <linux/signal.h> #include <asm/pgtable.h> #include <asm/page.h> #include <asm/system.h> #include <asm/uaccess.h> #include <asm/ptrace.h> #include <asm/elf.h> #include <asm/coprocessor.h> void user_enable_single_step(struct task_struct *child) { child->ptrace |= PT_SINGLESTEP; } void user_disable_single_step(struct task_struct *child) { child->ptrace &= ~PT_SINGLESTEP; } /* * Called by kernel/ptrace.c when detaching to disable single stepping. */ void ptrace_disable(struct task_struct *child) { /* Nothing to do.. */ } int ptrace_getregs(struct task_struct *child, void __user *uregs) { struct pt_regs *regs = task_pt_regs(child); xtensa_gregset_t __user *gregset = uregs; unsigned long wm = regs->wmask; unsigned long wb = regs->windowbase; int live, i; if (!access_ok(VERIFY_WRITE, uregs, sizeof(xtensa_gregset_t))) return -EIO; __put_user(regs->pc, &gregset->pc); __put_user(regs->ps & ~(1 << PS_EXCM_BIT), &gregset->ps); __put_user(regs->lbeg, &gregset->lbeg); __put_user(regs->lend, &gregset->lend); __put_user(regs->lcount, &gregset->lcount); __put_user(regs->windowstart, &gregset->windowstart); __put_user(regs->windowbase, &gregset->windowbase); live = (wm & 2) ? 4 : (wm & 4) ? 8 : (wm & 8) ? 12 : 16; for (i = 0; i < live; i++) __put_user(regs->areg[i],gregset->a+((wb*4+i)%XCHAL_NUM_AREGS)); for (i = XCHAL_NUM_AREGS - (wm >> 4) * 4; i < XCHAL_NUM_AREGS; i++) __put_user(regs->areg[i],gregset->a+((wb*4+i)%XCHAL_NUM_AREGS)); return 0; } int ptrace_setregs(struct task_struct *child, void __user *uregs) { struct pt_regs *regs = task_pt_regs(child); xtensa_gregset_t *gregset = uregs; const unsigned long ps_mask = PS_CALLINC_MASK | PS_OWB_MASK; unsigned long ps; unsigned long wb; if (!access_ok(VERIFY_WRITE, uregs, sizeof(xtensa_gregset_t))) return -EIO; __get_user(regs->pc, &gregset->pc); __get_user(ps, &gregset->ps); __get_user(regs->lbeg, &gregset->lbeg); __get_user(regs->lend, &gregset->lend); __get_user(regs->lcount, &gregset->lcount); __get_user(regs->windowstart, &gregset->windowstart); __get_user(wb, &gregset->windowbase); regs->ps = (regs->ps & ~ps_mask) | (ps & ps_mask) | (1 << PS_EXCM_BIT); if (wb >= XCHAL_NUM_AREGS / 4) return -EFAULT; regs->windowbase = wb; if (wb != 0 && __copy_from_user(regs->areg + XCHAL_NUM_AREGS - wb * 4, gregset->a, wb * 16)) return -EFAULT; if (__copy_from_user(regs->areg, gregset->a + wb*4, (WSBITS-wb) * 16)) return -EFAULT; return 0; } int ptrace_getxregs(struct task_struct *child, void __user *uregs) { struct pt_regs *regs = task_pt_regs(child); struct thread_info *ti = task_thread_info(child); elf_xtregs_t __user *xtregs = uregs; int ret = 0; if (!access_ok(VERIFY_WRITE, uregs, sizeof(elf_xtregs_t))) return -EIO; #if XTENSA_HAVE_COPROCESSORS /* Flush all coprocessor registers to memory. */ coprocessor_flush_all(ti); ret |= __copy_to_user(&xtregs->cp0, &ti->xtregs_cp, sizeof(xtregs_coprocessor_t)); #endif ret |= __copy_to_user(&xtregs->opt, &regs->xtregs_opt, sizeof(xtregs->opt)); ret |= __copy_to_user(&xtregs->user,&ti->xtregs_user, sizeof(xtregs->user)); return ret ? -EFAULT : 0; } int ptrace_setxregs(struct task_struct *child, void __user *uregs) { struct thread_info *ti = task_thread_info(child); struct pt_regs *regs = task_pt_regs(child); elf_xtregs_t *xtregs = uregs; int ret = 0; if (!access_ok(VERIFY_READ, uregs, sizeof(elf_xtregs_t))) return -EFAULT; #if XTENSA_HAVE_COPROCESSORS /* Flush all coprocessors before we overwrite them. */ coprocessor_flush_all(ti); coprocessor_release_all(ti); ret |= __copy_from_user(&ti->xtregs_cp, &xtregs->cp0, sizeof(xtregs_coprocessor_t)); #endif ret |= __copy_from_user(&regs->xtregs_opt, &xtregs->opt, sizeof(xtregs->opt)); ret |= __copy_from_user(&ti->xtregs_user, &xtregs->user, sizeof(xtregs->user)); return ret ? -EFAULT : 0; } int ptrace_peekusr(struct task_struct *child, long regno, long __user *ret) { struct pt_regs *regs; unsigned long tmp; regs = task_pt_regs(child); tmp = 0; /* Default return value. */ switch(regno) { case REG_AR_BASE ... REG_AR_BASE + XCHAL_NUM_AREGS - 1: tmp = regs->areg[regno - REG_AR_BASE]; break; case REG_A_BASE ... REG_A_BASE + 15: tmp = regs->areg[regno - REG_A_BASE]; break; case REG_PC: tmp = regs->pc; break; case REG_PS: /* Note: PS.EXCM is not set while user task is running; * its being set in regs is for exception handling * convenience. */ tmp = (regs->ps & ~(1 << PS_EXCM_BIT)); break; case REG_WB: break; /* tmp = 0 */ case REG_WS: { unsigned long wb = regs->windowbase; unsigned long ws = regs->windowstart; tmp = ((ws>>wb) | (ws<<(WSBITS-wb))) & ((1<<WSBITS)-1); break; } case REG_LBEG: tmp = regs->lbeg; break; case REG_LEND: tmp = regs->lend; break; case REG_LCOUNT: tmp = regs->lcount; break; case REG_SAR: tmp = regs->sar; break; case SYSCALL_NR: tmp = regs->syscall; break; default: return -EIO; } return put_user(tmp, ret); } int ptrace_pokeusr(struct task_struct *child, long regno, long val) { struct pt_regs *regs; regs = task_pt_regs(child); switch (regno) { case REG_AR_BASE ... REG_AR_BASE + XCHAL_NUM_AREGS - 1: regs->areg[regno - REG_AR_BASE] = val; break; case REG_A_BASE ... REG_A_BASE + 15: regs->areg[regno - REG_A_BASE] = val; break; case REG_PC: regs->pc = val; break; case SYSCALL_NR: regs->syscall = val; break; default: return -EIO; } return 0; } long arch_ptrace(struct task_struct *child, long request, unsigned long addr, unsigned long data) { int ret = -EPERM; void __user *datap = (void __user *) data; switch (request) { case PTRACE_PEEKTEXT: /* read word at location addr. */ case PTRACE_PEEKDATA: ret = generic_ptrace_peekdata(child, addr, data); break; case PTRACE_PEEKUSR: /* read register specified by addr. */ ret = ptrace_peekusr(child, addr, datap); break; case PTRACE_POKETEXT: /* write the word at location addr. */ case PTRACE_POKEDATA: ret = generic_ptrace_pokedata(child, addr, data); break; case PTRACE_POKEUSR: /* write register specified by addr. */ ret = ptrace_pokeusr(child, addr, data); break; case PTRACE_GETREGS: ret = ptrace_getregs(child, datap); break; case PTRACE_SETREGS: ret = ptrace_setregs(child, datap); break; case PTRACE_GETXTREGS: ret = ptrace_getxregs(child, datap); break; case PTRACE_SETXTREGS: ret = ptrace_setxregs(child, datap); break; default: ret = ptrace_request(child, request, addr, data); break; } return ret; } void do_syscall_trace(void) { /* * The 0x80 provides a way for the tracing parent to distinguish * between a syscall stop and SIGTRAP delivery */ ptrace_notify(SIGTRAP|((current->ptrace & PT_TRACESYSGOOD) ? 0x80 : 0)); /* * this isn't the same as continuing with a signal, but it will do * for normal use. strace only continues with a signal if the * stopping signal is not SIGTRAP. -brl */ if (current->exit_code) { send_sig(current->exit_code, current, 1); current->exit_code = 0; } } void do_syscall_trace_enter(struct pt_regs *regs) { if (test_thread_flag(TIF_SYSCALL_TRACE) && (current->ptrace & PT_PTRACED)) do_syscall_trace(); #if 0 if (unlikely(current->audit_context)) audit_syscall_entry(current, AUDIT_ARCH_XTENSA..); #endif } void do_syscall_trace_leave(struct pt_regs *regs) { if ((test_thread_flag(TIF_SYSCALL_TRACE)) && (current->ptrace & PT_PTRACED)) do_syscall_trace(); }
./CrossVul/dataset_final_sorted/CWE-20/c/good_3480_0
crossvul-cpp_data_bad_5113_0
/* netscreen.c * * Juniper NetScreen snoop output parser * Created by re-using a lot of code from cosine.c * Copyright (c) 2007 by Sake Blok <sake@euronet.nl> * * Wiretap Library * Copyright (c) 1998 by Gilbert Ramirez <gram@alumni.rice.edu> * * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "config.h" #include "wtap-int.h" #include "netscreen.h" #include "file_wrappers.h" #include <stdlib.h> #include <string.h> /* XXX TODO: * * o Construct a list of interfaces, with interface names, give * them link-layer types based on the interface name and packet * data, and supply interface IDs with each packet (i.e., make * this supply a pcap-ng-style set of interfaces and associate * packets with interfaces). This is probably the right way * to "Pass the interface names and the traffic direction to either * the frame-structure, a pseudo-header or use PPI." See the * message at * * http://www.wireshark.org/lists/wireshark-dev/200708/msg00029.html * * to see whether any further discussion is still needed. I suspect * it doesn't; pcap-NG existed at the time, as per the final * message in that thread: * * http://www.wireshark.org/lists/wireshark-dev/200708/msg00039.html * * but I don't think we fully *supported* it at that point. Now * that we do, we have the infrastructure to support this, except * that we currently have no way to translate interface IDs to * interface names in the "frame" dissector or to supply interface * information as part of the packet metadata from Wiretap modules. * That should be fixed so that we can show interface information, * such as the interface name, in packet dissections from, for example, * pcap-NG captures. */ static gboolean info_line(const gchar *line); static gint64 netscreen_seek_next_packet(wtap *wth, int *err, gchar **err_info, char *hdr); static gboolean netscreen_check_file_type(wtap *wth, int *err, gchar **err_info); static gboolean netscreen_read(wtap *wth, int *err, gchar **err_info, gint64 *data_offset); static gboolean netscreen_seek_read(wtap *wth, gint64 seek_off, struct wtap_pkthdr *phdr, Buffer *buf, int *err, gchar **err_info); static gboolean parse_netscreen_packet(FILE_T fh, struct wtap_pkthdr *phdr, Buffer* buf, char *line, int *err, gchar **err_info); static int parse_single_hex_dump_line(char* rec, guint8 *buf, guint byte_offset); /* Returns TRUE if the line appears to be a line with protocol info. Otherwise it returns FALSE. */ static gboolean info_line(const gchar *line) { int i=NETSCREEN_SPACES_ON_INFO_LINE; while (i-- > 0) { if (g_ascii_isspace(*line)) { line++; continue; } else { return FALSE; } } return TRUE; } /* Seeks to the beginning of the next packet, and returns the byte offset. Copy the header line to hdr. Returns -1 on failure, and sets "*err" to the error and sets "*err_info" to null or an additional error string. */ static gint64 netscreen_seek_next_packet(wtap *wth, int *err, gchar **err_info, char *hdr) { gint64 cur_off; char buf[NETSCREEN_LINE_LENGTH]; while (1) { cur_off = file_tell(wth->fh); if (cur_off == -1) { /* Error */ *err = file_error(wth->fh, err_info); return -1; } if (file_gets(buf, sizeof(buf), wth->fh) == NULL) { /* EOF or error. */ *err = file_error(wth->fh, err_info); break; } if (strstr(buf, NETSCREEN_REC_MAGIC_STR1) || strstr(buf, NETSCREEN_REC_MAGIC_STR2)) { g_strlcpy(hdr, buf, NETSCREEN_LINE_LENGTH); return cur_off; } } return -1; } /* Look through the first part of a file to see if this is * NetScreen snoop output. * * Returns TRUE if it is, FALSE if it isn't or if we get an I/O error; * if we get an I/O error, "*err" will be set to a non-zero value and * "*err_info" is set to null or an additional error string. */ static gboolean netscreen_check_file_type(wtap *wth, int *err, gchar **err_info) { char buf[NETSCREEN_LINE_LENGTH]; guint reclen, line; buf[NETSCREEN_LINE_LENGTH-1] = '\0'; for (line = 0; line < NETSCREEN_HEADER_LINES_TO_CHECK; line++) { if (file_gets(buf, NETSCREEN_LINE_LENGTH, wth->fh) == NULL) { /* EOF or error. */ *err = file_error(wth->fh, err_info); return FALSE; } reclen = (guint) strlen(buf); if (reclen < strlen(NETSCREEN_HDR_MAGIC_STR1) || reclen < strlen(NETSCREEN_HDR_MAGIC_STR2)) { continue; } if (strstr(buf, NETSCREEN_HDR_MAGIC_STR1) || strstr(buf, NETSCREEN_HDR_MAGIC_STR2)) { return TRUE; } } *err = 0; return FALSE; } wtap_open_return_val netscreen_open(wtap *wth, int *err, gchar **err_info) { /* Look for a NetScreen snoop header line */ if (!netscreen_check_file_type(wth, err, err_info)) { if (*err != 0 && *err != WTAP_ERR_SHORT_READ) return WTAP_OPEN_ERROR; return WTAP_OPEN_NOT_MINE; } if (file_seek(wth->fh, 0L, SEEK_SET, err) == -1) /* rewind */ return WTAP_OPEN_ERROR; wth->file_encap = WTAP_ENCAP_UNKNOWN; wth->file_type_subtype = WTAP_FILE_TYPE_SUBTYPE_NETSCREEN; wth->snapshot_length = 0; /* not known */ wth->subtype_read = netscreen_read; wth->subtype_seek_read = netscreen_seek_read; wth->file_tsprec = WTAP_TSPREC_DSEC; return WTAP_OPEN_MINE; } /* Find the next packet and parse it; called from wtap_read(). */ static gboolean netscreen_read(wtap *wth, int *err, gchar **err_info, gint64 *data_offset) { gint64 offset; char line[NETSCREEN_LINE_LENGTH]; /* Find the next packet */ offset = netscreen_seek_next_packet(wth, err, err_info, line); if (offset < 0) return FALSE; /* Parse the header and convert the ASCII hex dump to binary data */ if (!parse_netscreen_packet(wth->fh, &wth->phdr, wth->frame_buffer, line, err, err_info)) return FALSE; /* * If the per-file encapsulation isn't known, set it to this * packet's encapsulation. * * If it *is* known, and it isn't this packet's encapsulation, * set it to WTAP_ENCAP_PER_PACKET, as this file doesn't * have a single encapsulation for all packets in the file. */ if (wth->file_encap == WTAP_ENCAP_UNKNOWN) wth->file_encap = wth->phdr.pkt_encap; else { if (wth->file_encap != wth->phdr.pkt_encap) wth->file_encap = WTAP_ENCAP_PER_PACKET; } *data_offset = offset; return TRUE; } /* Used to read packets in random-access fashion */ static gboolean netscreen_seek_read(wtap *wth, gint64 seek_off, struct wtap_pkthdr *phdr, Buffer *buf, int *err, gchar **err_info) { char line[NETSCREEN_LINE_LENGTH]; if (file_seek(wth->random_fh, seek_off, SEEK_SET, err) == -1) { return FALSE; } if (file_gets(line, NETSCREEN_LINE_LENGTH, wth->random_fh) == NULL) { *err = file_error(wth->random_fh, err_info); if (*err == 0) { *err = WTAP_ERR_SHORT_READ; } return FALSE; } return parse_netscreen_packet(wth->random_fh, phdr, buf, line, err, err_info); } /* Parses a packet record header. There are a few possible formats: * * XXX list extra formats here! 6843828.0: trust(o) len=98:00121ebbd132->00600868d659/0800 192.168.1.1 -> 192.168.1.10/6 vhl=45, tos=00, id=37739, frag=0000, ttl=64 tlen=84 tcp:ports 2222->2333, seq=3452113890, ack=1540618280, flag=5018/ACK 00 60 08 68 d6 59 00 12 1e bb d1 32 08 00 45 00 .`.h.Y.....2..E. 00 54 93 6b 00 00 40 06 63 dd c0 a8 01 01 c0 a8 .T.k..@.c....... 01 0a 08 ae 09 1d cd c3 13 e2 5b d3 f8 28 50 18 ..........[..(P. 1f d4 79 21 00 00 e7 76 89 64 16 e2 19 0a 80 09 ..y!...v.d...... 31 e7 04 28 04 58 f3 d9 b1 9f 3d 65 1a db d8 61 1..(.X....=e...a 2c 21 b6 d3 20 60 0c 8c 35 98 88 cf 20 91 0e a9 ,!...`..5....... 1d 0b .. */ static gboolean parse_netscreen_packet(FILE_T fh, struct wtap_pkthdr *phdr, Buffer* buf, char *line, int *err, gchar **err_info) { int sec; int dsec; char cap_int[NETSCREEN_MAX_INT_NAME_LENGTH]; char direction[2]; guint pkt_len; char cap_src[13]; char cap_dst[13]; guint8 *pd; gchar *p; int n, i = 0; guint offset = 0; gchar dststr[13]; phdr->rec_type = REC_TYPE_PACKET; phdr->presence_flags = WTAP_HAS_TS|WTAP_HAS_CAP_LEN; if (sscanf(line, "%9d.%9d: %15[a-z0-9/:.-](%1[io]) len=%9u:%12s->%12s/", &sec, &dsec, cap_int, direction, &pkt_len, cap_src, cap_dst) < 5) { *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup("netscreen: Can't parse packet-header"); return -1; } if (pkt_len > WTAP_MAX_PACKET_SIZE) { /* * Probably a corrupt capture file; don't blow up trying * to allocate space for an immensely-large packet. */ *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup_printf("netscreen: File has %u-byte packet, bigger than maximum of %u", pkt_len, WTAP_MAX_PACKET_SIZE); return FALSE; } /* * If direction[0] is 'o', the direction is NETSCREEN_EGRESS, * otherwise it's NETSCREEN_INGRESS. */ phdr->ts.secs = sec; phdr->ts.nsecs = dsec * 100000000; phdr->len = pkt_len; /* Make sure we have enough room for the packet */ ws_buffer_assure_space(buf, pkt_len); pd = ws_buffer_start_ptr(buf); while(1) { /* The last packet is not delimited by an empty line, but by EOF * So accept EOF as a valid delimiter too */ if (file_gets(line, NETSCREEN_LINE_LENGTH, fh) == NULL) { break; } /* * Skip blanks. * The number of blanks is not fixed - for wireless * interfaces, there may be 14 extra spaces before * the hex data. */ for (p = &line[0]; g_ascii_isspace(*p); p++) ; /* packets are delimited with empty lines */ if (*p == '\0') { break; } n = parse_single_hex_dump_line(p, pd, offset); /* the smallest packet has a length of 6 bytes, if * the first hex-data is less then check whether * it is a info-line and act accordingly */ if (offset == 0 && n < 6) { if (info_line(line)) { if (++i <= NETSCREEN_MAX_INFOLINES) { continue; } } else { *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup("netscreen: cannot parse hex-data"); return FALSE; } } /* If there is no more data and the line was not empty, * then there must be an error in the file */ if (n == -1) { *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup("netscreen: cannot parse hex-data"); return FALSE; } /* Adjust the offset to the data that was just added to the buffer */ offset += n; /* If there was more hex-data than was announced in the len=x * header, then then there must be an error in the file */ if (offset > pkt_len) { *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup("netscreen: too much hex-data"); return FALSE; } } /* * Determine the encapsulation type, based on the * first 4 characters of the interface name * * XXX convert this to a 'case' structure when adding more * (non-ethernet) interfacetypes */ if (strncmp(cap_int, "adsl", 4) == 0) { /* The ADSL interface can be bridged with or without * PPP encapsulation. Check whether the first six bytes * of the hex data are the same as the destination mac * address in the header. If they are, assume ethernet * LinkLayer or else PPP */ g_snprintf(dststr, 13, "%02x%02x%02x%02x%02x%02x", pd[0], pd[1], pd[2], pd[3], pd[4], pd[5]); if (strncmp(dststr, cap_dst, 12) == 0) phdr->pkt_encap = WTAP_ENCAP_ETHERNET; else phdr->pkt_encap = WTAP_ENCAP_PPP; } else if (strncmp(cap_int, "seri", 4) == 0) phdr->pkt_encap = WTAP_ENCAP_PPP; else phdr->pkt_encap = WTAP_ENCAP_ETHERNET; phdr->caplen = offset; return TRUE; } /* Take a string representing one line from a hex dump, with leading white * space removed, and converts the text to binary data. We place the bytes * in the buffer at the specified offset. * * Returns number of bytes successfully read, -1 if bad. */ static int parse_single_hex_dump_line(char* rec, guint8 *buf, guint byte_offset) { int num_items_scanned; guint8 character; guint8 byte; for (num_items_scanned = 0; num_items_scanned < 16; num_items_scanned++) { character = *rec++; if (character >= '0' && character <= '9') byte = character - '0' + 0; else if (character >= 'A' && character <= 'F') byte = character - 'A' + 0xA; else if (character >= 'a' && character <= 'f') byte = character - 'a' + 0xa; else if (character == ' ' || character == '\r' || character == '\n' || character == '\0') { /* Nothing more to parse */ break; } else return -1; /* not a hex digit, space before ASCII dump, or EOL */ byte <<= 4; character = *rec++ & 0xFF; if (character >= '0' && character <= '9') byte += character - '0' + 0; else if (character >= 'A' && character <= 'F') byte += character - 'A' + 0xA; else if (character >= 'a' && character <= 'f') byte += character - 'a' + 0xa; else return -1; /* not a hex digit */ buf[byte_offset + num_items_scanned] = byte; character = *rec++ & 0xFF; if (character == '\0' || character == '\r' || character == '\n') { /* Nothing more to parse */ break; } else if (character != ' ') { /* not space before ASCII dump */ return -1; } } if (num_items_scanned == 0) return -1; return num_items_scanned; } /* * Editor modelines - http://www.wireshark.org/tools/modelines.html * * Local variables: * c-basic-offset: 8 * tab-width: 8 * indent-tabs-mode: t * End: * * vi: set shiftwidth=8 tabstop=8 noexpandtab: * :indentSize=8:tabSize=8:noTabs=false: */
./CrossVul/dataset_final_sorted/CWE-20/c/bad_5113_0
crossvul-cpp_data_good_2117_1
/* * Copyright (c) 2005 Voltaire Inc. All rights reserved. * Copyright (c) 2002-2005, Network Appliance, Inc. All rights reserved. * Copyright (c) 1999-2005, Mellanox Technologies, Inc. All rights reserved. * Copyright (c) 2005-2006 Intel Corporation. All rights reserved. * * This software is available to you under a choice of one of two * licenses. You may choose to be licensed under the terms of the GNU * General Public License (GPL) Version 2, available from the file * COPYING in the main directory of this source tree, or the * OpenIB.org BSD license below: * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * - Redistributions of source code must retain the above * copyright notice, this list of conditions and the following * disclaimer. * * - Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include <linux/completion.h> #include <linux/in.h> #include <linux/in6.h> #include <linux/mutex.h> #include <linux/random.h> #include <linux/idr.h> #include <linux/inetdevice.h> #include <linux/slab.h> #include <linux/module.h> #include <net/route.h> #include <net/tcp.h> #include <net/ipv6.h> #include <rdma/rdma_cm.h> #include <rdma/rdma_cm_ib.h> #include <rdma/rdma_netlink.h> #include <rdma/ib.h> #include <rdma/ib_cache.h> #include <rdma/ib_cm.h> #include <rdma/ib_sa.h> #include <rdma/iw_cm.h> MODULE_AUTHOR("Sean Hefty"); MODULE_DESCRIPTION("Generic RDMA CM Agent"); MODULE_LICENSE("Dual BSD/GPL"); #define CMA_CM_RESPONSE_TIMEOUT 20 #define CMA_MAX_CM_RETRIES 15 #define CMA_CM_MRA_SETTING (IB_CM_MRA_FLAG_DELAY | 24) #define CMA_IBOE_PACKET_LIFETIME 18 static void cma_add_one(struct ib_device *device); static void cma_remove_one(struct ib_device *device); static struct ib_client cma_client = { .name = "cma", .add = cma_add_one, .remove = cma_remove_one }; static struct ib_sa_client sa_client; static struct rdma_addr_client addr_client; static LIST_HEAD(dev_list); static LIST_HEAD(listen_any_list); static DEFINE_MUTEX(lock); static struct workqueue_struct *cma_wq; static DEFINE_IDR(tcp_ps); static DEFINE_IDR(udp_ps); static DEFINE_IDR(ipoib_ps); static DEFINE_IDR(ib_ps); struct cma_device { struct list_head list; struct ib_device *device; struct completion comp; atomic_t refcount; struct list_head id_list; }; struct rdma_bind_list { struct idr *ps; struct hlist_head owners; unsigned short port; }; enum { CMA_OPTION_AFONLY, }; /* * Device removal can occur at anytime, so we need extra handling to * serialize notifying the user of device removal with other callbacks. * We do this by disabling removal notification while a callback is in process, * and reporting it after the callback completes. */ struct rdma_id_private { struct rdma_cm_id id; struct rdma_bind_list *bind_list; struct hlist_node node; struct list_head list; /* listen_any_list or cma_device.list */ struct list_head listen_list; /* per device listens */ struct cma_device *cma_dev; struct list_head mc_list; int internal_id; enum rdma_cm_state state; spinlock_t lock; struct mutex qp_mutex; struct completion comp; atomic_t refcount; struct mutex handler_mutex; int backlog; int timeout_ms; struct ib_sa_query *query; int query_id; union { struct ib_cm_id *ib; struct iw_cm_id *iw; } cm_id; u32 seq_num; u32 qkey; u32 qp_num; pid_t owner; u32 options; u8 srq; u8 tos; u8 reuseaddr; u8 afonly; }; struct cma_multicast { struct rdma_id_private *id_priv; union { struct ib_sa_multicast *ib; } multicast; struct list_head list; void *context; struct sockaddr_storage addr; struct kref mcref; }; struct cma_work { struct work_struct work; struct rdma_id_private *id; enum rdma_cm_state old_state; enum rdma_cm_state new_state; struct rdma_cm_event event; }; struct cma_ndev_work { struct work_struct work; struct rdma_id_private *id; struct rdma_cm_event event; }; struct iboe_mcast_work { struct work_struct work; struct rdma_id_private *id; struct cma_multicast *mc; }; union cma_ip_addr { struct in6_addr ip6; struct { __be32 pad[3]; __be32 addr; } ip4; }; struct cma_hdr { u8 cma_version; u8 ip_version; /* IP version: 7:4 */ __be16 port; union cma_ip_addr src_addr; union cma_ip_addr dst_addr; }; #define CMA_VERSION 0x00 static int cma_comp(struct rdma_id_private *id_priv, enum rdma_cm_state comp) { unsigned long flags; int ret; spin_lock_irqsave(&id_priv->lock, flags); ret = (id_priv->state == comp); spin_unlock_irqrestore(&id_priv->lock, flags); return ret; } static int cma_comp_exch(struct rdma_id_private *id_priv, enum rdma_cm_state comp, enum rdma_cm_state exch) { unsigned long flags; int ret; spin_lock_irqsave(&id_priv->lock, flags); if ((ret = (id_priv->state == comp))) id_priv->state = exch; spin_unlock_irqrestore(&id_priv->lock, flags); return ret; } static enum rdma_cm_state cma_exch(struct rdma_id_private *id_priv, enum rdma_cm_state exch) { unsigned long flags; enum rdma_cm_state old; spin_lock_irqsave(&id_priv->lock, flags); old = id_priv->state; id_priv->state = exch; spin_unlock_irqrestore(&id_priv->lock, flags); return old; } static inline u8 cma_get_ip_ver(struct cma_hdr *hdr) { return hdr->ip_version >> 4; } static inline void cma_set_ip_ver(struct cma_hdr *hdr, u8 ip_ver) { hdr->ip_version = (ip_ver << 4) | (hdr->ip_version & 0xF); } static void cma_attach_to_dev(struct rdma_id_private *id_priv, struct cma_device *cma_dev) { atomic_inc(&cma_dev->refcount); id_priv->cma_dev = cma_dev; id_priv->id.device = cma_dev->device; id_priv->id.route.addr.dev_addr.transport = rdma_node_get_transport(cma_dev->device->node_type); list_add_tail(&id_priv->list, &cma_dev->id_list); } static inline void cma_deref_dev(struct cma_device *cma_dev) { if (atomic_dec_and_test(&cma_dev->refcount)) complete(&cma_dev->comp); } static inline void release_mc(struct kref *kref) { struct cma_multicast *mc = container_of(kref, struct cma_multicast, mcref); kfree(mc->multicast.ib); kfree(mc); } static void cma_release_dev(struct rdma_id_private *id_priv) { mutex_lock(&lock); list_del(&id_priv->list); cma_deref_dev(id_priv->cma_dev); id_priv->cma_dev = NULL; mutex_unlock(&lock); } static inline struct sockaddr *cma_src_addr(struct rdma_id_private *id_priv) { return (struct sockaddr *) &id_priv->id.route.addr.src_addr; } static inline struct sockaddr *cma_dst_addr(struct rdma_id_private *id_priv) { return (struct sockaddr *) &id_priv->id.route.addr.dst_addr; } static inline unsigned short cma_family(struct rdma_id_private *id_priv) { return id_priv->id.route.addr.src_addr.ss_family; } static int cma_set_qkey(struct rdma_id_private *id_priv, u32 qkey) { struct ib_sa_mcmember_rec rec; int ret = 0; if (id_priv->qkey) { if (qkey && id_priv->qkey != qkey) return -EINVAL; return 0; } if (qkey) { id_priv->qkey = qkey; return 0; } switch (id_priv->id.ps) { case RDMA_PS_UDP: case RDMA_PS_IB: id_priv->qkey = RDMA_UDP_QKEY; break; case RDMA_PS_IPOIB: ib_addr_get_mgid(&id_priv->id.route.addr.dev_addr, &rec.mgid); ret = ib_sa_get_mcmember_rec(id_priv->id.device, id_priv->id.port_num, &rec.mgid, &rec); if (!ret) id_priv->qkey = be32_to_cpu(rec.qkey); break; default: break; } return ret; } static void cma_translate_ib(struct sockaddr_ib *sib, struct rdma_dev_addr *dev_addr) { dev_addr->dev_type = ARPHRD_INFINIBAND; rdma_addr_set_sgid(dev_addr, (union ib_gid *) &sib->sib_addr); ib_addr_set_pkey(dev_addr, ntohs(sib->sib_pkey)); } static int cma_translate_addr(struct sockaddr *addr, struct rdma_dev_addr *dev_addr) { int ret; if (addr->sa_family != AF_IB) { ret = rdma_translate_ip(addr, dev_addr, NULL); } else { cma_translate_ib((struct sockaddr_ib *) addr, dev_addr); ret = 0; } return ret; } static int cma_acquire_dev(struct rdma_id_private *id_priv, struct rdma_id_private *listen_id_priv) { struct rdma_dev_addr *dev_addr = &id_priv->id.route.addr.dev_addr; struct cma_device *cma_dev; union ib_gid gid, iboe_gid; int ret = -ENODEV; u8 port, found_port; enum rdma_link_layer dev_ll = dev_addr->dev_type == ARPHRD_INFINIBAND ? IB_LINK_LAYER_INFINIBAND : IB_LINK_LAYER_ETHERNET; if (dev_ll != IB_LINK_LAYER_INFINIBAND && id_priv->id.ps == RDMA_PS_IPOIB) return -EINVAL; mutex_lock(&lock); rdma_ip2gid((struct sockaddr *)&id_priv->id.route.addr.src_addr, &iboe_gid); memcpy(&gid, dev_addr->src_dev_addr + rdma_addr_gid_offset(dev_addr), sizeof gid); if (listen_id_priv && rdma_port_get_link_layer(listen_id_priv->id.device, listen_id_priv->id.port_num) == dev_ll) { cma_dev = listen_id_priv->cma_dev; port = listen_id_priv->id.port_num; if (rdma_node_get_transport(cma_dev->device->node_type) == RDMA_TRANSPORT_IB && rdma_port_get_link_layer(cma_dev->device, port) == IB_LINK_LAYER_ETHERNET) ret = ib_find_cached_gid(cma_dev->device, &iboe_gid, &found_port, NULL); else ret = ib_find_cached_gid(cma_dev->device, &gid, &found_port, NULL); if (!ret && (port == found_port)) { id_priv->id.port_num = found_port; goto out; } } list_for_each_entry(cma_dev, &dev_list, list) { for (port = 1; port <= cma_dev->device->phys_port_cnt; ++port) { if (listen_id_priv && listen_id_priv->cma_dev == cma_dev && listen_id_priv->id.port_num == port) continue; if (rdma_port_get_link_layer(cma_dev->device, port) == dev_ll) { if (rdma_node_get_transport(cma_dev->device->node_type) == RDMA_TRANSPORT_IB && rdma_port_get_link_layer(cma_dev->device, port) == IB_LINK_LAYER_ETHERNET) ret = ib_find_cached_gid(cma_dev->device, &iboe_gid, &found_port, NULL); else ret = ib_find_cached_gid(cma_dev->device, &gid, &found_port, NULL); if (!ret && (port == found_port)) { id_priv->id.port_num = found_port; goto out; } } } } out: if (!ret) cma_attach_to_dev(id_priv, cma_dev); mutex_unlock(&lock); return ret; } /* * Select the source IB device and address to reach the destination IB address. */ static int cma_resolve_ib_dev(struct rdma_id_private *id_priv) { struct cma_device *cma_dev, *cur_dev; struct sockaddr_ib *addr; union ib_gid gid, sgid, *dgid; u16 pkey, index; u8 p; int i; cma_dev = NULL; addr = (struct sockaddr_ib *) cma_dst_addr(id_priv); dgid = (union ib_gid *) &addr->sib_addr; pkey = ntohs(addr->sib_pkey); list_for_each_entry(cur_dev, &dev_list, list) { if (rdma_node_get_transport(cur_dev->device->node_type) != RDMA_TRANSPORT_IB) continue; for (p = 1; p <= cur_dev->device->phys_port_cnt; ++p) { if (ib_find_cached_pkey(cur_dev->device, p, pkey, &index)) continue; for (i = 0; !ib_get_cached_gid(cur_dev->device, p, i, &gid); i++) { if (!memcmp(&gid, dgid, sizeof(gid))) { cma_dev = cur_dev; sgid = gid; id_priv->id.port_num = p; goto found; } if (!cma_dev && (gid.global.subnet_prefix == dgid->global.subnet_prefix)) { cma_dev = cur_dev; sgid = gid; id_priv->id.port_num = p; } } } } if (!cma_dev) return -ENODEV; found: cma_attach_to_dev(id_priv, cma_dev); addr = (struct sockaddr_ib *) cma_src_addr(id_priv); memcpy(&addr->sib_addr, &sgid, sizeof sgid); cma_translate_ib(addr, &id_priv->id.route.addr.dev_addr); return 0; } static void cma_deref_id(struct rdma_id_private *id_priv) { if (atomic_dec_and_test(&id_priv->refcount)) complete(&id_priv->comp); } static int cma_disable_callback(struct rdma_id_private *id_priv, enum rdma_cm_state state) { mutex_lock(&id_priv->handler_mutex); if (id_priv->state != state) { mutex_unlock(&id_priv->handler_mutex); return -EINVAL; } return 0; } struct rdma_cm_id *rdma_create_id(rdma_cm_event_handler event_handler, void *context, enum rdma_port_space ps, enum ib_qp_type qp_type) { struct rdma_id_private *id_priv; id_priv = kzalloc(sizeof *id_priv, GFP_KERNEL); if (!id_priv) return ERR_PTR(-ENOMEM); id_priv->owner = task_pid_nr(current); id_priv->state = RDMA_CM_IDLE; id_priv->id.context = context; id_priv->id.event_handler = event_handler; id_priv->id.ps = ps; id_priv->id.qp_type = qp_type; spin_lock_init(&id_priv->lock); mutex_init(&id_priv->qp_mutex); init_completion(&id_priv->comp); atomic_set(&id_priv->refcount, 1); mutex_init(&id_priv->handler_mutex); INIT_LIST_HEAD(&id_priv->listen_list); INIT_LIST_HEAD(&id_priv->mc_list); get_random_bytes(&id_priv->seq_num, sizeof id_priv->seq_num); return &id_priv->id; } EXPORT_SYMBOL(rdma_create_id); static int cma_init_ud_qp(struct rdma_id_private *id_priv, struct ib_qp *qp) { struct ib_qp_attr qp_attr; int qp_attr_mask, ret; qp_attr.qp_state = IB_QPS_INIT; ret = rdma_init_qp_attr(&id_priv->id, &qp_attr, &qp_attr_mask); if (ret) return ret; ret = ib_modify_qp(qp, &qp_attr, qp_attr_mask); if (ret) return ret; qp_attr.qp_state = IB_QPS_RTR; ret = ib_modify_qp(qp, &qp_attr, IB_QP_STATE); if (ret) return ret; qp_attr.qp_state = IB_QPS_RTS; qp_attr.sq_psn = 0; ret = ib_modify_qp(qp, &qp_attr, IB_QP_STATE | IB_QP_SQ_PSN); return ret; } static int cma_init_conn_qp(struct rdma_id_private *id_priv, struct ib_qp *qp) { struct ib_qp_attr qp_attr; int qp_attr_mask, ret; qp_attr.qp_state = IB_QPS_INIT; ret = rdma_init_qp_attr(&id_priv->id, &qp_attr, &qp_attr_mask); if (ret) return ret; return ib_modify_qp(qp, &qp_attr, qp_attr_mask); } int rdma_create_qp(struct rdma_cm_id *id, struct ib_pd *pd, struct ib_qp_init_attr *qp_init_attr) { struct rdma_id_private *id_priv; struct ib_qp *qp; int ret; id_priv = container_of(id, struct rdma_id_private, id); if (id->device != pd->device) return -EINVAL; qp = ib_create_qp(pd, qp_init_attr); if (IS_ERR(qp)) return PTR_ERR(qp); if (id->qp_type == IB_QPT_UD) ret = cma_init_ud_qp(id_priv, qp); else ret = cma_init_conn_qp(id_priv, qp); if (ret) goto err; id->qp = qp; id_priv->qp_num = qp->qp_num; id_priv->srq = (qp->srq != NULL); return 0; err: ib_destroy_qp(qp); return ret; } EXPORT_SYMBOL(rdma_create_qp); void rdma_destroy_qp(struct rdma_cm_id *id) { struct rdma_id_private *id_priv; id_priv = container_of(id, struct rdma_id_private, id); mutex_lock(&id_priv->qp_mutex); ib_destroy_qp(id_priv->id.qp); id_priv->id.qp = NULL; mutex_unlock(&id_priv->qp_mutex); } EXPORT_SYMBOL(rdma_destroy_qp); static int cma_modify_qp_rtr(struct rdma_id_private *id_priv, struct rdma_conn_param *conn_param) { struct ib_qp_attr qp_attr; int qp_attr_mask, ret; union ib_gid sgid; mutex_lock(&id_priv->qp_mutex); if (!id_priv->id.qp) { ret = 0; goto out; } /* Need to update QP attributes from default values. */ qp_attr.qp_state = IB_QPS_INIT; ret = rdma_init_qp_attr(&id_priv->id, &qp_attr, &qp_attr_mask); if (ret) goto out; ret = ib_modify_qp(id_priv->id.qp, &qp_attr, qp_attr_mask); if (ret) goto out; qp_attr.qp_state = IB_QPS_RTR; ret = rdma_init_qp_attr(&id_priv->id, &qp_attr, &qp_attr_mask); if (ret) goto out; ret = ib_query_gid(id_priv->id.device, id_priv->id.port_num, qp_attr.ah_attr.grh.sgid_index, &sgid); if (ret) goto out; if (rdma_node_get_transport(id_priv->cma_dev->device->node_type) == RDMA_TRANSPORT_IB && rdma_port_get_link_layer(id_priv->id.device, id_priv->id.port_num) == IB_LINK_LAYER_ETHERNET) { ret = rdma_addr_find_smac_by_sgid(&sgid, qp_attr.smac, NULL); if (ret) goto out; } if (conn_param) qp_attr.max_dest_rd_atomic = conn_param->responder_resources; ret = ib_modify_qp(id_priv->id.qp, &qp_attr, qp_attr_mask); out: mutex_unlock(&id_priv->qp_mutex); return ret; } static int cma_modify_qp_rts(struct rdma_id_private *id_priv, struct rdma_conn_param *conn_param) { struct ib_qp_attr qp_attr; int qp_attr_mask, ret; mutex_lock(&id_priv->qp_mutex); if (!id_priv->id.qp) { ret = 0; goto out; } qp_attr.qp_state = IB_QPS_RTS; ret = rdma_init_qp_attr(&id_priv->id, &qp_attr, &qp_attr_mask); if (ret) goto out; if (conn_param) qp_attr.max_rd_atomic = conn_param->initiator_depth; ret = ib_modify_qp(id_priv->id.qp, &qp_attr, qp_attr_mask); out: mutex_unlock(&id_priv->qp_mutex); return ret; } static int cma_modify_qp_err(struct rdma_id_private *id_priv) { struct ib_qp_attr qp_attr; int ret; mutex_lock(&id_priv->qp_mutex); if (!id_priv->id.qp) { ret = 0; goto out; } qp_attr.qp_state = IB_QPS_ERR; ret = ib_modify_qp(id_priv->id.qp, &qp_attr, IB_QP_STATE); out: mutex_unlock(&id_priv->qp_mutex); return ret; } static int cma_ib_init_qp_attr(struct rdma_id_private *id_priv, struct ib_qp_attr *qp_attr, int *qp_attr_mask) { struct rdma_dev_addr *dev_addr = &id_priv->id.route.addr.dev_addr; int ret; u16 pkey; if (rdma_port_get_link_layer(id_priv->id.device, id_priv->id.port_num) == IB_LINK_LAYER_INFINIBAND) pkey = ib_addr_get_pkey(dev_addr); else pkey = 0xffff; ret = ib_find_cached_pkey(id_priv->id.device, id_priv->id.port_num, pkey, &qp_attr->pkey_index); if (ret) return ret; qp_attr->port_num = id_priv->id.port_num; *qp_attr_mask = IB_QP_STATE | IB_QP_PKEY_INDEX | IB_QP_PORT; if (id_priv->id.qp_type == IB_QPT_UD) { ret = cma_set_qkey(id_priv, 0); if (ret) return ret; qp_attr->qkey = id_priv->qkey; *qp_attr_mask |= IB_QP_QKEY; } else { qp_attr->qp_access_flags = 0; *qp_attr_mask |= IB_QP_ACCESS_FLAGS; } return 0; } int rdma_init_qp_attr(struct rdma_cm_id *id, struct ib_qp_attr *qp_attr, int *qp_attr_mask) { struct rdma_id_private *id_priv; int ret = 0; id_priv = container_of(id, struct rdma_id_private, id); switch (rdma_node_get_transport(id_priv->id.device->node_type)) { case RDMA_TRANSPORT_IB: if (!id_priv->cm_id.ib || (id_priv->id.qp_type == IB_QPT_UD)) ret = cma_ib_init_qp_attr(id_priv, qp_attr, qp_attr_mask); else ret = ib_cm_init_qp_attr(id_priv->cm_id.ib, qp_attr, qp_attr_mask); if (qp_attr->qp_state == IB_QPS_RTR) qp_attr->rq_psn = id_priv->seq_num; break; case RDMA_TRANSPORT_IWARP: if (!id_priv->cm_id.iw) { qp_attr->qp_access_flags = 0; *qp_attr_mask = IB_QP_STATE | IB_QP_ACCESS_FLAGS; } else ret = iw_cm_init_qp_attr(id_priv->cm_id.iw, qp_attr, qp_attr_mask); break; default: ret = -ENOSYS; break; } return ret; } EXPORT_SYMBOL(rdma_init_qp_attr); static inline int cma_zero_addr(struct sockaddr *addr) { switch (addr->sa_family) { case AF_INET: return ipv4_is_zeronet(((struct sockaddr_in *)addr)->sin_addr.s_addr); case AF_INET6: return ipv6_addr_any(&((struct sockaddr_in6 *) addr)->sin6_addr); case AF_IB: return ib_addr_any(&((struct sockaddr_ib *) addr)->sib_addr); default: return 0; } } static inline int cma_loopback_addr(struct sockaddr *addr) { switch (addr->sa_family) { case AF_INET: return ipv4_is_loopback(((struct sockaddr_in *) addr)->sin_addr.s_addr); case AF_INET6: return ipv6_addr_loopback(&((struct sockaddr_in6 *) addr)->sin6_addr); case AF_IB: return ib_addr_loopback(&((struct sockaddr_ib *) addr)->sib_addr); default: return 0; } } static inline int cma_any_addr(struct sockaddr *addr) { return cma_zero_addr(addr) || cma_loopback_addr(addr); } static int cma_addr_cmp(struct sockaddr *src, struct sockaddr *dst) { if (src->sa_family != dst->sa_family) return -1; switch (src->sa_family) { case AF_INET: return ((struct sockaddr_in *) src)->sin_addr.s_addr != ((struct sockaddr_in *) dst)->sin_addr.s_addr; case AF_INET6: return ipv6_addr_cmp(&((struct sockaddr_in6 *) src)->sin6_addr, &((struct sockaddr_in6 *) dst)->sin6_addr); default: return ib_addr_cmp(&((struct sockaddr_ib *) src)->sib_addr, &((struct sockaddr_ib *) dst)->sib_addr); } } static __be16 cma_port(struct sockaddr *addr) { struct sockaddr_ib *sib; switch (addr->sa_family) { case AF_INET: return ((struct sockaddr_in *) addr)->sin_port; case AF_INET6: return ((struct sockaddr_in6 *) addr)->sin6_port; case AF_IB: sib = (struct sockaddr_ib *) addr; return htons((u16) (be64_to_cpu(sib->sib_sid) & be64_to_cpu(sib->sib_sid_mask))); default: return 0; } } static inline int cma_any_port(struct sockaddr *addr) { return !cma_port(addr); } static void cma_save_ib_info(struct rdma_cm_id *id, struct rdma_cm_id *listen_id, struct ib_sa_path_rec *path) { struct sockaddr_ib *listen_ib, *ib; listen_ib = (struct sockaddr_ib *) &listen_id->route.addr.src_addr; ib = (struct sockaddr_ib *) &id->route.addr.src_addr; ib->sib_family = listen_ib->sib_family; ib->sib_pkey = path->pkey; ib->sib_flowinfo = path->flow_label; memcpy(&ib->sib_addr, &path->sgid, 16); ib->sib_sid = listen_ib->sib_sid; ib->sib_sid_mask = cpu_to_be64(0xffffffffffffffffULL); ib->sib_scope_id = listen_ib->sib_scope_id; ib = (struct sockaddr_ib *) &id->route.addr.dst_addr; ib->sib_family = listen_ib->sib_family; ib->sib_pkey = path->pkey; ib->sib_flowinfo = path->flow_label; memcpy(&ib->sib_addr, &path->dgid, 16); } static void cma_save_ip4_info(struct rdma_cm_id *id, struct rdma_cm_id *listen_id, struct cma_hdr *hdr) { struct sockaddr_in *listen4, *ip4; listen4 = (struct sockaddr_in *) &listen_id->route.addr.src_addr; ip4 = (struct sockaddr_in *) &id->route.addr.src_addr; ip4->sin_family = listen4->sin_family; ip4->sin_addr.s_addr = hdr->dst_addr.ip4.addr; ip4->sin_port = listen4->sin_port; ip4 = (struct sockaddr_in *) &id->route.addr.dst_addr; ip4->sin_family = listen4->sin_family; ip4->sin_addr.s_addr = hdr->src_addr.ip4.addr; ip4->sin_port = hdr->port; } static void cma_save_ip6_info(struct rdma_cm_id *id, struct rdma_cm_id *listen_id, struct cma_hdr *hdr) { struct sockaddr_in6 *listen6, *ip6; listen6 = (struct sockaddr_in6 *) &listen_id->route.addr.src_addr; ip6 = (struct sockaddr_in6 *) &id->route.addr.src_addr; ip6->sin6_family = listen6->sin6_family; ip6->sin6_addr = hdr->dst_addr.ip6; ip6->sin6_port = listen6->sin6_port; ip6 = (struct sockaddr_in6 *) &id->route.addr.dst_addr; ip6->sin6_family = listen6->sin6_family; ip6->sin6_addr = hdr->src_addr.ip6; ip6->sin6_port = hdr->port; } static int cma_save_net_info(struct rdma_cm_id *id, struct rdma_cm_id *listen_id, struct ib_cm_event *ib_event) { struct cma_hdr *hdr; if ((listen_id->route.addr.src_addr.ss_family == AF_IB) && (ib_event->event == IB_CM_REQ_RECEIVED)) { cma_save_ib_info(id, listen_id, ib_event->param.req_rcvd.primary_path); return 0; } hdr = ib_event->private_data; if (hdr->cma_version != CMA_VERSION) return -EINVAL; switch (cma_get_ip_ver(hdr)) { case 4: cma_save_ip4_info(id, listen_id, hdr); break; case 6: cma_save_ip6_info(id, listen_id, hdr); break; default: return -EINVAL; } return 0; } static inline int cma_user_data_offset(struct rdma_id_private *id_priv) { return cma_family(id_priv) == AF_IB ? 0 : sizeof(struct cma_hdr); } static void cma_cancel_route(struct rdma_id_private *id_priv) { switch (rdma_port_get_link_layer(id_priv->id.device, id_priv->id.port_num)) { case IB_LINK_LAYER_INFINIBAND: if (id_priv->query) ib_sa_cancel_query(id_priv->query_id, id_priv->query); break; default: break; } } static void cma_cancel_listens(struct rdma_id_private *id_priv) { struct rdma_id_private *dev_id_priv; /* * Remove from listen_any_list to prevent added devices from spawning * additional listen requests. */ mutex_lock(&lock); list_del(&id_priv->list); while (!list_empty(&id_priv->listen_list)) { dev_id_priv = list_entry(id_priv->listen_list.next, struct rdma_id_private, listen_list); /* sync with device removal to avoid duplicate destruction */ list_del_init(&dev_id_priv->list); list_del(&dev_id_priv->listen_list); mutex_unlock(&lock); rdma_destroy_id(&dev_id_priv->id); mutex_lock(&lock); } mutex_unlock(&lock); } static void cma_cancel_operation(struct rdma_id_private *id_priv, enum rdma_cm_state state) { switch (state) { case RDMA_CM_ADDR_QUERY: rdma_addr_cancel(&id_priv->id.route.addr.dev_addr); break; case RDMA_CM_ROUTE_QUERY: cma_cancel_route(id_priv); break; case RDMA_CM_LISTEN: if (cma_any_addr(cma_src_addr(id_priv)) && !id_priv->cma_dev) cma_cancel_listens(id_priv); break; default: break; } } static void cma_release_port(struct rdma_id_private *id_priv) { struct rdma_bind_list *bind_list = id_priv->bind_list; if (!bind_list) return; mutex_lock(&lock); hlist_del(&id_priv->node); if (hlist_empty(&bind_list->owners)) { idr_remove(bind_list->ps, bind_list->port); kfree(bind_list); } mutex_unlock(&lock); } static void cma_leave_mc_groups(struct rdma_id_private *id_priv) { struct cma_multicast *mc; while (!list_empty(&id_priv->mc_list)) { mc = container_of(id_priv->mc_list.next, struct cma_multicast, list); list_del(&mc->list); switch (rdma_port_get_link_layer(id_priv->cma_dev->device, id_priv->id.port_num)) { case IB_LINK_LAYER_INFINIBAND: ib_sa_free_multicast(mc->multicast.ib); kfree(mc); break; case IB_LINK_LAYER_ETHERNET: kref_put(&mc->mcref, release_mc); break; default: break; } } } void rdma_destroy_id(struct rdma_cm_id *id) { struct rdma_id_private *id_priv; enum rdma_cm_state state; id_priv = container_of(id, struct rdma_id_private, id); state = cma_exch(id_priv, RDMA_CM_DESTROYING); cma_cancel_operation(id_priv, state); /* * Wait for any active callback to finish. New callbacks will find * the id_priv state set to destroying and abort. */ mutex_lock(&id_priv->handler_mutex); mutex_unlock(&id_priv->handler_mutex); if (id_priv->cma_dev) { switch (rdma_node_get_transport(id_priv->id.device->node_type)) { case RDMA_TRANSPORT_IB: if (id_priv->cm_id.ib) ib_destroy_cm_id(id_priv->cm_id.ib); break; case RDMA_TRANSPORT_IWARP: if (id_priv->cm_id.iw) iw_destroy_cm_id(id_priv->cm_id.iw); break; default: break; } cma_leave_mc_groups(id_priv); cma_release_dev(id_priv); } cma_release_port(id_priv); cma_deref_id(id_priv); wait_for_completion(&id_priv->comp); if (id_priv->internal_id) cma_deref_id(id_priv->id.context); kfree(id_priv->id.route.path_rec); kfree(id_priv); } EXPORT_SYMBOL(rdma_destroy_id); static int cma_rep_recv(struct rdma_id_private *id_priv) { int ret; ret = cma_modify_qp_rtr(id_priv, NULL); if (ret) goto reject; ret = cma_modify_qp_rts(id_priv, NULL); if (ret) goto reject; ret = ib_send_cm_rtu(id_priv->cm_id.ib, NULL, 0); if (ret) goto reject; return 0; reject: cma_modify_qp_err(id_priv); ib_send_cm_rej(id_priv->cm_id.ib, IB_CM_REJ_CONSUMER_DEFINED, NULL, 0, NULL, 0); return ret; } static void cma_set_rep_event_data(struct rdma_cm_event *event, struct ib_cm_rep_event_param *rep_data, void *private_data) { event->param.conn.private_data = private_data; event->param.conn.private_data_len = IB_CM_REP_PRIVATE_DATA_SIZE; event->param.conn.responder_resources = rep_data->responder_resources; event->param.conn.initiator_depth = rep_data->initiator_depth; event->param.conn.flow_control = rep_data->flow_control; event->param.conn.rnr_retry_count = rep_data->rnr_retry_count; event->param.conn.srq = rep_data->srq; event->param.conn.qp_num = rep_data->remote_qpn; } static int cma_ib_handler(struct ib_cm_id *cm_id, struct ib_cm_event *ib_event) { struct rdma_id_private *id_priv = cm_id->context; struct rdma_cm_event event; int ret = 0; if ((ib_event->event != IB_CM_TIMEWAIT_EXIT && cma_disable_callback(id_priv, RDMA_CM_CONNECT)) || (ib_event->event == IB_CM_TIMEWAIT_EXIT && cma_disable_callback(id_priv, RDMA_CM_DISCONNECT))) return 0; memset(&event, 0, sizeof event); switch (ib_event->event) { case IB_CM_REQ_ERROR: case IB_CM_REP_ERROR: event.event = RDMA_CM_EVENT_UNREACHABLE; event.status = -ETIMEDOUT; break; case IB_CM_REP_RECEIVED: if (id_priv->id.qp) { event.status = cma_rep_recv(id_priv); event.event = event.status ? RDMA_CM_EVENT_CONNECT_ERROR : RDMA_CM_EVENT_ESTABLISHED; } else { event.event = RDMA_CM_EVENT_CONNECT_RESPONSE; } cma_set_rep_event_data(&event, &ib_event->param.rep_rcvd, ib_event->private_data); break; case IB_CM_RTU_RECEIVED: case IB_CM_USER_ESTABLISHED: event.event = RDMA_CM_EVENT_ESTABLISHED; break; case IB_CM_DREQ_ERROR: event.status = -ETIMEDOUT; /* fall through */ case IB_CM_DREQ_RECEIVED: case IB_CM_DREP_RECEIVED: if (!cma_comp_exch(id_priv, RDMA_CM_CONNECT, RDMA_CM_DISCONNECT)) goto out; event.event = RDMA_CM_EVENT_DISCONNECTED; break; case IB_CM_TIMEWAIT_EXIT: event.event = RDMA_CM_EVENT_TIMEWAIT_EXIT; break; case IB_CM_MRA_RECEIVED: /* ignore event */ goto out; case IB_CM_REJ_RECEIVED: cma_modify_qp_err(id_priv); event.status = ib_event->param.rej_rcvd.reason; event.event = RDMA_CM_EVENT_REJECTED; event.param.conn.private_data = ib_event->private_data; event.param.conn.private_data_len = IB_CM_REJ_PRIVATE_DATA_SIZE; break; default: printk(KERN_ERR "RDMA CMA: unexpected IB CM event: %d\n", ib_event->event); goto out; } ret = id_priv->id.event_handler(&id_priv->id, &event); if (ret) { /* Destroy the CM ID by returning a non-zero value. */ id_priv->cm_id.ib = NULL; cma_exch(id_priv, RDMA_CM_DESTROYING); mutex_unlock(&id_priv->handler_mutex); rdma_destroy_id(&id_priv->id); return ret; } out: mutex_unlock(&id_priv->handler_mutex); return ret; } static struct rdma_id_private *cma_new_conn_id(struct rdma_cm_id *listen_id, struct ib_cm_event *ib_event) { struct rdma_id_private *id_priv; struct rdma_cm_id *id; struct rdma_route *rt; int ret; id = rdma_create_id(listen_id->event_handler, listen_id->context, listen_id->ps, ib_event->param.req_rcvd.qp_type); if (IS_ERR(id)) return NULL; id_priv = container_of(id, struct rdma_id_private, id); if (cma_save_net_info(id, listen_id, ib_event)) goto err; rt = &id->route; rt->num_paths = ib_event->param.req_rcvd.alternate_path ? 2 : 1; rt->path_rec = kmalloc(sizeof *rt->path_rec * rt->num_paths, GFP_KERNEL); if (!rt->path_rec) goto err; rt->path_rec[0] = *ib_event->param.req_rcvd.primary_path; if (rt->num_paths == 2) rt->path_rec[1] = *ib_event->param.req_rcvd.alternate_path; if (cma_any_addr(cma_src_addr(id_priv))) { rt->addr.dev_addr.dev_type = ARPHRD_INFINIBAND; rdma_addr_set_sgid(&rt->addr.dev_addr, &rt->path_rec[0].sgid); ib_addr_set_pkey(&rt->addr.dev_addr, be16_to_cpu(rt->path_rec[0].pkey)); } else { ret = cma_translate_addr(cma_src_addr(id_priv), &rt->addr.dev_addr); if (ret) goto err; } rdma_addr_set_dgid(&rt->addr.dev_addr, &rt->path_rec[0].dgid); id_priv->state = RDMA_CM_CONNECT; return id_priv; err: rdma_destroy_id(id); return NULL; } static struct rdma_id_private *cma_new_udp_id(struct rdma_cm_id *listen_id, struct ib_cm_event *ib_event) { struct rdma_id_private *id_priv; struct rdma_cm_id *id; int ret; id = rdma_create_id(listen_id->event_handler, listen_id->context, listen_id->ps, IB_QPT_UD); if (IS_ERR(id)) return NULL; id_priv = container_of(id, struct rdma_id_private, id); if (cma_save_net_info(id, listen_id, ib_event)) goto err; if (!cma_any_addr((struct sockaddr *) &id->route.addr.src_addr)) { ret = cma_translate_addr(cma_src_addr(id_priv), &id->route.addr.dev_addr); if (ret) goto err; } id_priv->state = RDMA_CM_CONNECT; return id_priv; err: rdma_destroy_id(id); return NULL; } static void cma_set_req_event_data(struct rdma_cm_event *event, struct ib_cm_req_event_param *req_data, void *private_data, int offset) { event->param.conn.private_data = private_data + offset; event->param.conn.private_data_len = IB_CM_REQ_PRIVATE_DATA_SIZE - offset; event->param.conn.responder_resources = req_data->responder_resources; event->param.conn.initiator_depth = req_data->initiator_depth; event->param.conn.flow_control = req_data->flow_control; event->param.conn.retry_count = req_data->retry_count; event->param.conn.rnr_retry_count = req_data->rnr_retry_count; event->param.conn.srq = req_data->srq; event->param.conn.qp_num = req_data->remote_qpn; } static int cma_check_req_qp_type(struct rdma_cm_id *id, struct ib_cm_event *ib_event) { return (((ib_event->event == IB_CM_REQ_RECEIVED) && (ib_event->param.req_rcvd.qp_type == id->qp_type)) || ((ib_event->event == IB_CM_SIDR_REQ_RECEIVED) && (id->qp_type == IB_QPT_UD)) || (!id->qp_type)); } static int cma_req_handler(struct ib_cm_id *cm_id, struct ib_cm_event *ib_event) { struct rdma_id_private *listen_id, *conn_id; struct rdma_cm_event event; int offset, ret; listen_id = cm_id->context; if (!cma_check_req_qp_type(&listen_id->id, ib_event)) return -EINVAL; if (cma_disable_callback(listen_id, RDMA_CM_LISTEN)) return -ECONNABORTED; memset(&event, 0, sizeof event); offset = cma_user_data_offset(listen_id); event.event = RDMA_CM_EVENT_CONNECT_REQUEST; if (ib_event->event == IB_CM_SIDR_REQ_RECEIVED) { conn_id = cma_new_udp_id(&listen_id->id, ib_event); event.param.ud.private_data = ib_event->private_data + offset; event.param.ud.private_data_len = IB_CM_SIDR_REQ_PRIVATE_DATA_SIZE - offset; } else { conn_id = cma_new_conn_id(&listen_id->id, ib_event); cma_set_req_event_data(&event, &ib_event->param.req_rcvd, ib_event->private_data, offset); } if (!conn_id) { ret = -ENOMEM; goto err1; } mutex_lock_nested(&conn_id->handler_mutex, SINGLE_DEPTH_NESTING); ret = cma_acquire_dev(conn_id, listen_id); if (ret) goto err2; conn_id->cm_id.ib = cm_id; cm_id->context = conn_id; cm_id->cm_handler = cma_ib_handler; /* * Protect against the user destroying conn_id from another thread * until we're done accessing it. */ atomic_inc(&conn_id->refcount); ret = conn_id->id.event_handler(&conn_id->id, &event); if (ret) goto err3; /* * Acquire mutex to prevent user executing rdma_destroy_id() * while we're accessing the cm_id. */ mutex_lock(&lock); if (cma_comp(conn_id, RDMA_CM_CONNECT) && (conn_id->id.qp_type != IB_QPT_UD)) ib_send_cm_mra(cm_id, CMA_CM_MRA_SETTING, NULL, 0); mutex_unlock(&lock); mutex_unlock(&conn_id->handler_mutex); mutex_unlock(&listen_id->handler_mutex); cma_deref_id(conn_id); return 0; err3: cma_deref_id(conn_id); /* Destroy the CM ID by returning a non-zero value. */ conn_id->cm_id.ib = NULL; err2: cma_exch(conn_id, RDMA_CM_DESTROYING); mutex_unlock(&conn_id->handler_mutex); err1: mutex_unlock(&listen_id->handler_mutex); if (conn_id) rdma_destroy_id(&conn_id->id); return ret; } __be64 rdma_get_service_id(struct rdma_cm_id *id, struct sockaddr *addr) { if (addr->sa_family == AF_IB) return ((struct sockaddr_ib *) addr)->sib_sid; return cpu_to_be64(((u64)id->ps << 16) + be16_to_cpu(cma_port(addr))); } EXPORT_SYMBOL(rdma_get_service_id); static void cma_set_compare_data(enum rdma_port_space ps, struct sockaddr *addr, struct ib_cm_compare_data *compare) { struct cma_hdr *cma_data, *cma_mask; __be32 ip4_addr; struct in6_addr ip6_addr; memset(compare, 0, sizeof *compare); cma_data = (void *) compare->data; cma_mask = (void *) compare->mask; switch (addr->sa_family) { case AF_INET: ip4_addr = ((struct sockaddr_in *) addr)->sin_addr.s_addr; cma_set_ip_ver(cma_data, 4); cma_set_ip_ver(cma_mask, 0xF); if (!cma_any_addr(addr)) { cma_data->dst_addr.ip4.addr = ip4_addr; cma_mask->dst_addr.ip4.addr = htonl(~0); } break; case AF_INET6: ip6_addr = ((struct sockaddr_in6 *) addr)->sin6_addr; cma_set_ip_ver(cma_data, 6); cma_set_ip_ver(cma_mask, 0xF); if (!cma_any_addr(addr)) { cma_data->dst_addr.ip6 = ip6_addr; memset(&cma_mask->dst_addr.ip6, 0xFF, sizeof cma_mask->dst_addr.ip6); } break; default: break; } } static int cma_iw_handler(struct iw_cm_id *iw_id, struct iw_cm_event *iw_event) { struct rdma_id_private *id_priv = iw_id->context; struct rdma_cm_event event; int ret = 0; struct sockaddr *laddr = (struct sockaddr *)&iw_event->local_addr; struct sockaddr *raddr = (struct sockaddr *)&iw_event->remote_addr; if (cma_disable_callback(id_priv, RDMA_CM_CONNECT)) return 0; memset(&event, 0, sizeof event); switch (iw_event->event) { case IW_CM_EVENT_CLOSE: event.event = RDMA_CM_EVENT_DISCONNECTED; break; case IW_CM_EVENT_CONNECT_REPLY: memcpy(cma_src_addr(id_priv), laddr, rdma_addr_size(laddr)); memcpy(cma_dst_addr(id_priv), raddr, rdma_addr_size(raddr)); switch (iw_event->status) { case 0: event.event = RDMA_CM_EVENT_ESTABLISHED; event.param.conn.initiator_depth = iw_event->ird; event.param.conn.responder_resources = iw_event->ord; break; case -ECONNRESET: case -ECONNREFUSED: event.event = RDMA_CM_EVENT_REJECTED; break; case -ETIMEDOUT: event.event = RDMA_CM_EVENT_UNREACHABLE; break; default: event.event = RDMA_CM_EVENT_CONNECT_ERROR; break; } break; case IW_CM_EVENT_ESTABLISHED: event.event = RDMA_CM_EVENT_ESTABLISHED; event.param.conn.initiator_depth = iw_event->ird; event.param.conn.responder_resources = iw_event->ord; break; default: BUG_ON(1); } event.status = iw_event->status; event.param.conn.private_data = iw_event->private_data; event.param.conn.private_data_len = iw_event->private_data_len; ret = id_priv->id.event_handler(&id_priv->id, &event); if (ret) { /* Destroy the CM ID by returning a non-zero value. */ id_priv->cm_id.iw = NULL; cma_exch(id_priv, RDMA_CM_DESTROYING); mutex_unlock(&id_priv->handler_mutex); rdma_destroy_id(&id_priv->id); return ret; } mutex_unlock(&id_priv->handler_mutex); return ret; } static int iw_conn_req_handler(struct iw_cm_id *cm_id, struct iw_cm_event *iw_event) { struct rdma_cm_id *new_cm_id; struct rdma_id_private *listen_id, *conn_id; struct rdma_cm_event event; int ret; struct ib_device_attr attr; struct sockaddr *laddr = (struct sockaddr *)&iw_event->local_addr; struct sockaddr *raddr = (struct sockaddr *)&iw_event->remote_addr; listen_id = cm_id->context; if (cma_disable_callback(listen_id, RDMA_CM_LISTEN)) return -ECONNABORTED; /* Create a new RDMA id for the new IW CM ID */ new_cm_id = rdma_create_id(listen_id->id.event_handler, listen_id->id.context, RDMA_PS_TCP, IB_QPT_RC); if (IS_ERR(new_cm_id)) { ret = -ENOMEM; goto out; } conn_id = container_of(new_cm_id, struct rdma_id_private, id); mutex_lock_nested(&conn_id->handler_mutex, SINGLE_DEPTH_NESTING); conn_id->state = RDMA_CM_CONNECT; ret = rdma_translate_ip(laddr, &conn_id->id.route.addr.dev_addr, NULL); if (ret) { mutex_unlock(&conn_id->handler_mutex); rdma_destroy_id(new_cm_id); goto out; } ret = cma_acquire_dev(conn_id, listen_id); if (ret) { mutex_unlock(&conn_id->handler_mutex); rdma_destroy_id(new_cm_id); goto out; } conn_id->cm_id.iw = cm_id; cm_id->context = conn_id; cm_id->cm_handler = cma_iw_handler; memcpy(cma_src_addr(conn_id), laddr, rdma_addr_size(laddr)); memcpy(cma_dst_addr(conn_id), raddr, rdma_addr_size(raddr)); ret = ib_query_device(conn_id->id.device, &attr); if (ret) { mutex_unlock(&conn_id->handler_mutex); rdma_destroy_id(new_cm_id); goto out; } memset(&event, 0, sizeof event); event.event = RDMA_CM_EVENT_CONNECT_REQUEST; event.param.conn.private_data = iw_event->private_data; event.param.conn.private_data_len = iw_event->private_data_len; event.param.conn.initiator_depth = iw_event->ird; event.param.conn.responder_resources = iw_event->ord; /* * Protect against the user destroying conn_id from another thread * until we're done accessing it. */ atomic_inc(&conn_id->refcount); ret = conn_id->id.event_handler(&conn_id->id, &event); if (ret) { /* User wants to destroy the CM ID */ conn_id->cm_id.iw = NULL; cma_exch(conn_id, RDMA_CM_DESTROYING); mutex_unlock(&conn_id->handler_mutex); cma_deref_id(conn_id); rdma_destroy_id(&conn_id->id); goto out; } mutex_unlock(&conn_id->handler_mutex); cma_deref_id(conn_id); out: mutex_unlock(&listen_id->handler_mutex); return ret; } static int cma_ib_listen(struct rdma_id_private *id_priv) { struct ib_cm_compare_data compare_data; struct sockaddr *addr; struct ib_cm_id *id; __be64 svc_id; int ret; id = ib_create_cm_id(id_priv->id.device, cma_req_handler, id_priv); if (IS_ERR(id)) return PTR_ERR(id); id_priv->cm_id.ib = id; addr = cma_src_addr(id_priv); svc_id = rdma_get_service_id(&id_priv->id, addr); if (cma_any_addr(addr) && !id_priv->afonly) ret = ib_cm_listen(id_priv->cm_id.ib, svc_id, 0, NULL); else { cma_set_compare_data(id_priv->id.ps, addr, &compare_data); ret = ib_cm_listen(id_priv->cm_id.ib, svc_id, 0, &compare_data); } if (ret) { ib_destroy_cm_id(id_priv->cm_id.ib); id_priv->cm_id.ib = NULL; } return ret; } static int cma_iw_listen(struct rdma_id_private *id_priv, int backlog) { int ret; struct iw_cm_id *id; id = iw_create_cm_id(id_priv->id.device, iw_conn_req_handler, id_priv); if (IS_ERR(id)) return PTR_ERR(id); id_priv->cm_id.iw = id; memcpy(&id_priv->cm_id.iw->local_addr, cma_src_addr(id_priv), rdma_addr_size(cma_src_addr(id_priv))); ret = iw_cm_listen(id_priv->cm_id.iw, backlog); if (ret) { iw_destroy_cm_id(id_priv->cm_id.iw); id_priv->cm_id.iw = NULL; } return ret; } static int cma_listen_handler(struct rdma_cm_id *id, struct rdma_cm_event *event) { struct rdma_id_private *id_priv = id->context; id->context = id_priv->id.context; id->event_handler = id_priv->id.event_handler; return id_priv->id.event_handler(id, event); } static void cma_listen_on_dev(struct rdma_id_private *id_priv, struct cma_device *cma_dev) { struct rdma_id_private *dev_id_priv; struct rdma_cm_id *id; int ret; if (cma_family(id_priv) == AF_IB && rdma_node_get_transport(cma_dev->device->node_type) != RDMA_TRANSPORT_IB) return; id = rdma_create_id(cma_listen_handler, id_priv, id_priv->id.ps, id_priv->id.qp_type); if (IS_ERR(id)) return; dev_id_priv = container_of(id, struct rdma_id_private, id); dev_id_priv->state = RDMA_CM_ADDR_BOUND; memcpy(cma_src_addr(dev_id_priv), cma_src_addr(id_priv), rdma_addr_size(cma_src_addr(id_priv))); cma_attach_to_dev(dev_id_priv, cma_dev); list_add_tail(&dev_id_priv->listen_list, &id_priv->listen_list); atomic_inc(&id_priv->refcount); dev_id_priv->internal_id = 1; dev_id_priv->afonly = id_priv->afonly; ret = rdma_listen(id, id_priv->backlog); if (ret) printk(KERN_WARNING "RDMA CMA: cma_listen_on_dev, error %d, " "listening on device %s\n", ret, cma_dev->device->name); } static void cma_listen_on_all(struct rdma_id_private *id_priv) { struct cma_device *cma_dev; mutex_lock(&lock); list_add_tail(&id_priv->list, &listen_any_list); list_for_each_entry(cma_dev, &dev_list, list) cma_listen_on_dev(id_priv, cma_dev); mutex_unlock(&lock); } void rdma_set_service_type(struct rdma_cm_id *id, int tos) { struct rdma_id_private *id_priv; id_priv = container_of(id, struct rdma_id_private, id); id_priv->tos = (u8) tos; } EXPORT_SYMBOL(rdma_set_service_type); static void cma_query_handler(int status, struct ib_sa_path_rec *path_rec, void *context) { struct cma_work *work = context; struct rdma_route *route; route = &work->id->id.route; if (!status) { route->num_paths = 1; *route->path_rec = *path_rec; } else { work->old_state = RDMA_CM_ROUTE_QUERY; work->new_state = RDMA_CM_ADDR_RESOLVED; work->event.event = RDMA_CM_EVENT_ROUTE_ERROR; work->event.status = status; } queue_work(cma_wq, &work->work); } static int cma_query_ib_route(struct rdma_id_private *id_priv, int timeout_ms, struct cma_work *work) { struct rdma_dev_addr *dev_addr = &id_priv->id.route.addr.dev_addr; struct ib_sa_path_rec path_rec; ib_sa_comp_mask comp_mask; struct sockaddr_in6 *sin6; struct sockaddr_ib *sib; memset(&path_rec, 0, sizeof path_rec); rdma_addr_get_sgid(dev_addr, &path_rec.sgid); rdma_addr_get_dgid(dev_addr, &path_rec.dgid); path_rec.pkey = cpu_to_be16(ib_addr_get_pkey(dev_addr)); path_rec.numb_path = 1; path_rec.reversible = 1; path_rec.service_id = rdma_get_service_id(&id_priv->id, cma_dst_addr(id_priv)); comp_mask = IB_SA_PATH_REC_DGID | IB_SA_PATH_REC_SGID | IB_SA_PATH_REC_PKEY | IB_SA_PATH_REC_NUMB_PATH | IB_SA_PATH_REC_REVERSIBLE | IB_SA_PATH_REC_SERVICE_ID; switch (cma_family(id_priv)) { case AF_INET: path_rec.qos_class = cpu_to_be16((u16) id_priv->tos); comp_mask |= IB_SA_PATH_REC_QOS_CLASS; break; case AF_INET6: sin6 = (struct sockaddr_in6 *) cma_src_addr(id_priv); path_rec.traffic_class = (u8) (be32_to_cpu(sin6->sin6_flowinfo) >> 20); comp_mask |= IB_SA_PATH_REC_TRAFFIC_CLASS; break; case AF_IB: sib = (struct sockaddr_ib *) cma_src_addr(id_priv); path_rec.traffic_class = (u8) (be32_to_cpu(sib->sib_flowinfo) >> 20); comp_mask |= IB_SA_PATH_REC_TRAFFIC_CLASS; break; } id_priv->query_id = ib_sa_path_rec_get(&sa_client, id_priv->id.device, id_priv->id.port_num, &path_rec, comp_mask, timeout_ms, GFP_KERNEL, cma_query_handler, work, &id_priv->query); return (id_priv->query_id < 0) ? id_priv->query_id : 0; } static void cma_work_handler(struct work_struct *_work) { struct cma_work *work = container_of(_work, struct cma_work, work); struct rdma_id_private *id_priv = work->id; int destroy = 0; mutex_lock(&id_priv->handler_mutex); if (!cma_comp_exch(id_priv, work->old_state, work->new_state)) goto out; if (id_priv->id.event_handler(&id_priv->id, &work->event)) { cma_exch(id_priv, RDMA_CM_DESTROYING); destroy = 1; } out: mutex_unlock(&id_priv->handler_mutex); cma_deref_id(id_priv); if (destroy) rdma_destroy_id(&id_priv->id); kfree(work); } static void cma_ndev_work_handler(struct work_struct *_work) { struct cma_ndev_work *work = container_of(_work, struct cma_ndev_work, work); struct rdma_id_private *id_priv = work->id; int destroy = 0; mutex_lock(&id_priv->handler_mutex); if (id_priv->state == RDMA_CM_DESTROYING || id_priv->state == RDMA_CM_DEVICE_REMOVAL) goto out; if (id_priv->id.event_handler(&id_priv->id, &work->event)) { cma_exch(id_priv, RDMA_CM_DESTROYING); destroy = 1; } out: mutex_unlock(&id_priv->handler_mutex); cma_deref_id(id_priv); if (destroy) rdma_destroy_id(&id_priv->id); kfree(work); } static int cma_resolve_ib_route(struct rdma_id_private *id_priv, int timeout_ms) { struct rdma_route *route = &id_priv->id.route; struct cma_work *work; int ret; work = kzalloc(sizeof *work, GFP_KERNEL); if (!work) return -ENOMEM; work->id = id_priv; INIT_WORK(&work->work, cma_work_handler); work->old_state = RDMA_CM_ROUTE_QUERY; work->new_state = RDMA_CM_ROUTE_RESOLVED; work->event.event = RDMA_CM_EVENT_ROUTE_RESOLVED; route->path_rec = kmalloc(sizeof *route->path_rec, GFP_KERNEL); if (!route->path_rec) { ret = -ENOMEM; goto err1; } ret = cma_query_ib_route(id_priv, timeout_ms, work); if (ret) goto err2; return 0; err2: kfree(route->path_rec); route->path_rec = NULL; err1: kfree(work); return ret; } int rdma_set_ib_paths(struct rdma_cm_id *id, struct ib_sa_path_rec *path_rec, int num_paths) { struct rdma_id_private *id_priv; int ret; id_priv = container_of(id, struct rdma_id_private, id); if (!cma_comp_exch(id_priv, RDMA_CM_ADDR_RESOLVED, RDMA_CM_ROUTE_RESOLVED)) return -EINVAL; id->route.path_rec = kmemdup(path_rec, sizeof *path_rec * num_paths, GFP_KERNEL); if (!id->route.path_rec) { ret = -ENOMEM; goto err; } id->route.num_paths = num_paths; return 0; err: cma_comp_exch(id_priv, RDMA_CM_ROUTE_RESOLVED, RDMA_CM_ADDR_RESOLVED); return ret; } EXPORT_SYMBOL(rdma_set_ib_paths); static int cma_resolve_iw_route(struct rdma_id_private *id_priv, int timeout_ms) { struct cma_work *work; work = kzalloc(sizeof *work, GFP_KERNEL); if (!work) return -ENOMEM; work->id = id_priv; INIT_WORK(&work->work, cma_work_handler); work->old_state = RDMA_CM_ROUTE_QUERY; work->new_state = RDMA_CM_ROUTE_RESOLVED; work->event.event = RDMA_CM_EVENT_ROUTE_RESOLVED; queue_work(cma_wq, &work->work); return 0; } static int iboe_tos_to_sl(struct net_device *ndev, int tos) { int prio; struct net_device *dev; prio = rt_tos2priority(tos); dev = ndev->priv_flags & IFF_802_1Q_VLAN ? vlan_dev_real_dev(ndev) : ndev; if (dev->num_tc) return netdev_get_prio_tc_map(dev, prio); #if IS_ENABLED(CONFIG_VLAN_8021Q) if (ndev->priv_flags & IFF_802_1Q_VLAN) return (vlan_dev_get_egress_qos_mask(ndev, prio) & VLAN_PRIO_MASK) >> VLAN_PRIO_SHIFT; #endif return 0; } static int cma_resolve_iboe_route(struct rdma_id_private *id_priv) { struct rdma_route *route = &id_priv->id.route; struct rdma_addr *addr = &route->addr; struct cma_work *work; int ret; struct net_device *ndev = NULL; work = kzalloc(sizeof *work, GFP_KERNEL); if (!work) return -ENOMEM; work->id = id_priv; INIT_WORK(&work->work, cma_work_handler); route->path_rec = kzalloc(sizeof *route->path_rec, GFP_KERNEL); if (!route->path_rec) { ret = -ENOMEM; goto err1; } route->num_paths = 1; if (addr->dev_addr.bound_dev_if) ndev = dev_get_by_index(&init_net, addr->dev_addr.bound_dev_if); if (!ndev) { ret = -ENODEV; goto err2; } route->path_rec->vlan_id = rdma_vlan_dev_vlan_id(ndev); memcpy(route->path_rec->dmac, addr->dev_addr.dst_dev_addr, ETH_ALEN); memcpy(route->path_rec->smac, ndev->dev_addr, ndev->addr_len); rdma_ip2gid((struct sockaddr *)&id_priv->id.route.addr.src_addr, &route->path_rec->sgid); rdma_ip2gid((struct sockaddr *)&id_priv->id.route.addr.dst_addr, &route->path_rec->dgid); route->path_rec->hop_limit = 1; route->path_rec->reversible = 1; route->path_rec->pkey = cpu_to_be16(0xffff); route->path_rec->mtu_selector = IB_SA_EQ; route->path_rec->sl = iboe_tos_to_sl(ndev, id_priv->tos); route->path_rec->mtu = iboe_get_mtu(ndev->mtu); route->path_rec->rate_selector = IB_SA_EQ; route->path_rec->rate = iboe_get_rate(ndev); dev_put(ndev); route->path_rec->packet_life_time_selector = IB_SA_EQ; route->path_rec->packet_life_time = CMA_IBOE_PACKET_LIFETIME; if (!route->path_rec->mtu) { ret = -EINVAL; goto err2; } work->old_state = RDMA_CM_ROUTE_QUERY; work->new_state = RDMA_CM_ROUTE_RESOLVED; work->event.event = RDMA_CM_EVENT_ROUTE_RESOLVED; work->event.status = 0; queue_work(cma_wq, &work->work); return 0; err2: kfree(route->path_rec); route->path_rec = NULL; err1: kfree(work); return ret; } int rdma_resolve_route(struct rdma_cm_id *id, int timeout_ms) { struct rdma_id_private *id_priv; int ret; id_priv = container_of(id, struct rdma_id_private, id); if (!cma_comp_exch(id_priv, RDMA_CM_ADDR_RESOLVED, RDMA_CM_ROUTE_QUERY)) return -EINVAL; atomic_inc(&id_priv->refcount); switch (rdma_node_get_transport(id->device->node_type)) { case RDMA_TRANSPORT_IB: switch (rdma_port_get_link_layer(id->device, id->port_num)) { case IB_LINK_LAYER_INFINIBAND: ret = cma_resolve_ib_route(id_priv, timeout_ms); break; case IB_LINK_LAYER_ETHERNET: ret = cma_resolve_iboe_route(id_priv); break; default: ret = -ENOSYS; } break; case RDMA_TRANSPORT_IWARP: ret = cma_resolve_iw_route(id_priv, timeout_ms); break; default: ret = -ENOSYS; break; } if (ret) goto err; return 0; err: cma_comp_exch(id_priv, RDMA_CM_ROUTE_QUERY, RDMA_CM_ADDR_RESOLVED); cma_deref_id(id_priv); return ret; } EXPORT_SYMBOL(rdma_resolve_route); static void cma_set_loopback(struct sockaddr *addr) { switch (addr->sa_family) { case AF_INET: ((struct sockaddr_in *) addr)->sin_addr.s_addr = htonl(INADDR_LOOPBACK); break; case AF_INET6: ipv6_addr_set(&((struct sockaddr_in6 *) addr)->sin6_addr, 0, 0, 0, htonl(1)); break; default: ib_addr_set(&((struct sockaddr_ib *) addr)->sib_addr, 0, 0, 0, htonl(1)); break; } } static int cma_bind_loopback(struct rdma_id_private *id_priv) { struct cma_device *cma_dev, *cur_dev; struct ib_port_attr port_attr; union ib_gid gid; u16 pkey; int ret; u8 p; cma_dev = NULL; mutex_lock(&lock); list_for_each_entry(cur_dev, &dev_list, list) { if (cma_family(id_priv) == AF_IB && rdma_node_get_transport(cur_dev->device->node_type) != RDMA_TRANSPORT_IB) continue; if (!cma_dev) cma_dev = cur_dev; for (p = 1; p <= cur_dev->device->phys_port_cnt; ++p) { if (!ib_query_port(cur_dev->device, p, &port_attr) && port_attr.state == IB_PORT_ACTIVE) { cma_dev = cur_dev; goto port_found; } } } if (!cma_dev) { ret = -ENODEV; goto out; } p = 1; port_found: ret = ib_get_cached_gid(cma_dev->device, p, 0, &gid); if (ret) goto out; ret = ib_get_cached_pkey(cma_dev->device, p, 0, &pkey); if (ret) goto out; id_priv->id.route.addr.dev_addr.dev_type = (rdma_port_get_link_layer(cma_dev->device, p) == IB_LINK_LAYER_INFINIBAND) ? ARPHRD_INFINIBAND : ARPHRD_ETHER; rdma_addr_set_sgid(&id_priv->id.route.addr.dev_addr, &gid); ib_addr_set_pkey(&id_priv->id.route.addr.dev_addr, pkey); id_priv->id.port_num = p; cma_attach_to_dev(id_priv, cma_dev); cma_set_loopback(cma_src_addr(id_priv)); out: mutex_unlock(&lock); return ret; } static void addr_handler(int status, struct sockaddr *src_addr, struct rdma_dev_addr *dev_addr, void *context) { struct rdma_id_private *id_priv = context; struct rdma_cm_event event; memset(&event, 0, sizeof event); mutex_lock(&id_priv->handler_mutex); if (!cma_comp_exch(id_priv, RDMA_CM_ADDR_QUERY, RDMA_CM_ADDR_RESOLVED)) goto out; memcpy(cma_src_addr(id_priv), src_addr, rdma_addr_size(src_addr)); if (!status && !id_priv->cma_dev) status = cma_acquire_dev(id_priv, NULL); if (status) { if (!cma_comp_exch(id_priv, RDMA_CM_ADDR_RESOLVED, RDMA_CM_ADDR_BOUND)) goto out; event.event = RDMA_CM_EVENT_ADDR_ERROR; event.status = status; } else event.event = RDMA_CM_EVENT_ADDR_RESOLVED; if (id_priv->id.event_handler(&id_priv->id, &event)) { cma_exch(id_priv, RDMA_CM_DESTROYING); mutex_unlock(&id_priv->handler_mutex); cma_deref_id(id_priv); rdma_destroy_id(&id_priv->id); return; } out: mutex_unlock(&id_priv->handler_mutex); cma_deref_id(id_priv); } static int cma_resolve_loopback(struct rdma_id_private *id_priv) { struct cma_work *work; union ib_gid gid; int ret; work = kzalloc(sizeof *work, GFP_KERNEL); if (!work) return -ENOMEM; if (!id_priv->cma_dev) { ret = cma_bind_loopback(id_priv); if (ret) goto err; } rdma_addr_get_sgid(&id_priv->id.route.addr.dev_addr, &gid); rdma_addr_set_dgid(&id_priv->id.route.addr.dev_addr, &gid); work->id = id_priv; INIT_WORK(&work->work, cma_work_handler); work->old_state = RDMA_CM_ADDR_QUERY; work->new_state = RDMA_CM_ADDR_RESOLVED; work->event.event = RDMA_CM_EVENT_ADDR_RESOLVED; queue_work(cma_wq, &work->work); return 0; err: kfree(work); return ret; } static int cma_resolve_ib_addr(struct rdma_id_private *id_priv) { struct cma_work *work; int ret; work = kzalloc(sizeof *work, GFP_KERNEL); if (!work) return -ENOMEM; if (!id_priv->cma_dev) { ret = cma_resolve_ib_dev(id_priv); if (ret) goto err; } rdma_addr_set_dgid(&id_priv->id.route.addr.dev_addr, (union ib_gid *) &(((struct sockaddr_ib *) &id_priv->id.route.addr.dst_addr)->sib_addr)); work->id = id_priv; INIT_WORK(&work->work, cma_work_handler); work->old_state = RDMA_CM_ADDR_QUERY; work->new_state = RDMA_CM_ADDR_RESOLVED; work->event.event = RDMA_CM_EVENT_ADDR_RESOLVED; queue_work(cma_wq, &work->work); return 0; err: kfree(work); return ret; } static int cma_bind_addr(struct rdma_cm_id *id, struct sockaddr *src_addr, struct sockaddr *dst_addr) { if (!src_addr || !src_addr->sa_family) { src_addr = (struct sockaddr *) &id->route.addr.src_addr; src_addr->sa_family = dst_addr->sa_family; if (dst_addr->sa_family == AF_INET6) { ((struct sockaddr_in6 *) src_addr)->sin6_scope_id = ((struct sockaddr_in6 *) dst_addr)->sin6_scope_id; } else if (dst_addr->sa_family == AF_IB) { ((struct sockaddr_ib *) src_addr)->sib_pkey = ((struct sockaddr_ib *) dst_addr)->sib_pkey; } } return rdma_bind_addr(id, src_addr); } int rdma_resolve_addr(struct rdma_cm_id *id, struct sockaddr *src_addr, struct sockaddr *dst_addr, int timeout_ms) { struct rdma_id_private *id_priv; int ret; id_priv = container_of(id, struct rdma_id_private, id); if (id_priv->state == RDMA_CM_IDLE) { ret = cma_bind_addr(id, src_addr, dst_addr); if (ret) return ret; } if (cma_family(id_priv) != dst_addr->sa_family) return -EINVAL; if (!cma_comp_exch(id_priv, RDMA_CM_ADDR_BOUND, RDMA_CM_ADDR_QUERY)) return -EINVAL; atomic_inc(&id_priv->refcount); memcpy(cma_dst_addr(id_priv), dst_addr, rdma_addr_size(dst_addr)); if (cma_any_addr(dst_addr)) { ret = cma_resolve_loopback(id_priv); } else { if (dst_addr->sa_family == AF_IB) { ret = cma_resolve_ib_addr(id_priv); } else { ret = rdma_resolve_ip(&addr_client, cma_src_addr(id_priv), dst_addr, &id->route.addr.dev_addr, timeout_ms, addr_handler, id_priv); } } if (ret) goto err; return 0; err: cma_comp_exch(id_priv, RDMA_CM_ADDR_QUERY, RDMA_CM_ADDR_BOUND); cma_deref_id(id_priv); return ret; } EXPORT_SYMBOL(rdma_resolve_addr); int rdma_set_reuseaddr(struct rdma_cm_id *id, int reuse) { struct rdma_id_private *id_priv; unsigned long flags; int ret; id_priv = container_of(id, struct rdma_id_private, id); spin_lock_irqsave(&id_priv->lock, flags); if (reuse || id_priv->state == RDMA_CM_IDLE) { id_priv->reuseaddr = reuse; ret = 0; } else { ret = -EINVAL; } spin_unlock_irqrestore(&id_priv->lock, flags); return ret; } EXPORT_SYMBOL(rdma_set_reuseaddr); int rdma_set_afonly(struct rdma_cm_id *id, int afonly) { struct rdma_id_private *id_priv; unsigned long flags; int ret; id_priv = container_of(id, struct rdma_id_private, id); spin_lock_irqsave(&id_priv->lock, flags); if (id_priv->state == RDMA_CM_IDLE || id_priv->state == RDMA_CM_ADDR_BOUND) { id_priv->options |= (1 << CMA_OPTION_AFONLY); id_priv->afonly = afonly; ret = 0; } else { ret = -EINVAL; } spin_unlock_irqrestore(&id_priv->lock, flags); return ret; } EXPORT_SYMBOL(rdma_set_afonly); static void cma_bind_port(struct rdma_bind_list *bind_list, struct rdma_id_private *id_priv) { struct sockaddr *addr; struct sockaddr_ib *sib; u64 sid, mask; __be16 port; addr = cma_src_addr(id_priv); port = htons(bind_list->port); switch (addr->sa_family) { case AF_INET: ((struct sockaddr_in *) addr)->sin_port = port; break; case AF_INET6: ((struct sockaddr_in6 *) addr)->sin6_port = port; break; case AF_IB: sib = (struct sockaddr_ib *) addr; sid = be64_to_cpu(sib->sib_sid); mask = be64_to_cpu(sib->sib_sid_mask); sib->sib_sid = cpu_to_be64((sid & mask) | (u64) ntohs(port)); sib->sib_sid_mask = cpu_to_be64(~0ULL); break; } id_priv->bind_list = bind_list; hlist_add_head(&id_priv->node, &bind_list->owners); } static int cma_alloc_port(struct idr *ps, struct rdma_id_private *id_priv, unsigned short snum) { struct rdma_bind_list *bind_list; int ret; bind_list = kzalloc(sizeof *bind_list, GFP_KERNEL); if (!bind_list) return -ENOMEM; ret = idr_alloc(ps, bind_list, snum, snum + 1, GFP_KERNEL); if (ret < 0) goto err; bind_list->ps = ps; bind_list->port = (unsigned short)ret; cma_bind_port(bind_list, id_priv); return 0; err: kfree(bind_list); return ret == -ENOSPC ? -EADDRNOTAVAIL : ret; } static int cma_alloc_any_port(struct idr *ps, struct rdma_id_private *id_priv) { static unsigned int last_used_port; int low, high, remaining; unsigned int rover; inet_get_local_port_range(&init_net, &low, &high); remaining = (high - low) + 1; rover = prandom_u32() % remaining + low; retry: if (last_used_port != rover && !idr_find(ps, (unsigned short) rover)) { int ret = cma_alloc_port(ps, id_priv, rover); /* * Remember previously used port number in order to avoid * re-using same port immediately after it is closed. */ if (!ret) last_used_port = rover; if (ret != -EADDRNOTAVAIL) return ret; } if (--remaining) { rover++; if ((rover < low) || (rover > high)) rover = low; goto retry; } return -EADDRNOTAVAIL; } /* * Check that the requested port is available. This is called when trying to * bind to a specific port, or when trying to listen on a bound port. In * the latter case, the provided id_priv may already be on the bind_list, but * we still need to check that it's okay to start listening. */ static int cma_check_port(struct rdma_bind_list *bind_list, struct rdma_id_private *id_priv, uint8_t reuseaddr) { struct rdma_id_private *cur_id; struct sockaddr *addr, *cur_addr; addr = cma_src_addr(id_priv); hlist_for_each_entry(cur_id, &bind_list->owners, node) { if (id_priv == cur_id) continue; if ((cur_id->state != RDMA_CM_LISTEN) && reuseaddr && cur_id->reuseaddr) continue; cur_addr = cma_src_addr(cur_id); if (id_priv->afonly && cur_id->afonly && (addr->sa_family != cur_addr->sa_family)) continue; if (cma_any_addr(addr) || cma_any_addr(cur_addr)) return -EADDRNOTAVAIL; if (!cma_addr_cmp(addr, cur_addr)) return -EADDRINUSE; } return 0; } static int cma_use_port(struct idr *ps, struct rdma_id_private *id_priv) { struct rdma_bind_list *bind_list; unsigned short snum; int ret; snum = ntohs(cma_port(cma_src_addr(id_priv))); if (snum < PROT_SOCK && !capable(CAP_NET_BIND_SERVICE)) return -EACCES; bind_list = idr_find(ps, snum); if (!bind_list) { ret = cma_alloc_port(ps, id_priv, snum); } else { ret = cma_check_port(bind_list, id_priv, id_priv->reuseaddr); if (!ret) cma_bind_port(bind_list, id_priv); } return ret; } static int cma_bind_listen(struct rdma_id_private *id_priv) { struct rdma_bind_list *bind_list = id_priv->bind_list; int ret = 0; mutex_lock(&lock); if (bind_list->owners.first->next) ret = cma_check_port(bind_list, id_priv, 0); mutex_unlock(&lock); return ret; } static struct idr *cma_select_inet_ps(struct rdma_id_private *id_priv) { switch (id_priv->id.ps) { case RDMA_PS_TCP: return &tcp_ps; case RDMA_PS_UDP: return &udp_ps; case RDMA_PS_IPOIB: return &ipoib_ps; case RDMA_PS_IB: return &ib_ps; default: return NULL; } } static struct idr *cma_select_ib_ps(struct rdma_id_private *id_priv) { struct idr *ps = NULL; struct sockaddr_ib *sib; u64 sid_ps, mask, sid; sib = (struct sockaddr_ib *) cma_src_addr(id_priv); mask = be64_to_cpu(sib->sib_sid_mask) & RDMA_IB_IP_PS_MASK; sid = be64_to_cpu(sib->sib_sid) & mask; if ((id_priv->id.ps == RDMA_PS_IB) && (sid == (RDMA_IB_IP_PS_IB & mask))) { sid_ps = RDMA_IB_IP_PS_IB; ps = &ib_ps; } else if (((id_priv->id.ps == RDMA_PS_IB) || (id_priv->id.ps == RDMA_PS_TCP)) && (sid == (RDMA_IB_IP_PS_TCP & mask))) { sid_ps = RDMA_IB_IP_PS_TCP; ps = &tcp_ps; } else if (((id_priv->id.ps == RDMA_PS_IB) || (id_priv->id.ps == RDMA_PS_UDP)) && (sid == (RDMA_IB_IP_PS_UDP & mask))) { sid_ps = RDMA_IB_IP_PS_UDP; ps = &udp_ps; } if (ps) { sib->sib_sid = cpu_to_be64(sid_ps | ntohs(cma_port((struct sockaddr *) sib))); sib->sib_sid_mask = cpu_to_be64(RDMA_IB_IP_PS_MASK | be64_to_cpu(sib->sib_sid_mask)); } return ps; } static int cma_get_port(struct rdma_id_private *id_priv) { struct idr *ps; int ret; if (cma_family(id_priv) != AF_IB) ps = cma_select_inet_ps(id_priv); else ps = cma_select_ib_ps(id_priv); if (!ps) return -EPROTONOSUPPORT; mutex_lock(&lock); if (cma_any_port(cma_src_addr(id_priv))) ret = cma_alloc_any_port(ps, id_priv); else ret = cma_use_port(ps, id_priv); mutex_unlock(&lock); return ret; } static int cma_check_linklocal(struct rdma_dev_addr *dev_addr, struct sockaddr *addr) { #if IS_ENABLED(CONFIG_IPV6) struct sockaddr_in6 *sin6; if (addr->sa_family != AF_INET6) return 0; sin6 = (struct sockaddr_in6 *) addr; if (!(ipv6_addr_type(&sin6->sin6_addr) & IPV6_ADDR_LINKLOCAL)) return 0; if (!sin6->sin6_scope_id) return -EINVAL; dev_addr->bound_dev_if = sin6->sin6_scope_id; #endif return 0; } int rdma_listen(struct rdma_cm_id *id, int backlog) { struct rdma_id_private *id_priv; int ret; id_priv = container_of(id, struct rdma_id_private, id); if (id_priv->state == RDMA_CM_IDLE) { id->route.addr.src_addr.ss_family = AF_INET; ret = rdma_bind_addr(id, cma_src_addr(id_priv)); if (ret) return ret; } if (!cma_comp_exch(id_priv, RDMA_CM_ADDR_BOUND, RDMA_CM_LISTEN)) return -EINVAL; if (id_priv->reuseaddr) { ret = cma_bind_listen(id_priv); if (ret) goto err; } id_priv->backlog = backlog; if (id->device) { switch (rdma_node_get_transport(id->device->node_type)) { case RDMA_TRANSPORT_IB: ret = cma_ib_listen(id_priv); if (ret) goto err; break; case RDMA_TRANSPORT_IWARP: ret = cma_iw_listen(id_priv, backlog); if (ret) goto err; break; default: ret = -ENOSYS; goto err; } } else cma_listen_on_all(id_priv); return 0; err: id_priv->backlog = 0; cma_comp_exch(id_priv, RDMA_CM_LISTEN, RDMA_CM_ADDR_BOUND); return ret; } EXPORT_SYMBOL(rdma_listen); int rdma_bind_addr(struct rdma_cm_id *id, struct sockaddr *addr) { struct rdma_id_private *id_priv; int ret; if (addr->sa_family != AF_INET && addr->sa_family != AF_INET6 && addr->sa_family != AF_IB) return -EAFNOSUPPORT; id_priv = container_of(id, struct rdma_id_private, id); if (!cma_comp_exch(id_priv, RDMA_CM_IDLE, RDMA_CM_ADDR_BOUND)) return -EINVAL; ret = cma_check_linklocal(&id->route.addr.dev_addr, addr); if (ret) goto err1; memcpy(cma_src_addr(id_priv), addr, rdma_addr_size(addr)); if (!cma_any_addr(addr)) { ret = cma_translate_addr(addr, &id->route.addr.dev_addr); if (ret) goto err1; ret = cma_acquire_dev(id_priv, NULL); if (ret) goto err1; } if (!(id_priv->options & (1 << CMA_OPTION_AFONLY))) { if (addr->sa_family == AF_INET) id_priv->afonly = 1; #if IS_ENABLED(CONFIG_IPV6) else if (addr->sa_family == AF_INET6) id_priv->afonly = init_net.ipv6.sysctl.bindv6only; #endif } ret = cma_get_port(id_priv); if (ret) goto err2; return 0; err2: if (id_priv->cma_dev) cma_release_dev(id_priv); err1: cma_comp_exch(id_priv, RDMA_CM_ADDR_BOUND, RDMA_CM_IDLE); return ret; } EXPORT_SYMBOL(rdma_bind_addr); static int cma_format_hdr(void *hdr, struct rdma_id_private *id_priv) { struct cma_hdr *cma_hdr; cma_hdr = hdr; cma_hdr->cma_version = CMA_VERSION; if (cma_family(id_priv) == AF_INET) { struct sockaddr_in *src4, *dst4; src4 = (struct sockaddr_in *) cma_src_addr(id_priv); dst4 = (struct sockaddr_in *) cma_dst_addr(id_priv); cma_set_ip_ver(cma_hdr, 4); cma_hdr->src_addr.ip4.addr = src4->sin_addr.s_addr; cma_hdr->dst_addr.ip4.addr = dst4->sin_addr.s_addr; cma_hdr->port = src4->sin_port; } else if (cma_family(id_priv) == AF_INET6) { struct sockaddr_in6 *src6, *dst6; src6 = (struct sockaddr_in6 *) cma_src_addr(id_priv); dst6 = (struct sockaddr_in6 *) cma_dst_addr(id_priv); cma_set_ip_ver(cma_hdr, 6); cma_hdr->src_addr.ip6 = src6->sin6_addr; cma_hdr->dst_addr.ip6 = dst6->sin6_addr; cma_hdr->port = src6->sin6_port; } return 0; } static int cma_sidr_rep_handler(struct ib_cm_id *cm_id, struct ib_cm_event *ib_event) { struct rdma_id_private *id_priv = cm_id->context; struct rdma_cm_event event; struct ib_cm_sidr_rep_event_param *rep = &ib_event->param.sidr_rep_rcvd; int ret = 0; if (cma_disable_callback(id_priv, RDMA_CM_CONNECT)) return 0; memset(&event, 0, sizeof event); switch (ib_event->event) { case IB_CM_SIDR_REQ_ERROR: event.event = RDMA_CM_EVENT_UNREACHABLE; event.status = -ETIMEDOUT; break; case IB_CM_SIDR_REP_RECEIVED: event.param.ud.private_data = ib_event->private_data; event.param.ud.private_data_len = IB_CM_SIDR_REP_PRIVATE_DATA_SIZE; if (rep->status != IB_SIDR_SUCCESS) { event.event = RDMA_CM_EVENT_UNREACHABLE; event.status = ib_event->param.sidr_rep_rcvd.status; break; } ret = cma_set_qkey(id_priv, rep->qkey); if (ret) { event.event = RDMA_CM_EVENT_ADDR_ERROR; event.status = ret; break; } ib_init_ah_from_path(id_priv->id.device, id_priv->id.port_num, id_priv->id.route.path_rec, &event.param.ud.ah_attr); event.param.ud.qp_num = rep->qpn; event.param.ud.qkey = rep->qkey; event.event = RDMA_CM_EVENT_ESTABLISHED; event.status = 0; break; default: printk(KERN_ERR "RDMA CMA: unexpected IB CM event: %d\n", ib_event->event); goto out; } ret = id_priv->id.event_handler(&id_priv->id, &event); if (ret) { /* Destroy the CM ID by returning a non-zero value. */ id_priv->cm_id.ib = NULL; cma_exch(id_priv, RDMA_CM_DESTROYING); mutex_unlock(&id_priv->handler_mutex); rdma_destroy_id(&id_priv->id); return ret; } out: mutex_unlock(&id_priv->handler_mutex); return ret; } static int cma_resolve_ib_udp(struct rdma_id_private *id_priv, struct rdma_conn_param *conn_param) { struct ib_cm_sidr_req_param req; struct ib_cm_id *id; void *private_data; int offset, ret; memset(&req, 0, sizeof req); offset = cma_user_data_offset(id_priv); req.private_data_len = offset + conn_param->private_data_len; if (req.private_data_len < conn_param->private_data_len) return -EINVAL; if (req.private_data_len) { private_data = kzalloc(req.private_data_len, GFP_ATOMIC); if (!private_data) return -ENOMEM; } else { private_data = NULL; } if (conn_param->private_data && conn_param->private_data_len) memcpy(private_data + offset, conn_param->private_data, conn_param->private_data_len); if (private_data) { ret = cma_format_hdr(private_data, id_priv); if (ret) goto out; req.private_data = private_data; } id = ib_create_cm_id(id_priv->id.device, cma_sidr_rep_handler, id_priv); if (IS_ERR(id)) { ret = PTR_ERR(id); goto out; } id_priv->cm_id.ib = id; req.path = id_priv->id.route.path_rec; req.service_id = rdma_get_service_id(&id_priv->id, cma_dst_addr(id_priv)); req.timeout_ms = 1 << (CMA_CM_RESPONSE_TIMEOUT - 8); req.max_cm_retries = CMA_MAX_CM_RETRIES; ret = ib_send_cm_sidr_req(id_priv->cm_id.ib, &req); if (ret) { ib_destroy_cm_id(id_priv->cm_id.ib); id_priv->cm_id.ib = NULL; } out: kfree(private_data); return ret; } static int cma_connect_ib(struct rdma_id_private *id_priv, struct rdma_conn_param *conn_param) { struct ib_cm_req_param req; struct rdma_route *route; void *private_data; struct ib_cm_id *id; int offset, ret; memset(&req, 0, sizeof req); offset = cma_user_data_offset(id_priv); req.private_data_len = offset + conn_param->private_data_len; if (req.private_data_len < conn_param->private_data_len) return -EINVAL; if (req.private_data_len) { private_data = kzalloc(req.private_data_len, GFP_ATOMIC); if (!private_data) return -ENOMEM; } else { private_data = NULL; } if (conn_param->private_data && conn_param->private_data_len) memcpy(private_data + offset, conn_param->private_data, conn_param->private_data_len); id = ib_create_cm_id(id_priv->id.device, cma_ib_handler, id_priv); if (IS_ERR(id)) { ret = PTR_ERR(id); goto out; } id_priv->cm_id.ib = id; route = &id_priv->id.route; if (private_data) { ret = cma_format_hdr(private_data, id_priv); if (ret) goto out; req.private_data = private_data; } req.primary_path = &route->path_rec[0]; if (route->num_paths == 2) req.alternate_path = &route->path_rec[1]; req.service_id = rdma_get_service_id(&id_priv->id, cma_dst_addr(id_priv)); req.qp_num = id_priv->qp_num; req.qp_type = id_priv->id.qp_type; req.starting_psn = id_priv->seq_num; req.responder_resources = conn_param->responder_resources; req.initiator_depth = conn_param->initiator_depth; req.flow_control = conn_param->flow_control; req.retry_count = min_t(u8, 7, conn_param->retry_count); req.rnr_retry_count = min_t(u8, 7, conn_param->rnr_retry_count); req.remote_cm_response_timeout = CMA_CM_RESPONSE_TIMEOUT; req.local_cm_response_timeout = CMA_CM_RESPONSE_TIMEOUT; req.max_cm_retries = CMA_MAX_CM_RETRIES; req.srq = id_priv->srq ? 1 : 0; ret = ib_send_cm_req(id_priv->cm_id.ib, &req); out: if (ret && !IS_ERR(id)) { ib_destroy_cm_id(id); id_priv->cm_id.ib = NULL; } kfree(private_data); return ret; } static int cma_connect_iw(struct rdma_id_private *id_priv, struct rdma_conn_param *conn_param) { struct iw_cm_id *cm_id; int ret; struct iw_cm_conn_param iw_param; cm_id = iw_create_cm_id(id_priv->id.device, cma_iw_handler, id_priv); if (IS_ERR(cm_id)) return PTR_ERR(cm_id); id_priv->cm_id.iw = cm_id; memcpy(&cm_id->local_addr, cma_src_addr(id_priv), rdma_addr_size(cma_src_addr(id_priv))); memcpy(&cm_id->remote_addr, cma_dst_addr(id_priv), rdma_addr_size(cma_dst_addr(id_priv))); ret = cma_modify_qp_rtr(id_priv, conn_param); if (ret) goto out; if (conn_param) { iw_param.ord = conn_param->initiator_depth; iw_param.ird = conn_param->responder_resources; iw_param.private_data = conn_param->private_data; iw_param.private_data_len = conn_param->private_data_len; iw_param.qpn = id_priv->id.qp ? id_priv->qp_num : conn_param->qp_num; } else { memset(&iw_param, 0, sizeof iw_param); iw_param.qpn = id_priv->qp_num; } ret = iw_cm_connect(cm_id, &iw_param); out: if (ret) { iw_destroy_cm_id(cm_id); id_priv->cm_id.iw = NULL; } return ret; } int rdma_connect(struct rdma_cm_id *id, struct rdma_conn_param *conn_param) { struct rdma_id_private *id_priv; int ret; id_priv = container_of(id, struct rdma_id_private, id); if (!cma_comp_exch(id_priv, RDMA_CM_ROUTE_RESOLVED, RDMA_CM_CONNECT)) return -EINVAL; if (!id->qp) { id_priv->qp_num = conn_param->qp_num; id_priv->srq = conn_param->srq; } switch (rdma_node_get_transport(id->device->node_type)) { case RDMA_TRANSPORT_IB: if (id->qp_type == IB_QPT_UD) ret = cma_resolve_ib_udp(id_priv, conn_param); else ret = cma_connect_ib(id_priv, conn_param); break; case RDMA_TRANSPORT_IWARP: ret = cma_connect_iw(id_priv, conn_param); break; default: ret = -ENOSYS; break; } if (ret) goto err; return 0; err: cma_comp_exch(id_priv, RDMA_CM_CONNECT, RDMA_CM_ROUTE_RESOLVED); return ret; } EXPORT_SYMBOL(rdma_connect); static int cma_accept_ib(struct rdma_id_private *id_priv, struct rdma_conn_param *conn_param) { struct ib_cm_rep_param rep; int ret; ret = cma_modify_qp_rtr(id_priv, conn_param); if (ret) goto out; ret = cma_modify_qp_rts(id_priv, conn_param); if (ret) goto out; memset(&rep, 0, sizeof rep); rep.qp_num = id_priv->qp_num; rep.starting_psn = id_priv->seq_num; rep.private_data = conn_param->private_data; rep.private_data_len = conn_param->private_data_len; rep.responder_resources = conn_param->responder_resources; rep.initiator_depth = conn_param->initiator_depth; rep.failover_accepted = 0; rep.flow_control = conn_param->flow_control; rep.rnr_retry_count = min_t(u8, 7, conn_param->rnr_retry_count); rep.srq = id_priv->srq ? 1 : 0; ret = ib_send_cm_rep(id_priv->cm_id.ib, &rep); out: return ret; } static int cma_accept_iw(struct rdma_id_private *id_priv, struct rdma_conn_param *conn_param) { struct iw_cm_conn_param iw_param; int ret; ret = cma_modify_qp_rtr(id_priv, conn_param); if (ret) return ret; iw_param.ord = conn_param->initiator_depth; iw_param.ird = conn_param->responder_resources; iw_param.private_data = conn_param->private_data; iw_param.private_data_len = conn_param->private_data_len; if (id_priv->id.qp) { iw_param.qpn = id_priv->qp_num; } else iw_param.qpn = conn_param->qp_num; return iw_cm_accept(id_priv->cm_id.iw, &iw_param); } static int cma_send_sidr_rep(struct rdma_id_private *id_priv, enum ib_cm_sidr_status status, u32 qkey, const void *private_data, int private_data_len) { struct ib_cm_sidr_rep_param rep; int ret; memset(&rep, 0, sizeof rep); rep.status = status; if (status == IB_SIDR_SUCCESS) { ret = cma_set_qkey(id_priv, qkey); if (ret) return ret; rep.qp_num = id_priv->qp_num; rep.qkey = id_priv->qkey; } rep.private_data = private_data; rep.private_data_len = private_data_len; return ib_send_cm_sidr_rep(id_priv->cm_id.ib, &rep); } int rdma_accept(struct rdma_cm_id *id, struct rdma_conn_param *conn_param) { struct rdma_id_private *id_priv; int ret; id_priv = container_of(id, struct rdma_id_private, id); id_priv->owner = task_pid_nr(current); if (!cma_comp(id_priv, RDMA_CM_CONNECT)) return -EINVAL; if (!id->qp && conn_param) { id_priv->qp_num = conn_param->qp_num; id_priv->srq = conn_param->srq; } switch (rdma_node_get_transport(id->device->node_type)) { case RDMA_TRANSPORT_IB: if (id->qp_type == IB_QPT_UD) { if (conn_param) ret = cma_send_sidr_rep(id_priv, IB_SIDR_SUCCESS, conn_param->qkey, conn_param->private_data, conn_param->private_data_len); else ret = cma_send_sidr_rep(id_priv, IB_SIDR_SUCCESS, 0, NULL, 0); } else { if (conn_param) ret = cma_accept_ib(id_priv, conn_param); else ret = cma_rep_recv(id_priv); } break; case RDMA_TRANSPORT_IWARP: ret = cma_accept_iw(id_priv, conn_param); break; default: ret = -ENOSYS; break; } if (ret) goto reject; return 0; reject: cma_modify_qp_err(id_priv); rdma_reject(id, NULL, 0); return ret; } EXPORT_SYMBOL(rdma_accept); int rdma_notify(struct rdma_cm_id *id, enum ib_event_type event) { struct rdma_id_private *id_priv; int ret; id_priv = container_of(id, struct rdma_id_private, id); if (!id_priv->cm_id.ib) return -EINVAL; switch (id->device->node_type) { case RDMA_NODE_IB_CA: ret = ib_cm_notify(id_priv->cm_id.ib, event); break; default: ret = 0; break; } return ret; } EXPORT_SYMBOL(rdma_notify); int rdma_reject(struct rdma_cm_id *id, const void *private_data, u8 private_data_len) { struct rdma_id_private *id_priv; int ret; id_priv = container_of(id, struct rdma_id_private, id); if (!id_priv->cm_id.ib) return -EINVAL; switch (rdma_node_get_transport(id->device->node_type)) { case RDMA_TRANSPORT_IB: if (id->qp_type == IB_QPT_UD) ret = cma_send_sidr_rep(id_priv, IB_SIDR_REJECT, 0, private_data, private_data_len); else ret = ib_send_cm_rej(id_priv->cm_id.ib, IB_CM_REJ_CONSUMER_DEFINED, NULL, 0, private_data, private_data_len); break; case RDMA_TRANSPORT_IWARP: ret = iw_cm_reject(id_priv->cm_id.iw, private_data, private_data_len); break; default: ret = -ENOSYS; break; } return ret; } EXPORT_SYMBOL(rdma_reject); int rdma_disconnect(struct rdma_cm_id *id) { struct rdma_id_private *id_priv; int ret; id_priv = container_of(id, struct rdma_id_private, id); if (!id_priv->cm_id.ib) return -EINVAL; switch (rdma_node_get_transport(id->device->node_type)) { case RDMA_TRANSPORT_IB: ret = cma_modify_qp_err(id_priv); if (ret) goto out; /* Initiate or respond to a disconnect. */ if (ib_send_cm_dreq(id_priv->cm_id.ib, NULL, 0)) ib_send_cm_drep(id_priv->cm_id.ib, NULL, 0); break; case RDMA_TRANSPORT_IWARP: ret = iw_cm_disconnect(id_priv->cm_id.iw, 0); break; default: ret = -EINVAL; break; } out: return ret; } EXPORT_SYMBOL(rdma_disconnect); static int cma_ib_mc_handler(int status, struct ib_sa_multicast *multicast) { struct rdma_id_private *id_priv; struct cma_multicast *mc = multicast->context; struct rdma_cm_event event; int ret; id_priv = mc->id_priv; if (cma_disable_callback(id_priv, RDMA_CM_ADDR_BOUND) && cma_disable_callback(id_priv, RDMA_CM_ADDR_RESOLVED)) return 0; if (!status) status = cma_set_qkey(id_priv, be32_to_cpu(multicast->rec.qkey)); mutex_lock(&id_priv->qp_mutex); if (!status && id_priv->id.qp) status = ib_attach_mcast(id_priv->id.qp, &multicast->rec.mgid, be16_to_cpu(multicast->rec.mlid)); mutex_unlock(&id_priv->qp_mutex); memset(&event, 0, sizeof event); event.status = status; event.param.ud.private_data = mc->context; if (!status) { event.event = RDMA_CM_EVENT_MULTICAST_JOIN; ib_init_ah_from_mcmember(id_priv->id.device, id_priv->id.port_num, &multicast->rec, &event.param.ud.ah_attr); event.param.ud.qp_num = 0xFFFFFF; event.param.ud.qkey = be32_to_cpu(multicast->rec.qkey); } else event.event = RDMA_CM_EVENT_MULTICAST_ERROR; ret = id_priv->id.event_handler(&id_priv->id, &event); if (ret) { cma_exch(id_priv, RDMA_CM_DESTROYING); mutex_unlock(&id_priv->handler_mutex); rdma_destroy_id(&id_priv->id); return 0; } mutex_unlock(&id_priv->handler_mutex); return 0; } static void cma_set_mgid(struct rdma_id_private *id_priv, struct sockaddr *addr, union ib_gid *mgid) { unsigned char mc_map[MAX_ADDR_LEN]; struct rdma_dev_addr *dev_addr = &id_priv->id.route.addr.dev_addr; struct sockaddr_in *sin = (struct sockaddr_in *) addr; struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) addr; if (cma_any_addr(addr)) { memset(mgid, 0, sizeof *mgid); } else if ((addr->sa_family == AF_INET6) && ((be32_to_cpu(sin6->sin6_addr.s6_addr32[0]) & 0xFFF0FFFF) == 0xFF10A01B)) { /* IPv6 address is an SA assigned MGID. */ memcpy(mgid, &sin6->sin6_addr, sizeof *mgid); } else if (addr->sa_family == AF_IB) { memcpy(mgid, &((struct sockaddr_ib *) addr)->sib_addr, sizeof *mgid); } else if ((addr->sa_family == AF_INET6)) { ipv6_ib_mc_map(&sin6->sin6_addr, dev_addr->broadcast, mc_map); if (id_priv->id.ps == RDMA_PS_UDP) mc_map[7] = 0x01; /* Use RDMA CM signature */ *mgid = *(union ib_gid *) (mc_map + 4); } else { ip_ib_mc_map(sin->sin_addr.s_addr, dev_addr->broadcast, mc_map); if (id_priv->id.ps == RDMA_PS_UDP) mc_map[7] = 0x01; /* Use RDMA CM signature */ *mgid = *(union ib_gid *) (mc_map + 4); } } static int cma_join_ib_multicast(struct rdma_id_private *id_priv, struct cma_multicast *mc) { struct ib_sa_mcmember_rec rec; struct rdma_dev_addr *dev_addr = &id_priv->id.route.addr.dev_addr; ib_sa_comp_mask comp_mask; int ret; ib_addr_get_mgid(dev_addr, &rec.mgid); ret = ib_sa_get_mcmember_rec(id_priv->id.device, id_priv->id.port_num, &rec.mgid, &rec); if (ret) return ret; ret = cma_set_qkey(id_priv, 0); if (ret) return ret; cma_set_mgid(id_priv, (struct sockaddr *) &mc->addr, &rec.mgid); rec.qkey = cpu_to_be32(id_priv->qkey); rdma_addr_get_sgid(dev_addr, &rec.port_gid); rec.pkey = cpu_to_be16(ib_addr_get_pkey(dev_addr)); rec.join_state = 1; comp_mask = IB_SA_MCMEMBER_REC_MGID | IB_SA_MCMEMBER_REC_PORT_GID | IB_SA_MCMEMBER_REC_PKEY | IB_SA_MCMEMBER_REC_JOIN_STATE | IB_SA_MCMEMBER_REC_QKEY | IB_SA_MCMEMBER_REC_SL | IB_SA_MCMEMBER_REC_FLOW_LABEL | IB_SA_MCMEMBER_REC_TRAFFIC_CLASS; if (id_priv->id.ps == RDMA_PS_IPOIB) comp_mask |= IB_SA_MCMEMBER_REC_RATE | IB_SA_MCMEMBER_REC_RATE_SELECTOR | IB_SA_MCMEMBER_REC_MTU_SELECTOR | IB_SA_MCMEMBER_REC_MTU | IB_SA_MCMEMBER_REC_HOP_LIMIT; mc->multicast.ib = ib_sa_join_multicast(&sa_client, id_priv->id.device, id_priv->id.port_num, &rec, comp_mask, GFP_KERNEL, cma_ib_mc_handler, mc); return PTR_ERR_OR_ZERO(mc->multicast.ib); } static void iboe_mcast_work_handler(struct work_struct *work) { struct iboe_mcast_work *mw = container_of(work, struct iboe_mcast_work, work); struct cma_multicast *mc = mw->mc; struct ib_sa_multicast *m = mc->multicast.ib; mc->multicast.ib->context = mc; cma_ib_mc_handler(0, m); kref_put(&mc->mcref, release_mc); kfree(mw); } static void cma_iboe_set_mgid(struct sockaddr *addr, union ib_gid *mgid) { struct sockaddr_in *sin = (struct sockaddr_in *)addr; struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)addr; if (cma_any_addr(addr)) { memset(mgid, 0, sizeof *mgid); } else if (addr->sa_family == AF_INET6) { memcpy(mgid, &sin6->sin6_addr, sizeof *mgid); } else { mgid->raw[0] = 0xff; mgid->raw[1] = 0x0e; mgid->raw[2] = 0; mgid->raw[3] = 0; mgid->raw[4] = 0; mgid->raw[5] = 0; mgid->raw[6] = 0; mgid->raw[7] = 0; mgid->raw[8] = 0; mgid->raw[9] = 0; mgid->raw[10] = 0xff; mgid->raw[11] = 0xff; *(__be32 *)(&mgid->raw[12]) = sin->sin_addr.s_addr; } } static int cma_iboe_join_multicast(struct rdma_id_private *id_priv, struct cma_multicast *mc) { struct iboe_mcast_work *work; struct rdma_dev_addr *dev_addr = &id_priv->id.route.addr.dev_addr; int err; struct sockaddr *addr = (struct sockaddr *)&mc->addr; struct net_device *ndev = NULL; if (cma_zero_addr((struct sockaddr *)&mc->addr)) return -EINVAL; work = kzalloc(sizeof *work, GFP_KERNEL); if (!work) return -ENOMEM; mc->multicast.ib = kzalloc(sizeof(struct ib_sa_multicast), GFP_KERNEL); if (!mc->multicast.ib) { err = -ENOMEM; goto out1; } cma_iboe_set_mgid(addr, &mc->multicast.ib->rec.mgid); mc->multicast.ib->rec.pkey = cpu_to_be16(0xffff); if (id_priv->id.ps == RDMA_PS_UDP) mc->multicast.ib->rec.qkey = cpu_to_be32(RDMA_UDP_QKEY); if (dev_addr->bound_dev_if) ndev = dev_get_by_index(&init_net, dev_addr->bound_dev_if); if (!ndev) { err = -ENODEV; goto out2; } mc->multicast.ib->rec.rate = iboe_get_rate(ndev); mc->multicast.ib->rec.hop_limit = 1; mc->multicast.ib->rec.mtu = iboe_get_mtu(ndev->mtu); dev_put(ndev); if (!mc->multicast.ib->rec.mtu) { err = -EINVAL; goto out2; } rdma_ip2gid((struct sockaddr *)&id_priv->id.route.addr.src_addr, &mc->multicast.ib->rec.port_gid); work->id = id_priv; work->mc = mc; INIT_WORK(&work->work, iboe_mcast_work_handler); kref_get(&mc->mcref); queue_work(cma_wq, &work->work); return 0; out2: kfree(mc->multicast.ib); out1: kfree(work); return err; } int rdma_join_multicast(struct rdma_cm_id *id, struct sockaddr *addr, void *context) { struct rdma_id_private *id_priv; struct cma_multicast *mc; int ret; id_priv = container_of(id, struct rdma_id_private, id); if (!cma_comp(id_priv, RDMA_CM_ADDR_BOUND) && !cma_comp(id_priv, RDMA_CM_ADDR_RESOLVED)) return -EINVAL; mc = kmalloc(sizeof *mc, GFP_KERNEL); if (!mc) return -ENOMEM; memcpy(&mc->addr, addr, rdma_addr_size(addr)); mc->context = context; mc->id_priv = id_priv; spin_lock(&id_priv->lock); list_add(&mc->list, &id_priv->mc_list); spin_unlock(&id_priv->lock); switch (rdma_node_get_transport(id->device->node_type)) { case RDMA_TRANSPORT_IB: switch (rdma_port_get_link_layer(id->device, id->port_num)) { case IB_LINK_LAYER_INFINIBAND: ret = cma_join_ib_multicast(id_priv, mc); break; case IB_LINK_LAYER_ETHERNET: kref_init(&mc->mcref); ret = cma_iboe_join_multicast(id_priv, mc); break; default: ret = -EINVAL; } break; default: ret = -ENOSYS; break; } if (ret) { spin_lock_irq(&id_priv->lock); list_del(&mc->list); spin_unlock_irq(&id_priv->lock); kfree(mc); } return ret; } EXPORT_SYMBOL(rdma_join_multicast); void rdma_leave_multicast(struct rdma_cm_id *id, struct sockaddr *addr) { struct rdma_id_private *id_priv; struct cma_multicast *mc; id_priv = container_of(id, struct rdma_id_private, id); spin_lock_irq(&id_priv->lock); list_for_each_entry(mc, &id_priv->mc_list, list) { if (!memcmp(&mc->addr, addr, rdma_addr_size(addr))) { list_del(&mc->list); spin_unlock_irq(&id_priv->lock); if (id->qp) ib_detach_mcast(id->qp, &mc->multicast.ib->rec.mgid, be16_to_cpu(mc->multicast.ib->rec.mlid)); if (rdma_node_get_transport(id_priv->cma_dev->device->node_type) == RDMA_TRANSPORT_IB) { switch (rdma_port_get_link_layer(id->device, id->port_num)) { case IB_LINK_LAYER_INFINIBAND: ib_sa_free_multicast(mc->multicast.ib); kfree(mc); break; case IB_LINK_LAYER_ETHERNET: kref_put(&mc->mcref, release_mc); break; default: break; } } return; } } spin_unlock_irq(&id_priv->lock); } EXPORT_SYMBOL(rdma_leave_multicast); static int cma_netdev_change(struct net_device *ndev, struct rdma_id_private *id_priv) { struct rdma_dev_addr *dev_addr; struct cma_ndev_work *work; dev_addr = &id_priv->id.route.addr.dev_addr; if ((dev_addr->bound_dev_if == ndev->ifindex) && memcmp(dev_addr->src_dev_addr, ndev->dev_addr, ndev->addr_len)) { printk(KERN_INFO "RDMA CM addr change for ndev %s used by id %p\n", ndev->name, &id_priv->id); work = kzalloc(sizeof *work, GFP_KERNEL); if (!work) return -ENOMEM; INIT_WORK(&work->work, cma_ndev_work_handler); work->id = id_priv; work->event.event = RDMA_CM_EVENT_ADDR_CHANGE; atomic_inc(&id_priv->refcount); queue_work(cma_wq, &work->work); } return 0; } static int cma_netdev_callback(struct notifier_block *self, unsigned long event, void *ptr) { struct net_device *ndev = netdev_notifier_info_to_dev(ptr); struct cma_device *cma_dev; struct rdma_id_private *id_priv; int ret = NOTIFY_DONE; if (dev_net(ndev) != &init_net) return NOTIFY_DONE; if (event != NETDEV_BONDING_FAILOVER) return NOTIFY_DONE; if (!(ndev->flags & IFF_MASTER) || !(ndev->priv_flags & IFF_BONDING)) return NOTIFY_DONE; mutex_lock(&lock); list_for_each_entry(cma_dev, &dev_list, list) list_for_each_entry(id_priv, &cma_dev->id_list, list) { ret = cma_netdev_change(ndev, id_priv); if (ret) goto out; } out: mutex_unlock(&lock); return ret; } static struct notifier_block cma_nb = { .notifier_call = cma_netdev_callback }; static void cma_add_one(struct ib_device *device) { struct cma_device *cma_dev; struct rdma_id_private *id_priv; cma_dev = kmalloc(sizeof *cma_dev, GFP_KERNEL); if (!cma_dev) return; cma_dev->device = device; init_completion(&cma_dev->comp); atomic_set(&cma_dev->refcount, 1); INIT_LIST_HEAD(&cma_dev->id_list); ib_set_client_data(device, &cma_client, cma_dev); mutex_lock(&lock); list_add_tail(&cma_dev->list, &dev_list); list_for_each_entry(id_priv, &listen_any_list, list) cma_listen_on_dev(id_priv, cma_dev); mutex_unlock(&lock); } static int cma_remove_id_dev(struct rdma_id_private *id_priv) { struct rdma_cm_event event; enum rdma_cm_state state; int ret = 0; /* Record that we want to remove the device */ state = cma_exch(id_priv, RDMA_CM_DEVICE_REMOVAL); if (state == RDMA_CM_DESTROYING) return 0; cma_cancel_operation(id_priv, state); mutex_lock(&id_priv->handler_mutex); /* Check for destruction from another callback. */ if (!cma_comp(id_priv, RDMA_CM_DEVICE_REMOVAL)) goto out; memset(&event, 0, sizeof event); event.event = RDMA_CM_EVENT_DEVICE_REMOVAL; ret = id_priv->id.event_handler(&id_priv->id, &event); out: mutex_unlock(&id_priv->handler_mutex); return ret; } static void cma_process_remove(struct cma_device *cma_dev) { struct rdma_id_private *id_priv; int ret; mutex_lock(&lock); while (!list_empty(&cma_dev->id_list)) { id_priv = list_entry(cma_dev->id_list.next, struct rdma_id_private, list); list_del(&id_priv->listen_list); list_del_init(&id_priv->list); atomic_inc(&id_priv->refcount); mutex_unlock(&lock); ret = id_priv->internal_id ? 1 : cma_remove_id_dev(id_priv); cma_deref_id(id_priv); if (ret) rdma_destroy_id(&id_priv->id); mutex_lock(&lock); } mutex_unlock(&lock); cma_deref_dev(cma_dev); wait_for_completion(&cma_dev->comp); } static void cma_remove_one(struct ib_device *device) { struct cma_device *cma_dev; cma_dev = ib_get_client_data(device, &cma_client); if (!cma_dev) return; mutex_lock(&lock); list_del(&cma_dev->list); mutex_unlock(&lock); cma_process_remove(cma_dev); kfree(cma_dev); } static int cma_get_id_stats(struct sk_buff *skb, struct netlink_callback *cb) { struct nlmsghdr *nlh; struct rdma_cm_id_stats *id_stats; struct rdma_id_private *id_priv; struct rdma_cm_id *id = NULL; struct cma_device *cma_dev; int i_dev = 0, i_id = 0; /* * We export all of the IDs as a sequence of messages. Each * ID gets its own netlink message. */ mutex_lock(&lock); list_for_each_entry(cma_dev, &dev_list, list) { if (i_dev < cb->args[0]) { i_dev++; continue; } i_id = 0; list_for_each_entry(id_priv, &cma_dev->id_list, list) { if (i_id < cb->args[1]) { i_id++; continue; } id_stats = ibnl_put_msg(skb, &nlh, cb->nlh->nlmsg_seq, sizeof *id_stats, RDMA_NL_RDMA_CM, RDMA_NL_RDMA_CM_ID_STATS); if (!id_stats) goto out; memset(id_stats, 0, sizeof *id_stats); id = &id_priv->id; id_stats->node_type = id->route.addr.dev_addr.dev_type; id_stats->port_num = id->port_num; id_stats->bound_dev_if = id->route.addr.dev_addr.bound_dev_if; if (ibnl_put_attr(skb, nlh, rdma_addr_size(cma_src_addr(id_priv)), cma_src_addr(id_priv), RDMA_NL_RDMA_CM_ATTR_SRC_ADDR)) goto out; if (ibnl_put_attr(skb, nlh, rdma_addr_size(cma_src_addr(id_priv)), cma_dst_addr(id_priv), RDMA_NL_RDMA_CM_ATTR_DST_ADDR)) goto out; id_stats->pid = id_priv->owner; id_stats->port_space = id->ps; id_stats->cm_state = id_priv->state; id_stats->qp_num = id_priv->qp_num; id_stats->qp_type = id->qp_type; i_id++; } cb->args[1] = 0; i_dev++; } out: mutex_unlock(&lock); cb->args[0] = i_dev; cb->args[1] = i_id; return skb->len; } static const struct ibnl_client_cbs cma_cb_table[] = { [RDMA_NL_RDMA_CM_ID_STATS] = { .dump = cma_get_id_stats, .module = THIS_MODULE }, }; static int __init cma_init(void) { int ret; cma_wq = create_singlethread_workqueue("rdma_cm"); if (!cma_wq) return -ENOMEM; ib_sa_register_client(&sa_client); rdma_addr_register_client(&addr_client); register_netdevice_notifier(&cma_nb); ret = ib_register_client(&cma_client); if (ret) goto err; if (ibnl_add_client(RDMA_NL_RDMA_CM, RDMA_NL_RDMA_CM_NUM_OPS, cma_cb_table)) printk(KERN_WARNING "RDMA CMA: failed to add netlink callback\n"); return 0; err: unregister_netdevice_notifier(&cma_nb); rdma_addr_unregister_client(&addr_client); ib_sa_unregister_client(&sa_client); destroy_workqueue(cma_wq); return ret; } static void __exit cma_cleanup(void) { ibnl_remove_client(RDMA_NL_RDMA_CM); ib_unregister_client(&cma_client); unregister_netdevice_notifier(&cma_nb); rdma_addr_unregister_client(&addr_client); ib_sa_unregister_client(&sa_client); destroy_workqueue(cma_wq); idr_destroy(&tcp_ps); idr_destroy(&udp_ps); idr_destroy(&ipoib_ps); idr_destroy(&ib_ps); } module_init(cma_init); module_exit(cma_cleanup);
./CrossVul/dataset_final_sorted/CWE-20/c/good_2117_1
crossvul-cpp_data_bad_5844_5
/* * UDP over IPv6 * Linux INET6 implementation * * Authors: * Pedro Roque <roque@di.fc.ul.pt> * * Based on linux/ipv4/udp.c * * Fixes: * Hideaki YOSHIFUJI : sin6_scope_id support * YOSHIFUJI Hideaki @USAGI and: Support IPV6_V6ONLY socket option, which * Alexey Kuznetsov allow both IPv4 and IPv6 sockets to bind * a single port at the same time. * Kazunori MIYAZAWA @USAGI: change process style to use ip6_append_data * YOSHIFUJI Hideaki @USAGI: convert /proc/net/udp6 to seq_file. * * 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/errno.h> #include <linux/types.h> #include <linux/socket.h> #include <linux/sockios.h> #include <linux/net.h> #include <linux/in6.h> #include <linux/netdevice.h> #include <linux/if_arp.h> #include <linux/ipv6.h> #include <linux/icmpv6.h> #include <linux/init.h> #include <linux/module.h> #include <linux/skbuff.h> #include <linux/slab.h> #include <asm/uaccess.h> #include <net/ndisc.h> #include <net/protocol.h> #include <net/transp_v6.h> #include <net/ip6_route.h> #include <net/raw.h> #include <net/tcp_states.h> #include <net/ip6_checksum.h> #include <net/xfrm.h> #include <net/inet6_hashtables.h> #include <net/busy_poll.h> #include <linux/proc_fs.h> #include <linux/seq_file.h> #include <trace/events/skb.h> #include "udp_impl.h" static unsigned int udp6_ehashfn(struct net *net, const struct in6_addr *laddr, const u16 lport, const struct in6_addr *faddr, const __be16 fport) { static u32 udp6_ehash_secret __read_mostly; static u32 udp_ipv6_hash_secret __read_mostly; u32 lhash, fhash; net_get_random_once(&udp6_ehash_secret, sizeof(udp6_ehash_secret)); net_get_random_once(&udp_ipv6_hash_secret, sizeof(udp_ipv6_hash_secret)); lhash = (__force u32)laddr->s6_addr32[3]; fhash = __ipv6_addr_jhash(faddr, udp_ipv6_hash_secret); return __inet6_ehashfn(lhash, lport, fhash, fport, udp_ipv6_hash_secret + net_hash_mix(net)); } int ipv6_rcv_saddr_equal(const struct sock *sk, const struct sock *sk2) { const struct in6_addr *sk2_rcv_saddr6 = inet6_rcv_saddr(sk2); int sk_ipv6only = ipv6_only_sock(sk); int sk2_ipv6only = inet_v6_ipv6only(sk2); int addr_type = ipv6_addr_type(&sk->sk_v6_rcv_saddr); int addr_type2 = sk2_rcv_saddr6 ? ipv6_addr_type(sk2_rcv_saddr6) : IPV6_ADDR_MAPPED; /* if both are mapped, treat as IPv4 */ if (addr_type == IPV6_ADDR_MAPPED && addr_type2 == IPV6_ADDR_MAPPED) return (!sk2_ipv6only && (!sk->sk_rcv_saddr || !sk2->sk_rcv_saddr || sk->sk_rcv_saddr == sk2->sk_rcv_saddr)); if (addr_type2 == IPV6_ADDR_ANY && !(sk2_ipv6only && addr_type == IPV6_ADDR_MAPPED)) return 1; if (addr_type == IPV6_ADDR_ANY && !(sk_ipv6only && addr_type2 == IPV6_ADDR_MAPPED)) return 1; if (sk2_rcv_saddr6 && ipv6_addr_equal(&sk->sk_v6_rcv_saddr, sk2_rcv_saddr6)) return 1; return 0; } static unsigned int udp6_portaddr_hash(struct net *net, const struct in6_addr *addr6, unsigned int port) { unsigned int hash, mix = net_hash_mix(net); if (ipv6_addr_any(addr6)) hash = jhash_1word(0, mix); else if (ipv6_addr_v4mapped(addr6)) hash = jhash_1word((__force u32)addr6->s6_addr32[3], mix); else hash = jhash2((__force u32 *)addr6->s6_addr32, 4, mix); return hash ^ port; } int udp_v6_get_port(struct sock *sk, unsigned short snum) { unsigned int hash2_nulladdr = udp6_portaddr_hash(sock_net(sk), &in6addr_any, snum); unsigned int hash2_partial = udp6_portaddr_hash(sock_net(sk), &sk->sk_v6_rcv_saddr, 0); /* precompute partial secondary hash */ udp_sk(sk)->udp_portaddr_hash = hash2_partial; return udp_lib_get_port(sk, snum, ipv6_rcv_saddr_equal, hash2_nulladdr); } static void udp_v6_rehash(struct sock *sk) { u16 new_hash = udp6_portaddr_hash(sock_net(sk), &sk->sk_v6_rcv_saddr, inet_sk(sk)->inet_num); udp_lib_rehash(sk, new_hash); } static inline int compute_score(struct sock *sk, struct net *net, unsigned short hnum, const struct in6_addr *saddr, __be16 sport, const struct in6_addr *daddr, __be16 dport, int dif) { int score = -1; if (net_eq(sock_net(sk), net) && udp_sk(sk)->udp_port_hash == hnum && sk->sk_family == PF_INET6) { struct inet_sock *inet = inet_sk(sk); score = 0; if (inet->inet_dport) { if (inet->inet_dport != sport) return -1; score++; } if (!ipv6_addr_any(&sk->sk_v6_rcv_saddr)) { if (!ipv6_addr_equal(&sk->sk_v6_rcv_saddr, daddr)) return -1; score++; } if (!ipv6_addr_any(&sk->sk_v6_daddr)) { if (!ipv6_addr_equal(&sk->sk_v6_daddr, saddr)) return -1; score++; } if (sk->sk_bound_dev_if) { if (sk->sk_bound_dev_if != dif) return -1; score++; } } return score; } #define SCORE2_MAX (1 + 1 + 1) static inline int compute_score2(struct sock *sk, struct net *net, const struct in6_addr *saddr, __be16 sport, const struct in6_addr *daddr, unsigned short hnum, int dif) { int score = -1; if (net_eq(sock_net(sk), net) && udp_sk(sk)->udp_port_hash == hnum && sk->sk_family == PF_INET6) { struct inet_sock *inet = inet_sk(sk); if (!ipv6_addr_equal(&sk->sk_v6_rcv_saddr, daddr)) return -1; score = 0; if (inet->inet_dport) { if (inet->inet_dport != sport) return -1; score++; } if (!ipv6_addr_any(&sk->sk_v6_daddr)) { if (!ipv6_addr_equal(&sk->sk_v6_daddr, saddr)) return -1; score++; } if (sk->sk_bound_dev_if) { if (sk->sk_bound_dev_if != dif) return -1; score++; } } return score; } /* called with read_rcu_lock() */ static struct sock *udp6_lib_lookup2(struct net *net, const struct in6_addr *saddr, __be16 sport, const struct in6_addr *daddr, unsigned int hnum, int dif, struct udp_hslot *hslot2, unsigned int slot2) { struct sock *sk, *result; struct hlist_nulls_node *node; int score, badness, matches = 0, reuseport = 0; u32 hash = 0; begin: result = NULL; badness = -1; udp_portaddr_for_each_entry_rcu(sk, node, &hslot2->head) { score = compute_score2(sk, net, saddr, sport, daddr, hnum, dif); if (score > badness) { result = sk; badness = score; reuseport = sk->sk_reuseport; if (reuseport) { hash = udp6_ehashfn(net, daddr, hnum, saddr, sport); matches = 1; } else if (score == SCORE2_MAX) goto exact_match; } else if (score == badness && reuseport) { matches++; if (((u64)hash * matches) >> 32 == 0) result = sk; hash = next_pseudo_random32(hash); } } /* * if the nulls value we got at the end of this lookup is * not the expected one, we must restart lookup. * We probably met an item that was moved to another chain. */ if (get_nulls_value(node) != slot2) goto begin; if (result) { exact_match: if (unlikely(!atomic_inc_not_zero_hint(&result->sk_refcnt, 2))) result = NULL; else if (unlikely(compute_score2(result, net, saddr, sport, daddr, hnum, dif) < badness)) { sock_put(result); goto begin; } } return result; } struct sock *__udp6_lib_lookup(struct net *net, const struct in6_addr *saddr, __be16 sport, const struct in6_addr *daddr, __be16 dport, int dif, struct udp_table *udptable) { struct sock *sk, *result; struct hlist_nulls_node *node; unsigned short hnum = ntohs(dport); unsigned int hash2, slot2, slot = udp_hashfn(net, hnum, udptable->mask); struct udp_hslot *hslot2, *hslot = &udptable->hash[slot]; int score, badness, matches = 0, reuseport = 0; u32 hash = 0; rcu_read_lock(); if (hslot->count > 10) { hash2 = udp6_portaddr_hash(net, daddr, hnum); slot2 = hash2 & udptable->mask; hslot2 = &udptable->hash2[slot2]; if (hslot->count < hslot2->count) goto begin; result = udp6_lib_lookup2(net, saddr, sport, daddr, hnum, dif, hslot2, slot2); if (!result) { hash2 = udp6_portaddr_hash(net, &in6addr_any, hnum); slot2 = hash2 & udptable->mask; hslot2 = &udptable->hash2[slot2]; if (hslot->count < hslot2->count) goto begin; result = udp6_lib_lookup2(net, saddr, sport, &in6addr_any, hnum, dif, hslot2, slot2); } rcu_read_unlock(); return result; } begin: result = NULL; badness = -1; sk_nulls_for_each_rcu(sk, node, &hslot->head) { score = compute_score(sk, net, hnum, saddr, sport, daddr, dport, dif); if (score > badness) { result = sk; badness = score; reuseport = sk->sk_reuseport; if (reuseport) { hash = udp6_ehashfn(net, daddr, hnum, saddr, sport); matches = 1; } } else if (score == badness && reuseport) { matches++; if (((u64)hash * matches) >> 32 == 0) result = sk; hash = next_pseudo_random32(hash); } } /* * if the nulls value we got at the end of this lookup is * not the expected one, we must restart lookup. * We probably met an item that was moved to another chain. */ if (get_nulls_value(node) != slot) goto begin; if (result) { if (unlikely(!atomic_inc_not_zero_hint(&result->sk_refcnt, 2))) result = NULL; else if (unlikely(compute_score(result, net, hnum, saddr, sport, daddr, dport, dif) < badness)) { sock_put(result); goto begin; } } rcu_read_unlock(); return result; } EXPORT_SYMBOL_GPL(__udp6_lib_lookup); static struct sock *__udp6_lib_lookup_skb(struct sk_buff *skb, __be16 sport, __be16 dport, struct udp_table *udptable) { struct sock *sk; const struct ipv6hdr *iph = ipv6_hdr(skb); if (unlikely(sk = skb_steal_sock(skb))) return sk; return __udp6_lib_lookup(dev_net(skb_dst(skb)->dev), &iph->saddr, sport, &iph->daddr, dport, inet6_iif(skb), udptable); } struct sock *udp6_lib_lookup(struct net *net, const struct in6_addr *saddr, __be16 sport, const struct in6_addr *daddr, __be16 dport, int dif) { return __udp6_lib_lookup(net, saddr, sport, daddr, dport, dif, &udp_table); } EXPORT_SYMBOL_GPL(udp6_lib_lookup); /* * This should be easy, if there is something there we * return it, otherwise we block. */ int udpv6_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg, size_t len, int noblock, int flags, int *addr_len) { struct ipv6_pinfo *np = inet6_sk(sk); struct inet_sock *inet = inet_sk(sk); struct sk_buff *skb; unsigned int ulen, copied; int peeked, off = 0; int err; int is_udplite = IS_UDPLITE(sk); int is_udp4; bool slow; if (addr_len) *addr_len = sizeof(struct sockaddr_in6); if (flags & MSG_ERRQUEUE) return ipv6_recv_error(sk, msg, len); if (np->rxpmtu && np->rxopt.bits.rxpmtu) return ipv6_recv_rxpmtu(sk, msg, len); try_again: skb = __skb_recv_datagram(sk, flags | (noblock ? MSG_DONTWAIT : 0), &peeked, &off, &err); if (!skb) goto out; ulen = skb->len - sizeof(struct udphdr); copied = len; if (copied > ulen) copied = ulen; else if (copied < ulen) msg->msg_flags |= MSG_TRUNC; is_udp4 = (skb->protocol == htons(ETH_P_IP)); /* * If checksum is needed at all, try to do it while copying the * data. If the data is truncated, or if we only want a partial * coverage checksum (UDP-Lite), do it before the copy. */ if (copied < ulen || UDP_SKB_CB(skb)->partial_cov) { if (udp_lib_checksum_complete(skb)) goto csum_copy_err; } if (skb_csum_unnecessary(skb)) err = skb_copy_datagram_iovec(skb, sizeof(struct udphdr), msg->msg_iov, copied); else { err = skb_copy_and_csum_datagram_iovec(skb, sizeof(struct udphdr), msg->msg_iov); if (err == -EINVAL) goto csum_copy_err; } if (unlikely(err)) { trace_kfree_skb(skb, udpv6_recvmsg); if (!peeked) { atomic_inc(&sk->sk_drops); if (is_udp4) UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_INERRORS, is_udplite); else UDP6_INC_STATS_USER(sock_net(sk), UDP_MIB_INERRORS, is_udplite); } goto out_free; } if (!peeked) { if (is_udp4) UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_INDATAGRAMS, is_udplite); else UDP6_INC_STATS_USER(sock_net(sk), UDP_MIB_INDATAGRAMS, is_udplite); } sock_recv_ts_and_drops(msg, sk, skb); /* Copy the address. */ if (msg->msg_name) { struct sockaddr_in6 *sin6; sin6 = (struct sockaddr_in6 *) msg->msg_name; sin6->sin6_family = AF_INET6; sin6->sin6_port = udp_hdr(skb)->source; sin6->sin6_flowinfo = 0; if (is_udp4) { ipv6_addr_set_v4mapped(ip_hdr(skb)->saddr, &sin6->sin6_addr); sin6->sin6_scope_id = 0; } else { sin6->sin6_addr = ipv6_hdr(skb)->saddr; sin6->sin6_scope_id = ipv6_iface_scope_id(&sin6->sin6_addr, IP6CB(skb)->iif); } } if (is_udp4) { if (inet->cmsg_flags) ip_cmsg_recv(msg, skb); } else { if (np->rxopt.all) ip6_datagram_recv_ctl(sk, msg, skb); } err = copied; if (flags & MSG_TRUNC) err = ulen; out_free: skb_free_datagram_locked(sk, skb); out: return err; csum_copy_err: slow = lock_sock_fast(sk); if (!skb_kill_datagram(sk, skb, flags)) { if (is_udp4) { UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_CSUMERRORS, is_udplite); UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_INERRORS, is_udplite); } else { UDP6_INC_STATS_USER(sock_net(sk), UDP_MIB_CSUMERRORS, is_udplite); UDP6_INC_STATS_USER(sock_net(sk), UDP_MIB_INERRORS, is_udplite); } } unlock_sock_fast(sk, slow); if (noblock) return -EAGAIN; /* starting over for a new packet */ msg->msg_flags &= ~MSG_TRUNC; goto try_again; } void __udp6_lib_err(struct sk_buff *skb, struct inet6_skb_parm *opt, u8 type, u8 code, int offset, __be32 info, struct udp_table *udptable) { struct ipv6_pinfo *np; const struct ipv6hdr *hdr = (const struct ipv6hdr *)skb->data; const struct in6_addr *saddr = &hdr->saddr; const struct in6_addr *daddr = &hdr->daddr; struct udphdr *uh = (struct udphdr*)(skb->data+offset); struct sock *sk; int err; sk = __udp6_lib_lookup(dev_net(skb->dev), daddr, uh->dest, saddr, uh->source, inet6_iif(skb), udptable); if (sk == NULL) return; if (type == ICMPV6_PKT_TOOBIG) ip6_sk_update_pmtu(skb, sk, info); if (type == NDISC_REDIRECT) { ip6_sk_redirect(skb, sk); goto out; } np = inet6_sk(sk); if (!icmpv6_err_convert(type, code, &err) && !np->recverr) goto out; if (sk->sk_state != TCP_ESTABLISHED && !np->recverr) goto out; if (np->recverr) ipv6_icmp_error(sk, skb, err, uh->dest, ntohl(info), (u8 *)(uh+1)); sk->sk_err = err; sk->sk_error_report(sk); out: sock_put(sk); } static int __udpv6_queue_rcv_skb(struct sock *sk, struct sk_buff *skb) { int rc; if (!ipv6_addr_any(&sk->sk_v6_daddr)) { sock_rps_save_rxhash(sk, skb); sk_mark_napi_id(sk, skb); } rc = sock_queue_rcv_skb(sk, skb); if (rc < 0) { int is_udplite = IS_UDPLITE(sk); /* Note that an ENOMEM error is charged twice */ if (rc == -ENOMEM) UDP6_INC_STATS_BH(sock_net(sk), UDP_MIB_RCVBUFERRORS, is_udplite); UDP6_INC_STATS_BH(sock_net(sk), UDP_MIB_INERRORS, is_udplite); kfree_skb(skb); return -1; } return 0; } static __inline__ void udpv6_err(struct sk_buff *skb, struct inet6_skb_parm *opt, u8 type, u8 code, int offset, __be32 info ) { __udp6_lib_err(skb, opt, type, code, offset, info, &udp_table); } static struct static_key udpv6_encap_needed __read_mostly; void udpv6_encap_enable(void) { if (!static_key_enabled(&udpv6_encap_needed)) static_key_slow_inc(&udpv6_encap_needed); } EXPORT_SYMBOL(udpv6_encap_enable); int udpv6_queue_rcv_skb(struct sock *sk, struct sk_buff *skb) { struct udp_sock *up = udp_sk(sk); int rc; int is_udplite = IS_UDPLITE(sk); if (!xfrm6_policy_check(sk, XFRM_POLICY_IN, skb)) goto drop; if (static_key_false(&udpv6_encap_needed) && up->encap_type) { int (*encap_rcv)(struct sock *sk, struct sk_buff *skb); /* * This is an encapsulation socket so pass the skb to * the socket's udp_encap_rcv() hook. Otherwise, just * fall through and pass this up the UDP socket. * up->encap_rcv() returns the following value: * =0 if skb was successfully passed to the encap * handler or was discarded by it. * >0 if skb should be passed on to UDP. * <0 if skb should be resubmitted as proto -N */ /* if we're overly short, let UDP handle it */ encap_rcv = ACCESS_ONCE(up->encap_rcv); if (skb->len > sizeof(struct udphdr) && encap_rcv != NULL) { int ret; ret = encap_rcv(sk, skb); if (ret <= 0) { UDP_INC_STATS_BH(sock_net(sk), UDP_MIB_INDATAGRAMS, is_udplite); return -ret; } } /* FALLTHROUGH -- it's a UDP Packet */ } /* * UDP-Lite specific tests, ignored on UDP sockets (see net/ipv4/udp.c). */ if ((is_udplite & UDPLITE_RECV_CC) && UDP_SKB_CB(skb)->partial_cov) { if (up->pcrlen == 0) { /* full coverage was set */ LIMIT_NETDEBUG(KERN_WARNING "UDPLITE6: partial coverage" " %d while full coverage %d requested\n", UDP_SKB_CB(skb)->cscov, skb->len); goto drop; } if (UDP_SKB_CB(skb)->cscov < up->pcrlen) { LIMIT_NETDEBUG(KERN_WARNING "UDPLITE6: coverage %d " "too small, need min %d\n", UDP_SKB_CB(skb)->cscov, up->pcrlen); goto drop; } } if (rcu_access_pointer(sk->sk_filter)) { if (udp_lib_checksum_complete(skb)) goto csum_error; } if (sk_rcvqueues_full(sk, skb, sk->sk_rcvbuf)) goto drop; skb_dst_drop(skb); bh_lock_sock(sk); rc = 0; if (!sock_owned_by_user(sk)) rc = __udpv6_queue_rcv_skb(sk, skb); else if (sk_add_backlog(sk, skb, sk->sk_rcvbuf)) { bh_unlock_sock(sk); goto drop; } bh_unlock_sock(sk); return rc; csum_error: UDP6_INC_STATS_BH(sock_net(sk), UDP_MIB_CSUMERRORS, is_udplite); drop: UDP6_INC_STATS_BH(sock_net(sk), UDP_MIB_INERRORS, is_udplite); atomic_inc(&sk->sk_drops); kfree_skb(skb); return -1; } static struct sock *udp_v6_mcast_next(struct net *net, struct sock *sk, __be16 loc_port, const struct in6_addr *loc_addr, __be16 rmt_port, const struct in6_addr *rmt_addr, int dif) { struct hlist_nulls_node *node; struct sock *s = sk; unsigned short num = ntohs(loc_port); sk_nulls_for_each_from(s, node) { struct inet_sock *inet = inet_sk(s); if (!net_eq(sock_net(s), net)) continue; if (udp_sk(s)->udp_port_hash == num && s->sk_family == PF_INET6) { if (inet->inet_dport) { if (inet->inet_dport != rmt_port) continue; } if (!ipv6_addr_any(&sk->sk_v6_daddr) && !ipv6_addr_equal(&sk->sk_v6_daddr, rmt_addr)) continue; if (s->sk_bound_dev_if && s->sk_bound_dev_if != dif) continue; if (!ipv6_addr_any(&sk->sk_v6_rcv_saddr)) { if (!ipv6_addr_equal(&sk->sk_v6_rcv_saddr, loc_addr)) continue; } if (!inet6_mc_check(s, loc_addr, rmt_addr)) continue; return s; } } return NULL; } static void flush_stack(struct sock **stack, unsigned int count, struct sk_buff *skb, unsigned int final) { struct sk_buff *skb1 = NULL; struct sock *sk; unsigned int i; for (i = 0; i < count; i++) { sk = stack[i]; if (likely(skb1 == NULL)) skb1 = (i == final) ? skb : skb_clone(skb, GFP_ATOMIC); if (!skb1) { atomic_inc(&sk->sk_drops); UDP6_INC_STATS_BH(sock_net(sk), UDP_MIB_RCVBUFERRORS, IS_UDPLITE(sk)); UDP6_INC_STATS_BH(sock_net(sk), UDP_MIB_INERRORS, IS_UDPLITE(sk)); } if (skb1 && udpv6_queue_rcv_skb(sk, skb1) <= 0) skb1 = NULL; } if (unlikely(skb1)) kfree_skb(skb1); } /* * Note: called only from the BH handler context, * so we don't need to lock the hashes. */ static int __udp6_lib_mcast_deliver(struct net *net, struct sk_buff *skb, const struct in6_addr *saddr, const struct in6_addr *daddr, struct udp_table *udptable) { struct sock *sk, *stack[256 / sizeof(struct sock *)]; const struct udphdr *uh = udp_hdr(skb); struct udp_hslot *hslot = udp_hashslot(udptable, net, ntohs(uh->dest)); int dif; unsigned int i, count = 0; spin_lock(&hslot->lock); sk = sk_nulls_head(&hslot->head); dif = inet6_iif(skb); sk = udp_v6_mcast_next(net, sk, uh->dest, daddr, uh->source, saddr, dif); while (sk) { stack[count++] = sk; sk = udp_v6_mcast_next(net, sk_nulls_next(sk), uh->dest, daddr, uh->source, saddr, dif); if (unlikely(count == ARRAY_SIZE(stack))) { if (!sk) break; flush_stack(stack, count, skb, ~0); count = 0; } } /* * before releasing the lock, we must take reference on sockets */ for (i = 0; i < count; i++) sock_hold(stack[i]); spin_unlock(&hslot->lock); if (count) { flush_stack(stack, count, skb, count - 1); for (i = 0; i < count; i++) sock_put(stack[i]); } else { kfree_skb(skb); } return 0; } int __udp6_lib_rcv(struct sk_buff *skb, struct udp_table *udptable, int proto) { struct net *net = dev_net(skb->dev); struct sock *sk; struct udphdr *uh; const struct in6_addr *saddr, *daddr; u32 ulen = 0; if (!pskb_may_pull(skb, sizeof(struct udphdr))) goto discard; saddr = &ipv6_hdr(skb)->saddr; daddr = &ipv6_hdr(skb)->daddr; uh = udp_hdr(skb); ulen = ntohs(uh->len); if (ulen > skb->len) goto short_packet; if (proto == IPPROTO_UDP) { /* UDP validates ulen. */ /* Check for jumbo payload */ if (ulen == 0) ulen = skb->len; if (ulen < sizeof(*uh)) goto short_packet; if (ulen < skb->len) { if (pskb_trim_rcsum(skb, ulen)) goto short_packet; saddr = &ipv6_hdr(skb)->saddr; daddr = &ipv6_hdr(skb)->daddr; uh = udp_hdr(skb); } } if (udp6_csum_init(skb, uh, proto)) goto csum_error; /* * Multicast receive code */ if (ipv6_addr_is_multicast(daddr)) return __udp6_lib_mcast_deliver(net, skb, saddr, daddr, udptable); /* Unicast */ /* * check socket cache ... must talk to Alan about his plans * for sock caches... i'll skip this for now. */ sk = __udp6_lib_lookup_skb(skb, uh->source, uh->dest, udptable); if (sk != NULL) { int ret; ret = udpv6_queue_rcv_skb(sk, skb); sock_put(sk); /* a return value > 0 means to resubmit the input, but * it wants the return to be -protocol, or 0 */ if (ret > 0) return -ret; return 0; } if (!xfrm6_policy_check(NULL, XFRM_POLICY_IN, skb)) goto discard; if (udp_lib_checksum_complete(skb)) goto csum_error; UDP6_INC_STATS_BH(net, UDP_MIB_NOPORTS, proto == IPPROTO_UDPLITE); icmpv6_send(skb, ICMPV6_DEST_UNREACH, ICMPV6_PORT_UNREACH, 0); kfree_skb(skb); return 0; short_packet: LIMIT_NETDEBUG(KERN_DEBUG "UDP%sv6: short packet: From [%pI6c]:%u %d/%d to [%pI6c]:%u\n", proto == IPPROTO_UDPLITE ? "-Lite" : "", saddr, ntohs(uh->source), ulen, skb->len, daddr, ntohs(uh->dest)); goto discard; csum_error: UDP6_INC_STATS_BH(net, UDP_MIB_CSUMERRORS, proto == IPPROTO_UDPLITE); discard: UDP6_INC_STATS_BH(net, UDP_MIB_INERRORS, proto == IPPROTO_UDPLITE); kfree_skb(skb); return 0; } static __inline__ int udpv6_rcv(struct sk_buff *skb) { return __udp6_lib_rcv(skb, &udp_table, IPPROTO_UDP); } /* * Throw away all pending data and cancel the corking. Socket is locked. */ static void udp_v6_flush_pending_frames(struct sock *sk) { struct udp_sock *up = udp_sk(sk); if (up->pending == AF_INET) udp_flush_pending_frames(sk); else if (up->pending) { up->len = 0; up->pending = 0; ip6_flush_pending_frames(sk); } } /** * udp6_hwcsum_outgoing - handle outgoing HW checksumming * @sk: socket we are sending on * @skb: sk_buff containing the filled-in UDP header * (checksum field must be zeroed out) */ static void udp6_hwcsum_outgoing(struct sock *sk, struct sk_buff *skb, const struct in6_addr *saddr, const struct in6_addr *daddr, int len) { unsigned int offset; struct udphdr *uh = udp_hdr(skb); __wsum csum = 0; if (skb_queue_len(&sk->sk_write_queue) == 1) { /* Only one fragment on the socket. */ skb->csum_start = skb_transport_header(skb) - skb->head; skb->csum_offset = offsetof(struct udphdr, check); uh->check = ~csum_ipv6_magic(saddr, daddr, len, IPPROTO_UDP, 0); } else { /* * HW-checksum won't work as there are two or more * fragments on the socket so that all csums of sk_buffs * should be together */ offset = skb_transport_offset(skb); skb->csum = skb_checksum(skb, offset, skb->len - offset, 0); skb->ip_summed = CHECKSUM_NONE; skb_queue_walk(&sk->sk_write_queue, skb) { csum = csum_add(csum, skb->csum); } uh->check = csum_ipv6_magic(saddr, daddr, len, IPPROTO_UDP, csum); if (uh->check == 0) uh->check = CSUM_MANGLED_0; } } /* * Sending */ static int udp_v6_push_pending_frames(struct sock *sk) { struct sk_buff *skb; struct udphdr *uh; struct udp_sock *up = udp_sk(sk); struct inet_sock *inet = inet_sk(sk); struct flowi6 *fl6; int err = 0; int is_udplite = IS_UDPLITE(sk); __wsum csum = 0; if (up->pending == AF_INET) return udp_push_pending_frames(sk); fl6 = &inet->cork.fl.u.ip6; /* Grab the skbuff where UDP header space exists. */ if ((skb = skb_peek(&sk->sk_write_queue)) == NULL) goto out; /* * Create a UDP header */ uh = udp_hdr(skb); uh->source = fl6->fl6_sport; uh->dest = fl6->fl6_dport; uh->len = htons(up->len); uh->check = 0; if (is_udplite) csum = udplite_csum_outgoing(sk, skb); else if (skb->ip_summed == CHECKSUM_PARTIAL) { /* UDP hardware csum */ udp6_hwcsum_outgoing(sk, skb, &fl6->saddr, &fl6->daddr, up->len); goto send; } else csum = udp_csum_outgoing(sk, skb); /* add protocol-dependent pseudo-header */ uh->check = csum_ipv6_magic(&fl6->saddr, &fl6->daddr, up->len, fl6->flowi6_proto, csum); if (uh->check == 0) uh->check = CSUM_MANGLED_0; send: err = ip6_push_pending_frames(sk); if (err) { if (err == -ENOBUFS && !inet6_sk(sk)->recverr) { UDP6_INC_STATS_USER(sock_net(sk), UDP_MIB_SNDBUFERRORS, is_udplite); err = 0; } } else UDP6_INC_STATS_USER(sock_net(sk), UDP_MIB_OUTDATAGRAMS, is_udplite); out: up->len = 0; up->pending = 0; return err; } int udpv6_sendmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg, size_t len) { struct ipv6_txoptions opt_space; struct udp_sock *up = udp_sk(sk); struct inet_sock *inet = inet_sk(sk); struct ipv6_pinfo *np = inet6_sk(sk); struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) msg->msg_name; struct in6_addr *daddr, *final_p, final; struct ipv6_txoptions *opt = NULL; struct ip6_flowlabel *flowlabel = NULL; struct flowi6 fl6; struct dst_entry *dst; int addr_len = msg->msg_namelen; int ulen = len; int hlimit = -1; int tclass = -1; int dontfrag = -1; int corkreq = up->corkflag || msg->msg_flags&MSG_MORE; int err; int connected = 0; int is_udplite = IS_UDPLITE(sk); int (*getfrag)(void *, char *, int, int, int, struct sk_buff *); /* destination address check */ if (sin6) { if (addr_len < offsetof(struct sockaddr, sa_data)) return -EINVAL; switch (sin6->sin6_family) { case AF_INET6: if (addr_len < SIN6_LEN_RFC2133) return -EINVAL; daddr = &sin6->sin6_addr; break; case AF_INET: goto do_udp_sendmsg; case AF_UNSPEC: msg->msg_name = sin6 = NULL; msg->msg_namelen = addr_len = 0; daddr = NULL; break; default: return -EINVAL; } } else if (!up->pending) { if (sk->sk_state != TCP_ESTABLISHED) return -EDESTADDRREQ; daddr = &sk->sk_v6_daddr; } else daddr = NULL; if (daddr) { if (ipv6_addr_v4mapped(daddr)) { struct sockaddr_in sin; sin.sin_family = AF_INET; sin.sin_port = sin6 ? sin6->sin6_port : inet->inet_dport; sin.sin_addr.s_addr = daddr->s6_addr32[3]; msg->msg_name = &sin; msg->msg_namelen = sizeof(sin); do_udp_sendmsg: if (__ipv6_only_sock(sk)) return -ENETUNREACH; return udp_sendmsg(iocb, sk, msg, len); } } if (up->pending == AF_INET) return udp_sendmsg(iocb, sk, msg, len); /* Rough check on arithmetic overflow, better check is made in ip6_append_data(). */ if (len > INT_MAX - sizeof(struct udphdr)) return -EMSGSIZE; if (up->pending) { /* * There are pending frames. * The socket lock must be held while it's corked. */ lock_sock(sk); if (likely(up->pending)) { if (unlikely(up->pending != AF_INET6)) { release_sock(sk); return -EAFNOSUPPORT; } dst = NULL; goto do_append_data; } release_sock(sk); } ulen += sizeof(struct udphdr); memset(&fl6, 0, sizeof(fl6)); if (sin6) { if (sin6->sin6_port == 0) return -EINVAL; fl6.fl6_dport = sin6->sin6_port; daddr = &sin6->sin6_addr; if (np->sndflow) { fl6.flowlabel = sin6->sin6_flowinfo&IPV6_FLOWINFO_MASK; if (fl6.flowlabel&IPV6_FLOWLABEL_MASK) { flowlabel = fl6_sock_lookup(sk, fl6.flowlabel); if (flowlabel == NULL) return -EINVAL; daddr = &flowlabel->dst; } } /* * Otherwise it will be difficult to maintain * sk->sk_dst_cache. */ if (sk->sk_state == TCP_ESTABLISHED && ipv6_addr_equal(daddr, &sk->sk_v6_daddr)) daddr = &sk->sk_v6_daddr; if (addr_len >= sizeof(struct sockaddr_in6) && sin6->sin6_scope_id && __ipv6_addr_needs_scope_id(__ipv6_addr_type(daddr))) fl6.flowi6_oif = sin6->sin6_scope_id; } else { if (sk->sk_state != TCP_ESTABLISHED) return -EDESTADDRREQ; fl6.fl6_dport = inet->inet_dport; daddr = &sk->sk_v6_daddr; fl6.flowlabel = np->flow_label; connected = 1; } if (!fl6.flowi6_oif) fl6.flowi6_oif = sk->sk_bound_dev_if; if (!fl6.flowi6_oif) fl6.flowi6_oif = np->sticky_pktinfo.ipi6_ifindex; fl6.flowi6_mark = sk->sk_mark; if (msg->msg_controllen) { opt = &opt_space; memset(opt, 0, sizeof(struct ipv6_txoptions)); opt->tot_len = sizeof(*opt); err = ip6_datagram_send_ctl(sock_net(sk), sk, msg, &fl6, opt, &hlimit, &tclass, &dontfrag); if (err < 0) { fl6_sock_release(flowlabel); return err; } if ((fl6.flowlabel&IPV6_FLOWLABEL_MASK) && !flowlabel) { flowlabel = fl6_sock_lookup(sk, fl6.flowlabel); if (flowlabel == NULL) return -EINVAL; } if (!(opt->opt_nflen|opt->opt_flen)) opt = NULL; connected = 0; } if (opt == NULL) opt = np->opt; if (flowlabel) opt = fl6_merge_options(&opt_space, flowlabel, opt); opt = ipv6_fixup_options(&opt_space, opt); fl6.flowi6_proto = sk->sk_protocol; if (!ipv6_addr_any(daddr)) fl6.daddr = *daddr; else fl6.daddr.s6_addr[15] = 0x1; /* :: means loopback (BSD'ism) */ if (ipv6_addr_any(&fl6.saddr) && !ipv6_addr_any(&np->saddr)) fl6.saddr = np->saddr; fl6.fl6_sport = inet->inet_sport; final_p = fl6_update_dst(&fl6, opt, &final); if (final_p) connected = 0; if (!fl6.flowi6_oif && ipv6_addr_is_multicast(&fl6.daddr)) { fl6.flowi6_oif = np->mcast_oif; connected = 0; } else if (!fl6.flowi6_oif) fl6.flowi6_oif = np->ucast_oif; security_sk_classify_flow(sk, flowi6_to_flowi(&fl6)); dst = ip6_sk_dst_lookup_flow(sk, &fl6, final_p, true); if (IS_ERR(dst)) { err = PTR_ERR(dst); dst = NULL; goto out; } if (hlimit < 0) { if (ipv6_addr_is_multicast(&fl6.daddr)) hlimit = np->mcast_hops; else hlimit = np->hop_limit; if (hlimit < 0) hlimit = ip6_dst_hoplimit(dst); } if (tclass < 0) tclass = np->tclass; if (msg->msg_flags&MSG_CONFIRM) goto do_confirm; back_from_confirm: lock_sock(sk); if (unlikely(up->pending)) { /* The socket is already corked while preparing it. */ /* ... which is an evident application bug. --ANK */ release_sock(sk); LIMIT_NETDEBUG(KERN_DEBUG "udp cork app bug 2\n"); err = -EINVAL; goto out; } up->pending = AF_INET6; do_append_data: if (dontfrag < 0) dontfrag = np->dontfrag; up->len += ulen; getfrag = is_udplite ? udplite_getfrag : ip_generic_getfrag; err = ip6_append_data(sk, getfrag, msg->msg_iov, ulen, sizeof(struct udphdr), hlimit, tclass, opt, &fl6, (struct rt6_info*)dst, corkreq ? msg->msg_flags|MSG_MORE : msg->msg_flags, dontfrag); if (err) udp_v6_flush_pending_frames(sk); else if (!corkreq) err = udp_v6_push_pending_frames(sk); else if (unlikely(skb_queue_empty(&sk->sk_write_queue))) up->pending = 0; if (dst) { if (connected) { ip6_dst_store(sk, dst, ipv6_addr_equal(&fl6.daddr, &sk->sk_v6_daddr) ? &sk->sk_v6_daddr : NULL, #ifdef CONFIG_IPV6_SUBTREES ipv6_addr_equal(&fl6.saddr, &np->saddr) ? &np->saddr : #endif NULL); } else { dst_release(dst); } dst = NULL; } if (err > 0) err = np->recverr ? net_xmit_errno(err) : 0; release_sock(sk); out: dst_release(dst); fl6_sock_release(flowlabel); if (!err) return len; /* * ENOBUFS = no kernel mem, SOCK_NOSPACE = no sndbuf space. Reporting * ENOBUFS might not be good (it's not tunable per se), but otherwise * we don't have a good statistic (IpOutDiscards but it can be too many * things). We could add another new stat but at least for now that * seems like overkill. */ if (err == -ENOBUFS || test_bit(SOCK_NOSPACE, &sk->sk_socket->flags)) { UDP6_INC_STATS_USER(sock_net(sk), UDP_MIB_SNDBUFERRORS, is_udplite); } return err; do_confirm: dst_confirm(dst); if (!(msg->msg_flags&MSG_PROBE) || len) goto back_from_confirm; err = 0; goto out; } void udpv6_destroy_sock(struct sock *sk) { struct udp_sock *up = udp_sk(sk); lock_sock(sk); udp_v6_flush_pending_frames(sk); release_sock(sk); if (static_key_false(&udpv6_encap_needed) && up->encap_type) { void (*encap_destroy)(struct sock *sk); encap_destroy = ACCESS_ONCE(up->encap_destroy); if (encap_destroy) encap_destroy(sk); } inet6_destroy_sock(sk); } /* * Socket option code for UDP */ int udpv6_setsockopt(struct sock *sk, int level, int optname, char __user *optval, unsigned int optlen) { if (level == SOL_UDP || level == SOL_UDPLITE) return udp_lib_setsockopt(sk, level, optname, optval, optlen, udp_v6_push_pending_frames); return ipv6_setsockopt(sk, level, optname, optval, optlen); } #ifdef CONFIG_COMPAT int compat_udpv6_setsockopt(struct sock *sk, int level, int optname, char __user *optval, unsigned int optlen) { if (level == SOL_UDP || level == SOL_UDPLITE) return udp_lib_setsockopt(sk, level, optname, optval, optlen, udp_v6_push_pending_frames); return compat_ipv6_setsockopt(sk, level, optname, optval, optlen); } #endif int udpv6_getsockopt(struct sock *sk, int level, int optname, char __user *optval, int __user *optlen) { if (level == SOL_UDP || level == SOL_UDPLITE) return udp_lib_getsockopt(sk, level, optname, optval, optlen); return ipv6_getsockopt(sk, level, optname, optval, optlen); } #ifdef CONFIG_COMPAT int compat_udpv6_getsockopt(struct sock *sk, int level, int optname, char __user *optval, int __user *optlen) { if (level == SOL_UDP || level == SOL_UDPLITE) return udp_lib_getsockopt(sk, level, optname, optval, optlen); return compat_ipv6_getsockopt(sk, level, optname, optval, optlen); } #endif static const struct inet6_protocol udpv6_protocol = { .handler = udpv6_rcv, .err_handler = udpv6_err, .flags = INET6_PROTO_NOPOLICY|INET6_PROTO_FINAL, }; /* ------------------------------------------------------------------------ */ #ifdef CONFIG_PROC_FS int udp6_seq_show(struct seq_file *seq, void *v) { if (v == SEQ_START_TOKEN) { seq_puts(seq, IPV6_SEQ_DGRAM_HEADER); } else { int bucket = ((struct udp_iter_state *)seq->private)->bucket; struct inet_sock *inet = inet_sk(v); __u16 srcp = ntohs(inet->inet_sport); __u16 destp = ntohs(inet->inet_dport); ip6_dgram_sock_seq_show(seq, v, srcp, destp, bucket); } return 0; } static const struct file_operations udp6_afinfo_seq_fops = { .owner = THIS_MODULE, .open = udp_seq_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release_net }; static struct udp_seq_afinfo udp6_seq_afinfo = { .name = "udp6", .family = AF_INET6, .udp_table = &udp_table, .seq_fops = &udp6_afinfo_seq_fops, .seq_ops = { .show = udp6_seq_show, }, }; int __net_init udp6_proc_init(struct net *net) { return udp_proc_register(net, &udp6_seq_afinfo); } void udp6_proc_exit(struct net *net) { udp_proc_unregister(net, &udp6_seq_afinfo); } #endif /* CONFIG_PROC_FS */ void udp_v6_clear_sk(struct sock *sk, int size) { struct inet_sock *inet = inet_sk(sk); /* we do not want to clear pinet6 field, because of RCU lookups */ sk_prot_clear_portaddr_nulls(sk, offsetof(struct inet_sock, pinet6)); size -= offsetof(struct inet_sock, pinet6) + sizeof(inet->pinet6); memset(&inet->pinet6 + 1, 0, size); } /* ------------------------------------------------------------------------ */ struct proto udpv6_prot = { .name = "UDPv6", .owner = THIS_MODULE, .close = udp_lib_close, .connect = ip6_datagram_connect, .disconnect = udp_disconnect, .ioctl = udp_ioctl, .destroy = udpv6_destroy_sock, .setsockopt = udpv6_setsockopt, .getsockopt = udpv6_getsockopt, .sendmsg = udpv6_sendmsg, .recvmsg = udpv6_recvmsg, .backlog_rcv = __udpv6_queue_rcv_skb, .hash = udp_lib_hash, .unhash = udp_lib_unhash, .rehash = udp_v6_rehash, .get_port = udp_v6_get_port, .memory_allocated = &udp_memory_allocated, .sysctl_mem = sysctl_udp_mem, .sysctl_wmem = &sysctl_udp_wmem_min, .sysctl_rmem = &sysctl_udp_rmem_min, .obj_size = sizeof(struct udp6_sock), .slab_flags = SLAB_DESTROY_BY_RCU, .h.udp_table = &udp_table, #ifdef CONFIG_COMPAT .compat_setsockopt = compat_udpv6_setsockopt, .compat_getsockopt = compat_udpv6_getsockopt, #endif .clear_sk = udp_v6_clear_sk, }; static struct inet_protosw udpv6_protosw = { .type = SOCK_DGRAM, .protocol = IPPROTO_UDP, .prot = &udpv6_prot, .ops = &inet6_dgram_ops, .no_check = UDP_CSUM_DEFAULT, .flags = INET_PROTOSW_PERMANENT, }; int __init udpv6_init(void) { int ret; ret = inet6_add_protocol(&udpv6_protocol, IPPROTO_UDP); if (ret) goto out; ret = inet6_register_protosw(&udpv6_protosw); if (ret) goto out_udpv6_protocol; out: return ret; out_udpv6_protocol: inet6_del_protocol(&udpv6_protocol, IPPROTO_UDP); goto out; } void udpv6_exit(void) { inet6_unregister_protosw(&udpv6_protosw); inet6_del_protocol(&udpv6_protocol, IPPROTO_UDP); }
./CrossVul/dataset_final_sorted/CWE-20/c/bad_5844_5
crossvul-cpp_data_good_1657_1
/* A Bison parser, made by GNU Bison 2.4.1. */ /* Skeleton implementation for Bison's Yacc-like parsers in C Copyright (C) 1984, 1989, 1990, 2000, 2001, 2002, 2003, 2004, 2005, 2006 Free Software Foundation, Inc. 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/>. */ /* As a special exception, you may create a larger work that contains part or all of the Bison parser skeleton and distribute that work under terms of your choice, so long as that work isn't itself a parser generator using the skeleton or a modified version thereof as a parser skeleton. Alternatively, if you modify or redistribute the parser skeleton itself, you may (at your option) remove this special exception, which will cause the skeleton and the resulting Bison output files to be licensed under the GNU General Public License without this special exception. This special exception was added by the Free Software Foundation in version 2.2 of Bison. */ /* C LALR(1) parser skeleton written by Richard Stallman, by simplifying the original so-called "semantic" parser. */ /* All symbols defined below should begin with yy or YY, to avoid infringing on user name space. This should be done even for local variables, as they might otherwise be expanded by user macros. There are some unavoidable exceptions within include files to define necessary library symbols; they are noted "INFRINGES ON USER NAME SPACE" below. */ /* Identify Bison output. */ #define YYBISON 1 /* Bison version. */ #define YYBISON_VERSION "2.4.1" /* Skeleton name. */ #define YYSKELETON_NAME "yacc.c" /* Pure parsers. */ #define YYPURE 0 /* Push parsers. */ #define YYPUSH 0 /* Pull parsers. */ #define YYPULL 1 /* Using locations. */ #define YYLSP_NEEDED 0 /* Copy the first part of user declarations. */ /* Line 189 of yacc.c */ #line 11 "ntp_parser.y" #ifdef HAVE_CONFIG_H # include <config.h> #endif #include "ntpd.h" #include "ntp_machine.h" #include "ntp.h" #include "ntp_stdlib.h" #include "ntp_filegen.h" #include "ntp_data_structures.h" #include "ntp_scanner.h" #include "ntp_config.h" #include "ntp_crypto.h" #include "ntpsim.h" /* HMS: Do we really want this all the time? */ /* SK: It might be a good idea to always include the simulator code. That way someone can use the same configuration file for both the simulator and the daemon */ struct FILE_INFO *ip_file; /* Pointer to the configuration file stream */ #define YYMALLOC emalloc #define YYFREE free #define YYERROR_VERBOSE #define YYMAXDEPTH 1000 /* stop the madness sooner */ void yyerror (char *msg); extern int input_from_file; /* 0=input from ntpq :config */ /* Line 189 of yacc.c */ #line 107 "ntp_parser.c" /* Enabling traces. */ #ifndef YYDEBUG # define YYDEBUG 1 #endif /* Enabling verbose error messages. */ #ifdef YYERROR_VERBOSE # undef YYERROR_VERBOSE # define YYERROR_VERBOSE 1 #else # define YYERROR_VERBOSE 0 #endif /* Enabling the token table. */ #ifndef YYTOKEN_TABLE # define YYTOKEN_TABLE 1 #endif /* Tokens. */ #ifndef YYTOKENTYPE # define YYTOKENTYPE /* Put the tokens into the symbol table, so that GDB and other debuggers know about them. */ enum yytokentype { T_Age = 258, T_All = 259, T_Allan = 260, T_Auth = 261, T_Autokey = 262, T_Automax = 263, T_Average = 264, T_Bclient = 265, T_Beacon = 266, T_Bias = 267, T_Broadcast = 268, T_Broadcastclient = 269, T_Broadcastdelay = 270, T_Burst = 271, T_Calibrate = 272, T_Calldelay = 273, T_Ceiling = 274, T_Clockstats = 275, T_Cohort = 276, T_ControlKey = 277, T_Crypto = 278, T_Cryptostats = 279, T_Day = 280, T_Default = 281, T_Digest = 282, T_Disable = 283, T_Discard = 284, T_Dispersion = 285, T_Double = 286, T_Driftfile = 287, T_Drop = 288, T_Ellipsis = 289, T_Enable = 290, T_End = 291, T_False = 292, T_File = 293, T_Filegen = 294, T_Flag1 = 295, T_Flag2 = 296, T_Flag3 = 297, T_Flag4 = 298, T_Flake = 299, T_Floor = 300, T_Freq = 301, T_Fudge = 302, T_Host = 303, T_Huffpuff = 304, T_Iburst = 305, T_Ident = 306, T_Ignore = 307, T_Incalloc = 308, T_Incmem = 309, T_Initalloc = 310, T_Initmem = 311, T_Includefile = 312, T_Integer = 313, T_Interface = 314, T_Ipv4 = 315, T_Ipv4_flag = 316, T_Ipv6 = 317, T_Ipv6_flag = 318, T_Kernel = 319, T_Key = 320, T_Keys = 321, T_Keysdir = 322, T_Kod = 323, T_Mssntp = 324, T_Leapfile = 325, T_Limited = 326, T_Link = 327, T_Listen = 328, T_Logconfig = 329, T_Logfile = 330, T_Loopstats = 331, T_Lowpriotrap = 332, T_Manycastclient = 333, T_Manycastserver = 334, T_Mask = 335, T_Maxage = 336, T_Maxclock = 337, T_Maxdepth = 338, T_Maxdist = 339, T_Maxmem = 340, T_Maxpoll = 341, T_Minclock = 342, T_Mindepth = 343, T_Mindist = 344, T_Minimum = 345, T_Minpoll = 346, T_Minsane = 347, T_Mode = 348, T_Monitor = 349, T_Month = 350, T_Mru = 351, T_Multicastclient = 352, T_Nic = 353, T_Nolink = 354, T_Nomodify = 355, T_None = 356, T_Nopeer = 357, T_Noquery = 358, T_Noselect = 359, T_Noserve = 360, T_Notrap = 361, T_Notrust = 362, T_Ntp = 363, T_Ntpport = 364, T_NtpSignDsocket = 365, T_Orphan = 366, T_Orphanwait = 367, T_Panic = 368, T_Peer = 369, T_Peerstats = 370, T_Phone = 371, T_Pid = 372, T_Pidfile = 373, T_Pool = 374, T_Port = 375, T_Preempt = 376, T_Prefer = 377, T_Protostats = 378, T_Pw = 379, T_Qos = 380, T_Randfile = 381, T_Rawstats = 382, T_Refid = 383, T_Requestkey = 384, T_Restrict = 385, T_Revoke = 386, T_Saveconfigdir = 387, T_Server = 388, T_Setvar = 389, T_Sign = 390, T_Source = 391, T_Statistics = 392, T_Stats = 393, T_Statsdir = 394, T_Step = 395, T_Stepout = 396, T_Stratum = 397, T_String = 398, T_Sysstats = 399, T_Tick = 400, T_Time1 = 401, T_Time2 = 402, T_Timingstats = 403, T_Tinker = 404, T_Tos = 405, T_Trap = 406, T_True = 407, T_Trustedkey = 408, T_Ttl = 409, T_Type = 410, T_Unconfig = 411, T_Unpeer = 412, T_Version = 413, T_WanderThreshold = 414, T_Week = 415, T_Wildcard = 416, T_Xleave = 417, T_Year = 418, T_Flag = 419, T_Void = 420, T_EOC = 421, T_Simulate = 422, T_Beep_Delay = 423, T_Sim_Duration = 424, T_Server_Offset = 425, T_Duration = 426, T_Freq_Offset = 427, T_Wander = 428, T_Jitter = 429, T_Prop_Delay = 430, T_Proc_Delay = 431 }; #endif /* Tokens. */ #define T_Age 258 #define T_All 259 #define T_Allan 260 #define T_Auth 261 #define T_Autokey 262 #define T_Automax 263 #define T_Average 264 #define T_Bclient 265 #define T_Beacon 266 #define T_Bias 267 #define T_Broadcast 268 #define T_Broadcastclient 269 #define T_Broadcastdelay 270 #define T_Burst 271 #define T_Calibrate 272 #define T_Calldelay 273 #define T_Ceiling 274 #define T_Clockstats 275 #define T_Cohort 276 #define T_ControlKey 277 #define T_Crypto 278 #define T_Cryptostats 279 #define T_Day 280 #define T_Default 281 #define T_Digest 282 #define T_Disable 283 #define T_Discard 284 #define T_Dispersion 285 #define T_Double 286 #define T_Driftfile 287 #define T_Drop 288 #define T_Ellipsis 289 #define T_Enable 290 #define T_End 291 #define T_False 292 #define T_File 293 #define T_Filegen 294 #define T_Flag1 295 #define T_Flag2 296 #define T_Flag3 297 #define T_Flag4 298 #define T_Flake 299 #define T_Floor 300 #define T_Freq 301 #define T_Fudge 302 #define T_Host 303 #define T_Huffpuff 304 #define T_Iburst 305 #define T_Ident 306 #define T_Ignore 307 #define T_Incalloc 308 #define T_Incmem 309 #define T_Initalloc 310 #define T_Initmem 311 #define T_Includefile 312 #define T_Integer 313 #define T_Interface 314 #define T_Ipv4 315 #define T_Ipv4_flag 316 #define T_Ipv6 317 #define T_Ipv6_flag 318 #define T_Kernel 319 #define T_Key 320 #define T_Keys 321 #define T_Keysdir 322 #define T_Kod 323 #define T_Mssntp 324 #define T_Leapfile 325 #define T_Limited 326 #define T_Link 327 #define T_Listen 328 #define T_Logconfig 329 #define T_Logfile 330 #define T_Loopstats 331 #define T_Lowpriotrap 332 #define T_Manycastclient 333 #define T_Manycastserver 334 #define T_Mask 335 #define T_Maxage 336 #define T_Maxclock 337 #define T_Maxdepth 338 #define T_Maxdist 339 #define T_Maxmem 340 #define T_Maxpoll 341 #define T_Minclock 342 #define T_Mindepth 343 #define T_Mindist 344 #define T_Minimum 345 #define T_Minpoll 346 #define T_Minsane 347 #define T_Mode 348 #define T_Monitor 349 #define T_Month 350 #define T_Mru 351 #define T_Multicastclient 352 #define T_Nic 353 #define T_Nolink 354 #define T_Nomodify 355 #define T_None 356 #define T_Nopeer 357 #define T_Noquery 358 #define T_Noselect 359 #define T_Noserve 360 #define T_Notrap 361 #define T_Notrust 362 #define T_Ntp 363 #define T_Ntpport 364 #define T_NtpSignDsocket 365 #define T_Orphan 366 #define T_Orphanwait 367 #define T_Panic 368 #define T_Peer 369 #define T_Peerstats 370 #define T_Phone 371 #define T_Pid 372 #define T_Pidfile 373 #define T_Pool 374 #define T_Port 375 #define T_Preempt 376 #define T_Prefer 377 #define T_Protostats 378 #define T_Pw 379 #define T_Qos 380 #define T_Randfile 381 #define T_Rawstats 382 #define T_Refid 383 #define T_Requestkey 384 #define T_Restrict 385 #define T_Revoke 386 #define T_Saveconfigdir 387 #define T_Server 388 #define T_Setvar 389 #define T_Sign 390 #define T_Source 391 #define T_Statistics 392 #define T_Stats 393 #define T_Statsdir 394 #define T_Step 395 #define T_Stepout 396 #define T_Stratum 397 #define T_String 398 #define T_Sysstats 399 #define T_Tick 400 #define T_Time1 401 #define T_Time2 402 #define T_Timingstats 403 #define T_Tinker 404 #define T_Tos 405 #define T_Trap 406 #define T_True 407 #define T_Trustedkey 408 #define T_Ttl 409 #define T_Type 410 #define T_Unconfig 411 #define T_Unpeer 412 #define T_Version 413 #define T_WanderThreshold 414 #define T_Week 415 #define T_Wildcard 416 #define T_Xleave 417 #define T_Year 418 #define T_Flag 419 #define T_Void 420 #define T_EOC 421 #define T_Simulate 422 #define T_Beep_Delay 423 #define T_Sim_Duration 424 #define T_Server_Offset 425 #define T_Duration 426 #define T_Freq_Offset 427 #define T_Wander 428 #define T_Jitter 429 #define T_Prop_Delay 430 #define T_Proc_Delay 431 #if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED typedef union YYSTYPE { /* Line 214 of yacc.c */ #line 50 "ntp_parser.y" char *String; double Double; int Integer; void *VoidPtr; queue *Queue; struct attr_val *Attr_val; struct address_node *Address_node; struct setvar_node *Set_var; /* Simulation types */ server_info *Sim_server; script_info *Sim_script; /* Line 214 of yacc.c */ #line 512 "ntp_parser.c" } YYSTYPE; # define YYSTYPE_IS_TRIVIAL 1 # define yystype YYSTYPE /* obsolescent; will be withdrawn */ # define YYSTYPE_IS_DECLARED 1 #endif /* Copy the second part of user declarations. */ /* Line 264 of yacc.c */ #line 524 "ntp_parser.c" #ifdef short # undef short #endif #ifdef YYTYPE_UINT8 typedef YYTYPE_UINT8 yytype_uint8; #else typedef unsigned char yytype_uint8; #endif #ifdef YYTYPE_INT8 typedef YYTYPE_INT8 yytype_int8; #elif (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) typedef signed char yytype_int8; #else typedef short int yytype_int8; #endif #ifdef YYTYPE_UINT16 typedef YYTYPE_UINT16 yytype_uint16; #else typedef unsigned short int yytype_uint16; #endif #ifdef YYTYPE_INT16 typedef YYTYPE_INT16 yytype_int16; #else typedef short int yytype_int16; #endif #ifndef YYSIZE_T # ifdef __SIZE_TYPE__ # define YYSIZE_T __SIZE_TYPE__ # elif defined size_t # define YYSIZE_T size_t # elif ! defined YYSIZE_T && (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) # include <stddef.h> /* INFRINGES ON USER NAME SPACE */ # define YYSIZE_T size_t # else # define YYSIZE_T unsigned int # endif #endif #define YYSIZE_MAXIMUM ((YYSIZE_T) -1) #ifndef YY_ # if YYENABLE_NLS # if ENABLE_NLS # include <libintl.h> /* INFRINGES ON USER NAME SPACE */ # define YY_(msgid) dgettext ("bison-runtime", msgid) # endif # endif # ifndef YY_ # define YY_(msgid) msgid # endif #endif /* Suppress unused-variable warnings by "using" E. */ #if ! defined lint || defined __GNUC__ # define YYUSE(e) ((void) (e)) #else # define YYUSE(e) /* empty */ #endif /* Identity function, used to suppress warnings about constant conditions. */ #ifndef lint # define YYID(n) (n) #else #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static int YYID (int yyi) #else static int YYID (yyi) int yyi; #endif { return yyi; } #endif #if ! defined yyoverflow || YYERROR_VERBOSE /* The parser invokes alloca or malloc; define the necessary symbols. */ # ifdef YYSTACK_USE_ALLOCA # if YYSTACK_USE_ALLOCA # ifdef __GNUC__ # define YYSTACK_ALLOC __builtin_alloca # elif defined __BUILTIN_VA_ARG_INCR # include <alloca.h> /* INFRINGES ON USER NAME SPACE */ # elif defined _AIX # define YYSTACK_ALLOC __alloca # elif defined _MSC_VER # include <malloc.h> /* INFRINGES ON USER NAME SPACE */ # define alloca _alloca # else # define YYSTACK_ALLOC alloca # if ! defined _ALLOCA_H && ! defined _STDLIB_H && (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) # include <stdlib.h> /* INFRINGES ON USER NAME SPACE */ # ifndef _STDLIB_H # define _STDLIB_H 1 # endif # endif # endif # endif # endif # ifdef YYSTACK_ALLOC /* Pacify GCC's `empty if-body' warning. */ # define YYSTACK_FREE(Ptr) do { /* empty */; } while (YYID (0)) # ifndef YYSTACK_ALLOC_MAXIMUM /* The OS might guarantee only one guard page at the bottom of the stack, and a page size can be as small as 4096 bytes. So we cannot safely invoke alloca (N) if N exceeds 4096. Use a slightly smaller number to allow for a few compiler-allocated temporary stack slots. */ # define YYSTACK_ALLOC_MAXIMUM 4032 /* reasonable circa 2006 */ # endif # else # define YYSTACK_ALLOC YYMALLOC # define YYSTACK_FREE YYFREE # ifndef YYSTACK_ALLOC_MAXIMUM # define YYSTACK_ALLOC_MAXIMUM YYSIZE_MAXIMUM # endif # if (defined __cplusplus && ! defined _STDLIB_H \ && ! ((defined YYMALLOC || defined malloc) \ && (defined YYFREE || defined free))) # include <stdlib.h> /* INFRINGES ON USER NAME SPACE */ # ifndef _STDLIB_H # define _STDLIB_H 1 # endif # endif # ifndef YYMALLOC # define YYMALLOC malloc # if ! defined malloc && ! defined _STDLIB_H && (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) void *malloc (YYSIZE_T); /* INFRINGES ON USER NAME SPACE */ # endif # endif # ifndef YYFREE # define YYFREE free # if ! defined free && ! defined _STDLIB_H && (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) void free (void *); /* INFRINGES ON USER NAME SPACE */ # endif # endif # endif #endif /* ! defined yyoverflow || YYERROR_VERBOSE */ #if (! defined yyoverflow \ && (! defined __cplusplus \ || (defined YYSTYPE_IS_TRIVIAL && YYSTYPE_IS_TRIVIAL))) /* A type that is properly aligned for any stack member. */ union yyalloc { yytype_int16 yyss_alloc; YYSTYPE yyvs_alloc; }; /* The size of the maximum gap between one aligned stack and the next. */ # define YYSTACK_GAP_MAXIMUM (sizeof (union yyalloc) - 1) /* The size of an array large to enough to hold all stacks, each with N elements. */ # define YYSTACK_BYTES(N) \ ((N) * (sizeof (yytype_int16) + sizeof (YYSTYPE)) \ + YYSTACK_GAP_MAXIMUM) /* Copy COUNT objects from FROM to TO. The source and destination do not overlap. */ # ifndef YYCOPY # if defined __GNUC__ && 1 < __GNUC__ # define YYCOPY(To, From, Count) \ __builtin_memcpy (To, From, (Count) * sizeof (*(From))) # else # define YYCOPY(To, From, Count) \ do \ { \ YYSIZE_T yyi; \ for (yyi = 0; yyi < (Count); yyi++) \ (To)[yyi] = (From)[yyi]; \ } \ while (YYID (0)) # endif # endif /* Relocate STACK from its old location to the new one. The local variables YYSIZE and YYSTACKSIZE give the old and new number of elements in the stack, and YYPTR gives the new location of the stack. Advance YYPTR to a properly aligned location for the next stack. */ # define YYSTACK_RELOCATE(Stack_alloc, Stack) \ do \ { \ YYSIZE_T yynewbytes; \ YYCOPY (&yyptr->Stack_alloc, Stack, yysize); \ Stack = &yyptr->Stack_alloc; \ yynewbytes = yystacksize * sizeof (*Stack) + YYSTACK_GAP_MAXIMUM; \ yyptr += yynewbytes / sizeof (*yyptr); \ } \ while (YYID (0)) #endif /* YYFINAL -- State number of the termination state. */ #define YYFINAL 190 /* YYLAST -- Last index in YYTABLE. */ #define YYLAST 718 /* YYNTOKENS -- Number of terminals. */ #define YYNTOKENS 182 /* YYNNTS -- Number of nonterminals. */ #define YYNNTS 73 /* YYNRULES -- Number of rules. */ #define YYNRULES 263 /* YYNRULES -- Number of states. */ #define YYNSTATES 417 /* YYTRANSLATE(YYLEX) -- Bison symbol number corresponding to YYLEX. */ #define YYUNDEFTOK 2 #define YYMAXUTOK 431 #define YYTRANSLATE(YYX) \ ((unsigned int) (YYX) <= YYMAXUTOK ? yytranslate[YYX] : YYUNDEFTOK) /* YYTRANSLATE[YYLEX] -- Bison symbol number corresponding to YYLEX. */ static const yytype_uint8 yytranslate[] = { 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 178, 179, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 177, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 180, 2, 181, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176 }; #if YYDEBUG /* YYPRHS[YYN] -- Index of the first RHS symbol of rule number YYN in YYRHS. */ static const yytype_uint16 yyprhs[] = { 0, 0, 3, 5, 9, 12, 15, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 44, 47, 49, 51, 53, 55, 57, 59, 62, 65, 67, 70, 72, 74, 77, 79, 81, 84, 87, 90, 92, 94, 96, 98, 100, 103, 106, 109, 112, 114, 116, 118, 121, 124, 127, 130, 133, 136, 139, 142, 145, 148, 151, 153, 154, 157, 159, 162, 165, 168, 171, 174, 177, 180, 183, 186, 188, 191, 194, 197, 200, 203, 206, 209, 212, 215, 218, 221, 224, 227, 231, 234, 236, 238, 240, 242, 244, 246, 248, 250, 252, 255, 257, 260, 263, 265, 267, 269, 271, 273, 275, 277, 279, 281, 283, 285, 288, 291, 295, 301, 305, 310, 315, 319, 320, 323, 325, 327, 329, 331, 333, 335, 337, 339, 341, 343, 345, 347, 349, 351, 354, 356, 359, 362, 365, 368, 370, 373, 376, 379, 382, 385, 388, 391, 394, 398, 401, 403, 406, 409, 412, 415, 418, 421, 424, 427, 430, 433, 436, 438, 440, 442, 444, 446, 448, 450, 452, 455, 458, 460, 463, 466, 469, 472, 475, 478, 481, 483, 487, 489, 492, 495, 498, 501, 504, 507, 510, 513, 516, 519, 522, 525, 529, 532, 535, 537, 540, 541, 546, 550, 553, 555, 558, 561, 564, 566, 568, 572, 576, 578, 580, 582, 584, 586, 588, 590, 592, 594, 597, 599, 602, 604, 606, 608, 614, 617, 619, 622, 624, 626, 628, 630, 632, 634, 640, 642, 646, 649, 653, 657, 660, 662, 668, 673, 677, 680, 682, 689, 693, 696, 700, 704, 708, 712 }; /* YYRHS -- A `-1'-separated list of the rules' RHS. */ static const yytype_int16 yyrhs[] = { 183, 0, -1, 184, -1, 184, 185, 166, -1, 185, 166, -1, 1, 166, -1, -1, 186, -1, 192, -1, 194, -1, 195, -1, 202, -1, 208, -1, 199, -1, 215, -1, 218, -1, 221, -1, 224, -1, 243, -1, 187, 188, 190, -1, 187, 188, -1, 133, -1, 119, -1, 114, -1, 13, -1, 78, -1, 189, -1, 61, 143, -1, 63, 143, -1, 143, -1, 190, 191, -1, 191, -1, 7, -1, 12, 242, -1, 16, -1, 50, -1, 65, 58, -1, 91, 58, -1, 86, 58, -1, 104, -1, 121, -1, 122, -1, 152, -1, 162, -1, 154, 58, -1, 93, 58, -1, 158, 58, -1, 193, 188, -1, 156, -1, 157, -1, 14, -1, 79, 240, -1, 97, 240, -1, 8, 58, -1, 22, 58, -1, 23, 196, -1, 66, 143, -1, 67, 143, -1, 129, 58, -1, 131, 58, -1, 153, 236, -1, 110, 143, -1, 197, -1, -1, 197, 198, -1, 198, -1, 48, 143, -1, 51, 143, -1, 124, 143, -1, 126, 143, -1, 135, 143, -1, 27, 143, -1, 131, 58, -1, 150, 200, -1, 200, 201, -1, 201, -1, 19, 58, -1, 45, 58, -1, 21, 241, -1, 111, 58, -1, 112, 58, -1, 89, 242, -1, 84, 242, -1, 87, 242, -1, 82, 242, -1, 92, 58, -1, 11, 58, -1, 137, 203, -1, 139, 143, -1, 39, 204, 205, -1, 203, 204, -1, 204, -1, 20, -1, 24, -1, 76, -1, 115, -1, 127, -1, 144, -1, 148, -1, 123, -1, 205, 206, -1, 206, -1, 38, 143, -1, 155, 207, -1, 72, -1, 99, -1, 35, -1, 28, -1, 101, -1, 117, -1, 25, -1, 160, -1, 95, -1, 163, -1, 3, -1, 29, 211, -1, 96, 213, -1, 130, 188, 209, -1, 130, 189, 80, 189, 209, -1, 130, 26, 209, -1, 130, 61, 26, 209, -1, 130, 63, 26, 209, -1, 130, 136, 209, -1, -1, 209, 210, -1, 44, -1, 52, -1, 68, -1, 69, -1, 71, -1, 77, -1, 100, -1, 102, -1, 103, -1, 105, -1, 106, -1, 107, -1, 109, -1, 158, -1, 211, 212, -1, 212, -1, 9, 58, -1, 90, 58, -1, 94, 58, -1, 213, 214, -1, 214, -1, 53, 58, -1, 54, 58, -1, 55, 58, -1, 56, 58, -1, 81, 58, -1, 83, 58, -1, 85, 58, -1, 88, 58, -1, 47, 188, 216, -1, 216, 217, -1, 217, -1, 146, 242, -1, 147, 242, -1, 142, 58, -1, 128, 143, -1, 40, 241, -1, 41, 241, -1, 42, 241, -1, 43, 241, -1, 35, 219, -1, 28, 219, -1, 219, 220, -1, 220, -1, 6, -1, 10, -1, 17, -1, 64, -1, 94, -1, 108, -1, 138, -1, 149, 222, -1, 222, 223, -1, 223, -1, 5, 242, -1, 30, 242, -1, 46, 242, -1, 49, 242, -1, 113, 242, -1, 140, 242, -1, 141, 242, -1, 231, -1, 57, 143, 185, -1, 36, -1, 15, 242, -1, 18, 58, -1, 145, 242, -1, 32, 225, -1, 70, 143, -1, 118, 143, -1, 75, 143, -1, 74, 229, -1, 116, 239, -1, 132, 143, -1, 134, 226, -1, 151, 189, -1, 151, 189, 227, -1, 154, 235, -1, 125, 143, -1, 143, -1, 143, 31, -1, -1, 143, 177, 143, 26, -1, 143, 177, 143, -1, 227, 228, -1, 228, -1, 120, 58, -1, 59, 189, -1, 229, 230, -1, 230, -1, 143, -1, 232, 234, 233, -1, 232, 234, 143, -1, 59, -1, 98, -1, 4, -1, 60, -1, 62, -1, 161, -1, 73, -1, 52, -1, 33, -1, 235, 58, -1, 58, -1, 236, 237, -1, 237, -1, 58, -1, 238, -1, 178, 58, 34, 58, 179, -1, 239, 143, -1, 143, -1, 240, 188, -1, 188, -1, 58, -1, 152, -1, 37, -1, 58, -1, 31, -1, 244, 180, 245, 247, 181, -1, 167, -1, 245, 246, 166, -1, 246, 166, -1, 168, 177, 242, -1, 169, 177, 242, -1, 247, 248, -1, 248, -1, 250, 180, 249, 251, 181, -1, 170, 177, 242, 166, -1, 133, 177, 188, -1, 251, 252, -1, 252, -1, 171, 177, 242, 180, 253, 181, -1, 253, 254, 166, -1, 254, 166, -1, 172, 177, 242, -1, 173, 177, 242, -1, 174, 177, 242, -1, 175, 177, 242, -1, 176, 177, 242, -1 }; /* YYRLINE[YYN] -- source line where rule number YYN was defined. */ static const yytype_uint16 yyrline[] = { 0, 313, 313, 317, 318, 319, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 353, 359, 368, 369, 370, 371, 372, 376, 377, 378, 382, 386, 387, 391, 392, 393, 394, 395, 396, 397, 398, 399, 400, 401, 402, 403, 404, 405, 414, 422, 423, 433, 435, 437, 448, 450, 452, 457, 459, 461, 463, 465, 467, 472, 474, 478, 485, 495, 497, 499, 501, 503, 505, 507, 524, 529, 530, 534, 536, 538, 540, 542, 544, 546, 548, 550, 552, 554, 564, 566, 575, 583, 584, 588, 589, 590, 591, 592, 593, 594, 595, 599, 606, 616, 626, 635, 644, 653, 654, 658, 659, 660, 661, 662, 663, 664, 673, 677, 681, 686, 691, 696, 709, 722, 734, 735, 740, 741, 742, 743, 744, 745, 746, 747, 748, 749, 750, 751, 752, 753, 757, 759, 764, 765, 766, 770, 772, 777, 778, 779, 780, 781, 782, 783, 784, 792, 797, 799, 804, 805, 806, 807, 808, 809, 810, 811, 819, 821, 826, 833, 843, 844, 845, 846, 847, 848, 849, 865, 869, 870, 874, 875, 876, 877, 878, 879, 880, 889, 890, 906, 912, 914, 916, 918, 920, 923, 925, 936, 938, 940, 950, 952, 954, 956, 958, 963, 965, 969, 973, 975, 980, 982, 986, 987, 991, 992, 996, 1021, 1026, 1034, 1035, 1039, 1040, 1041, 1042, 1046, 1047, 1048, 1058, 1059, 1063, 1065, 1070, 1072, 1076, 1081, 1082, 1086, 1087, 1091, 1100, 1101, 1105, 1106, 1115, 1130, 1134, 1135, 1139, 1140, 1144, 1145, 1149, 1154, 1158, 1162, 1163, 1167, 1172, 1173, 1177, 1179, 1181, 1183, 1185 }; #endif #if YYDEBUG || YYERROR_VERBOSE || YYTOKEN_TABLE /* YYTNAME[SYMBOL-NUM] -- String name of the symbol SYMBOL-NUM. First, the terminals, then, starting at YYNTOKENS, nonterminals. */ static const char *const yytname[] = { "$end", "error", "$undefined", "T_Age", "T_All", "T_Allan", "T_Auth", "T_Autokey", "T_Automax", "T_Average", "T_Bclient", "T_Beacon", "T_Bias", "T_Broadcast", "T_Broadcastclient", "T_Broadcastdelay", "T_Burst", "T_Calibrate", "T_Calldelay", "T_Ceiling", "T_Clockstats", "T_Cohort", "T_ControlKey", "T_Crypto", "T_Cryptostats", "T_Day", "T_Default", "T_Digest", "T_Disable", "T_Discard", "T_Dispersion", "T_Double", "T_Driftfile", "T_Drop", "T_Ellipsis", "T_Enable", "T_End", "T_False", "T_File", "T_Filegen", "T_Flag1", "T_Flag2", "T_Flag3", "T_Flag4", "T_Flake", "T_Floor", "T_Freq", "T_Fudge", "T_Host", "T_Huffpuff", "T_Iburst", "T_Ident", "T_Ignore", "T_Incalloc", "T_Incmem", "T_Initalloc", "T_Initmem", "T_Includefile", "T_Integer", "T_Interface", "T_Ipv4", "T_Ipv4_flag", "T_Ipv6", "T_Ipv6_flag", "T_Kernel", "T_Key", "T_Keys", "T_Keysdir", "T_Kod", "T_Mssntp", "T_Leapfile", "T_Limited", "T_Link", "T_Listen", "T_Logconfig", "T_Logfile", "T_Loopstats", "T_Lowpriotrap", "T_Manycastclient", "T_Manycastserver", "T_Mask", "T_Maxage", "T_Maxclock", "T_Maxdepth", "T_Maxdist", "T_Maxmem", "T_Maxpoll", "T_Minclock", "T_Mindepth", "T_Mindist", "T_Minimum", "T_Minpoll", "T_Minsane", "T_Mode", "T_Monitor", "T_Month", "T_Mru", "T_Multicastclient", "T_Nic", "T_Nolink", "T_Nomodify", "T_None", "T_Nopeer", "T_Noquery", "T_Noselect", "T_Noserve", "T_Notrap", "T_Notrust", "T_Ntp", "T_Ntpport", "T_NtpSignDsocket", "T_Orphan", "T_Orphanwait", "T_Panic", "T_Peer", "T_Peerstats", "T_Phone", "T_Pid", "T_Pidfile", "T_Pool", "T_Port", "T_Preempt", "T_Prefer", "T_Protostats", "T_Pw", "T_Qos", "T_Randfile", "T_Rawstats", "T_Refid", "T_Requestkey", "T_Restrict", "T_Revoke", "T_Saveconfigdir", "T_Server", "T_Setvar", "T_Sign", "T_Source", "T_Statistics", "T_Stats", "T_Statsdir", "T_Step", "T_Stepout", "T_Stratum", "T_String", "T_Sysstats", "T_Tick", "T_Time1", "T_Time2", "T_Timingstats", "T_Tinker", "T_Tos", "T_Trap", "T_True", "T_Trustedkey", "T_Ttl", "T_Type", "T_Unconfig", "T_Unpeer", "T_Version", "T_WanderThreshold", "T_Week", "T_Wildcard", "T_Xleave", "T_Year", "T_Flag", "T_Void", "T_EOC", "T_Simulate", "T_Beep_Delay", "T_Sim_Duration", "T_Server_Offset", "T_Duration", "T_Freq_Offset", "T_Wander", "T_Jitter", "T_Prop_Delay", "T_Proc_Delay", "'='", "'('", "')'", "'{'", "'}'", "$accept", "configuration", "command_list", "command", "server_command", "client_type", "address", "ip_address", "option_list", "option", "unpeer_command", "unpeer_keyword", "other_mode_command", "authentication_command", "crypto_command_line", "crypto_command_list", "crypto_command", "orphan_mode_command", "tos_option_list", "tos_option", "monitoring_command", "stats_list", "stat", "filegen_option_list", "filegen_option", "filegen_type", "access_control_command", "ac_flag_list", "access_control_flag", "discard_option_list", "discard_option", "mru_option_list", "mru_option", "fudge_command", "fudge_factor_list", "fudge_factor", "system_option_command", "system_option_list", "system_option", "tinker_command", "tinker_option_list", "tinker_option", "miscellaneous_command", "drift_parm", "variable_assign", "trap_option_list", "trap_option", "log_config_list", "log_config_command", "interface_command", "interface_nic", "nic_rule_class", "nic_rule_action", "integer_list", "integer_list_range", "integer_list_range_elt", "integer_range", "string_list", "address_list", "boolean", "number", "simulate_command", "sim_conf_start", "sim_init_statement_list", "sim_init_statement", "sim_server_list", "sim_server", "sim_server_offset", "sim_server_name", "sim_act_list", "sim_act", "sim_act_stmt_list", "sim_act_stmt", 0 }; #endif # ifdef YYPRINT /* YYTOKNUM[YYLEX-NUM] -- Internal token number corresponding to token YYLEX-NUM. */ static const yytype_uint16 yytoknum[] = { 0, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 374, 375, 376, 377, 378, 379, 380, 381, 382, 383, 384, 385, 386, 387, 388, 389, 390, 391, 392, 393, 394, 395, 396, 397, 398, 399, 400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 418, 419, 420, 421, 422, 423, 424, 425, 426, 427, 428, 429, 430, 431, 61, 40, 41, 123, 125 }; # endif /* YYR1[YYN] -- Symbol number of symbol that rule YYN derives. */ static const yytype_uint8 yyr1[] = { 0, 182, 183, 184, 184, 184, 185, 185, 185, 185, 185, 185, 185, 185, 185, 185, 185, 185, 185, 186, 186, 187, 187, 187, 187, 187, 188, 188, 188, 189, 190, 190, 191, 191, 191, 191, 191, 191, 191, 191, 191, 191, 191, 191, 191, 191, 191, 192, 193, 193, 194, 194, 194, 195, 195, 195, 195, 195, 195, 195, 195, 195, 196, 196, 197, 197, 198, 198, 198, 198, 198, 198, 198, 199, 200, 200, 201, 201, 201, 201, 201, 201, 201, 201, 201, 201, 201, 202, 202, 202, 203, 203, 204, 204, 204, 204, 204, 204, 204, 204, 205, 205, 206, 206, 206, 206, 206, 206, 207, 207, 207, 207, 207, 207, 207, 208, 208, 208, 208, 208, 208, 208, 208, 209, 209, 210, 210, 210, 210, 210, 210, 210, 210, 210, 210, 210, 210, 210, 210, 211, 211, 212, 212, 212, 213, 213, 214, 214, 214, 214, 214, 214, 214, 214, 215, 216, 216, 217, 217, 217, 217, 217, 217, 217, 217, 218, 218, 219, 219, 220, 220, 220, 220, 220, 220, 220, 221, 222, 222, 223, 223, 223, 223, 223, 223, 223, 224, 224, 224, 224, 224, 224, 224, 224, 224, 224, 224, 224, 224, 224, 224, 224, 224, 224, 225, 225, 225, 226, 226, 227, 227, 228, 228, 229, 229, 230, 231, 231, 232, 232, 233, 233, 233, 233, 234, 234, 234, 235, 235, 236, 236, 237, 237, 238, 239, 239, 240, 240, 241, 241, 241, 242, 242, 243, 244, 245, 245, 246, 246, 247, 247, 248, 249, 250, 251, 251, 252, 253, 253, 254, 254, 254, 254, 254 }; /* YYR2[YYN] -- Number of symbols composing right hand side of rule YYN. */ static const yytype_uint8 yyr2[] = { 0, 2, 1, 3, 2, 2, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 2, 1, 1, 1, 1, 1, 1, 2, 2, 1, 2, 1, 1, 2, 1, 1, 2, 2, 2, 1, 1, 1, 1, 1, 2, 2, 2, 2, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 0, 2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 3, 5, 3, 4, 4, 3, 0, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2, 1, 3, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 2, 2, 1, 2, 0, 4, 3, 2, 1, 2, 2, 2, 1, 1, 3, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 2, 1, 1, 1, 5, 2, 1, 2, 1, 1, 1, 1, 1, 1, 5, 1, 3, 2, 3, 3, 2, 1, 5, 4, 3, 2, 1, 6, 3, 2, 3, 3, 3, 3, 3 }; /* YYDEFACT[STATE-NAME] -- Default rule to reduce with in state STATE-NUM when YYTABLE doesn't specify something else to do. Zero means the default is an error. */ static const yytype_uint16 yydefact[] = { 0, 0, 0, 24, 50, 0, 0, 0, 63, 0, 0, 206, 0, 188, 0, 0, 0, 218, 0, 0, 0, 0, 0, 25, 0, 0, 0, 219, 0, 23, 0, 0, 22, 0, 0, 0, 0, 0, 21, 0, 0, 0, 0, 0, 0, 0, 0, 0, 48, 49, 244, 0, 2, 0, 7, 0, 8, 0, 9, 10, 13, 11, 12, 14, 15, 16, 17, 186, 0, 18, 0, 5, 53, 242, 241, 189, 190, 54, 0, 0, 0, 0, 0, 0, 0, 55, 62, 65, 169, 170, 171, 172, 173, 174, 175, 166, 168, 0, 0, 0, 115, 140, 204, 192, 165, 92, 93, 94, 95, 99, 96, 97, 98, 0, 0, 0, 29, 0, 26, 6, 56, 57, 193, 215, 196, 214, 195, 237, 51, 0, 0, 0, 0, 0, 0, 0, 0, 116, 145, 52, 61, 235, 197, 194, 203, 58, 123, 0, 0, 123, 123, 26, 59, 198, 0, 199, 87, 91, 88, 191, 0, 0, 0, 0, 0, 0, 0, 176, 178, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 73, 75, 200, 231, 0, 60, 230, 232, 228, 202, 1, 0, 4, 20, 47, 226, 225, 224, 0, 0, 71, 66, 67, 68, 69, 72, 70, 64, 167, 141, 142, 143, 139, 205, 107, 106, 0, 104, 105, 0, 89, 101, 27, 28, 0, 0, 0, 0, 0, 0, 0, 0, 154, 156, 187, 213, 236, 146, 147, 148, 149, 150, 151, 152, 153, 144, 234, 119, 123, 123, 122, 117, 0, 0, 90, 179, 180, 181, 182, 183, 184, 185, 177, 86, 76, 240, 238, 239, 78, 77, 84, 82, 83, 81, 85, 79, 80, 74, 0, 0, 201, 210, 0, 229, 227, 3, 32, 0, 34, 35, 0, 0, 0, 0, 39, 40, 41, 42, 0, 0, 43, 19, 31, 220, 221, 222, 217, 223, 216, 0, 0, 0, 0, 102, 114, 110, 112, 108, 109, 111, 113, 103, 100, 161, 162, 163, 164, 160, 159, 157, 158, 155, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 124, 120, 121, 123, 208, 212, 211, 209, 0, 33, 36, 38, 37, 45, 44, 46, 30, 0, 0, 0, 0, 0, 250, 0, 246, 118, 207, 0, 247, 248, 0, 245, 243, 249, 0, 233, 253, 0, 0, 0, 0, 0, 255, 0, 0, 251, 254, 252, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 256, 0, 258, 259, 260, 261, 262, 263, 257 }; /* YYDEFGOTO[NTERM-NUM]. */ static const yytype_int16 yydefgoto[] = { -1, 51, 52, 53, 54, 55, 127, 118, 301, 302, 56, 57, 58, 59, 85, 86, 87, 60, 180, 181, 61, 156, 113, 220, 221, 321, 62, 247, 346, 100, 101, 137, 138, 63, 232, 233, 64, 95, 96, 65, 167, 168, 66, 103, 155, 280, 281, 124, 125, 67, 68, 308, 198, 189, 185, 186, 187, 142, 128, 268, 75, 69, 70, 311, 312, 367, 368, 384, 369, 387, 388, 401, 402 }; /* YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing STATE-NUM. */ #define YYPACT_NINF -148 static const yytype_int16 yypact[] = { 137, -132, -20, -148, -148, -7, -17, -16, 44, -1, 9, -99, -1, -148, 115, -46, -98, -148, -97, -95, -94, -90, -88, -148, -46, 144, -46, -148, -85, -148, -84, -78, -148, -77, -2, 13, 12, -71, -148, -70, 115, -66, -7, 1, 538, -65, -51, 32, -148, -148, -148, 91, 310, -68, -148, -46, -148, -46, -148, -148, -148, -148, -148, -148, -148, -148, -148, -148, -12, -148, -80, -148, -148, -148, -148, -148, -148, -148, -47, -39, -38, -28, -27, 55, -26, -148, 44, -148, -148, -148, -148, -148, -148, -148, -148, -1, -148, 71, 72, 86, 9, -148, 117, -148, -1, -148, -148, -148, -148, -148, -148, -148, -148, -15, 10, 14, -148, 39, -148, 457, -148, -148, -148, -148, -90, -148, -148, -148, -46, 96, 104, 105, 106, 119, 120, 122, 124, 144, -148, -46, -148, -148, 40, -148, -148, -148, -148, 3, 4, -148, -148, 107, -148, -148, 15, -148, 115, -148, -148, -148, -7, -7, -7, -7, -7, -7, -7, 1, -148, 132, 135, 6, 143, -7, -7, -7, -7, 147, 148, 150, 538, -148, -37, -148, 151, -51, -148, -148, -148, 152, -148, 29, -148, 530, -148, -148, -148, -148, 0, -142, -148, -148, -148, -148, -148, -148, -148, -148, -148, -148, -148, -148, -148, -148, -148, -148, 70, -148, -148, 11, -15, -148, -148, -148, 6, 6, 6, 6, 74, 156, -7, -7, 39, -148, -148, -148, -148, -148, -148, -148, -148, -148, -148, -148, -148, -148, -148, 560, -148, -148, 560, 560, -65, 81, -148, -148, -148, -148, -148, -148, -148, -148, -148, -148, -148, -148, -148, -148, -148, -148, -148, -148, -148, -148, -148, -148, -148, -148, -65, 168, -37, -148, 194, -148, -148, -148, -148, -7, -148, -148, 173, 178, 179, 181, -148, -148, -148, -148, 182, 183, -148, 530, -148, -148, -148, -148, -148, -148, -148, 66, 69, -100, 82, -148, -148, -148, -148, -148, -148, -148, -148, -148, -148, -148, -148, -148, -148, -148, -148, -148, -148, -148, -148, -148, -148, -148, -148, -148, -148, -148, -148, -148, -148, -148, -148, -148, -148, 560, 560, -148, 223, -148, -148, -148, 192, -148, -148, -148, -148, -148, -148, -148, -148, -7, -7, 75, 88, -114, -148, 77, -148, 560, -148, 79, -148, -148, -46, -148, -148, -148, 90, -148, -148, 84, 93, -7, 95, -146, -148, 99, -7, -148, -148, -148, 97, 47, 98, 101, 102, 103, 108, -87, 118, -7, -7, -7, -7, -7, -148, 123, -148, -148, -148, -148, -148, -148, -148 }; /* YYPGOTO[NTERM-NUM]. */ static const yytype_int16 yypgoto[] = { -148, -148, -148, -44, -148, -148, -3, -34, -148, -18, -148, -148, -148, -148, -148, -148, 187, -148, -148, 112, -148, -148, -30, -148, 61, -148, -148, -147, -148, -148, 195, -148, 159, -148, -148, 65, -148, 286, -67, -148, -148, 133, -148, -148, -148, -148, 19, -148, 177, -148, -148, -148, -148, -148, -148, 121, -148, -148, 276, -116, -42, -148, -148, -148, -6, -148, -60, -148, -148, -148, -79, -148, -92 }; /* YYTABLE[YYPACT[STATE-NUM]]. What to do in state STATE-NUM. If positive, shift that token. If negative, reduce the rule which number is the opposite. If zero, do what YYDEFACT says. If YYTABLE_NINF, syntax error. */ #define YYTABLE_NINF -7 static const yytype_int16 yytable[] = { 159, 151, 250, 251, 303, 88, 160, 183, 191, 89, 157, 182, 117, 214, 314, 114, 90, 115, 97, 365, 215, 195, 278, 216, 73, 386, 309, 310, 208, 248, 249, 161, 150, 365, 71, 391, 315, 208, 72, 146, 196, 76, 77, 265, 102, 119, 120, 162, 121, 122, 163, 74, 193, 123, 194, 126, 145, 217, 140, 141, 304, 197, 305, 91, 266, 143, 144, 378, 309, 310, 152, 78, 153, 154, 147, 234, 148, 158, 116, 224, 225, 226, 227, 279, 218, 396, 397, 398, 399, 400, 188, 190, 79, 92, 408, 80, 200, 116, 192, 98, 199, 347, 348, 99, 201, 202, 316, 93, 323, 324, 325, 326, 317, 205, 164, 203, 204, 206, 255, 256, 257, 258, 259, 260, 261, 236, 254, 184, 318, 209, 210, 270, 271, 272, 273, 105, 236, 94, 1, 106, 219, 165, 166, 306, 211, 2, 222, 223, 213, 149, 3, 4, 5, 222, 237, 6, 116, 223, 267, 7, 8, 307, 238, 239, 240, 9, 10, 228, 81, 11, 82, 319, 12, 13, 320, 83, 14, 241, 242, 84, 243, 229, 244, 246, 15, 230, 231, 252, 329, 330, 263, 107, 253, 264, 16, 285, 17, 129, 130, 131, 132, 269, 371, 18, 19, 274, 275, 20, 276, 282, 284, 21, 22, 313, 328, 23, 24, 327, 349, 396, 397, 398, 399, 400, 350, 133, 352, 134, 354, 135, 108, 356, 136, 25, 26, 27, 357, 358, 109, 359, 360, 361, 110, 363, 351, 355, 364, 28, 370, 372, 373, 29, 376, 30, 377, 31, 32, 380, 381, 111, 383, 385, 33, 112, 386, 393, 34, 35, 36, 37, 38, 39, 390, 207, 40, 403, 41, 395, 404, 405, 406, 322, 42, 362, 410, 407, 43, 44, 45, 416, 46, 47, 277, 48, 49, 212, 245, 331, 104, 353, 262, 235, 139, -6, 50, 366, 283, 379, 392, 409, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 374, 375, 3, 4, 5, 0, 0, 6, 0, 0, 0, 7, 8, 0, 0, 0, 0, 9, 10, 0, 0, 11, 389, 0, 12, 13, 0, 394, 14, 0, 0, 0, 0, 0, 0, 0, 15, 0, 0, 0, 411, 412, 413, 414, 415, 0, 16, 0, 17, 0, 0, 0, 382, 0, 0, 18, 19, 0, 0, 20, 0, 0, 0, 21, 22, 0, 0, 23, 24, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 25, 26, 27, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 28, 0, 0, 0, 29, 0, 30, 0, 31, 32, 0, 0, 0, 0, 0, 33, 0, 0, 0, 34, 35, 36, 37, 38, 39, 0, 0, 40, 0, 41, 0, 0, 0, 0, 0, 42, 0, 0, 0, 43, 44, 45, 0, 46, 47, 2, 48, 49, 0, 0, 3, 4, 5, 0, 0, 6, -6, 50, 0, 7, 8, 0, 0, 0, 0, 9, 10, 0, 0, 11, 0, 0, 12, 13, 0, 0, 14, 0, 0, 0, 0, 0, 0, 0, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 0, 17, 0, 0, 0, 0, 0, 0, 18, 19, 0, 0, 20, 0, 0, 0, 21, 22, 0, 0, 23, 24, 286, 0, 0, 0, 0, 287, 0, 0, 0, 288, 0, 0, 169, 0, 0, 0, 25, 26, 27, 0, 170, 0, 171, 0, 0, 0, 0, 0, 0, 0, 28, 0, 0, 0, 29, 0, 30, 0, 31, 32, 0, 0, 0, 289, 0, 33, 172, 0, 0, 34, 35, 36, 37, 38, 39, 0, 0, 40, 290, 41, 0, 0, 0, 0, 0, 42, 0, 332, 0, 43, 44, 45, 0, 46, 47, 333, 48, 49, 0, 291, 0, 0, 0, 173, 292, 174, 293, 50, 175, 0, 176, 334, 335, 177, 336, 0, 0, 294, 0, 0, 337, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 178, 179, 295, 296, 0, 0, 0, 0, 0, 0, 0, 338, 0, 339, 340, 0, 341, 342, 343, 0, 344, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 297, 0, 298, 0, 0, 0, 299, 0, 0, 0, 300, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 345 }; static const yytype_int16 yycheck[] = { 42, 35, 149, 150, 4, 6, 5, 58, 52, 10, 40, 45, 15, 28, 3, 61, 17, 63, 9, 133, 35, 33, 59, 38, 31, 171, 168, 169, 95, 26, 26, 30, 35, 133, 166, 181, 25, 104, 58, 26, 52, 58, 58, 37, 143, 143, 143, 46, 143, 143, 49, 58, 55, 143, 57, 143, 58, 72, 143, 143, 60, 73, 62, 64, 58, 143, 143, 181, 168, 169, 58, 27, 143, 143, 61, 119, 63, 143, 143, 40, 41, 42, 43, 120, 99, 172, 173, 174, 175, 176, 58, 0, 48, 94, 181, 51, 143, 143, 166, 90, 180, 248, 249, 94, 143, 143, 95, 108, 224, 225, 226, 227, 101, 58, 113, 143, 143, 143, 160, 161, 162, 163, 164, 165, 166, 128, 156, 178, 117, 58, 58, 173, 174, 175, 176, 20, 139, 138, 1, 24, 155, 140, 141, 143, 58, 8, 143, 143, 31, 136, 13, 14, 15, 143, 58, 18, 143, 143, 152, 22, 23, 161, 58, 58, 58, 28, 29, 128, 124, 32, 126, 160, 35, 36, 163, 131, 39, 58, 58, 135, 58, 142, 58, 143, 47, 146, 147, 80, 230, 231, 58, 76, 177, 58, 57, 166, 59, 53, 54, 55, 56, 58, 349, 66, 67, 58, 58, 70, 58, 58, 58, 74, 75, 143, 58, 78, 79, 143, 252, 172, 173, 174, 175, 176, 143, 81, 58, 83, 34, 85, 115, 58, 88, 96, 97, 98, 58, 58, 123, 58, 58, 58, 127, 177, 278, 287, 177, 110, 166, 26, 58, 114, 177, 116, 166, 118, 119, 180, 179, 144, 170, 177, 125, 148, 171, 166, 129, 130, 131, 132, 133, 134, 177, 86, 137, 177, 139, 180, 177, 177, 177, 220, 145, 301, 166, 177, 149, 150, 151, 166, 153, 154, 180, 156, 157, 100, 137, 232, 12, 280, 167, 124, 26, 166, 167, 311, 185, 367, 387, 401, -1, -1, -1, -1, -1, -1, -1, -1, 8, -1, -1, 363, 364, 13, 14, 15, -1, -1, 18, -1, -1, -1, 22, 23, -1, -1, -1, -1, 28, 29, -1, -1, 32, 385, -1, 35, 36, -1, 390, 39, -1, -1, -1, -1, -1, -1, -1, 47, -1, -1, -1, 403, 404, 405, 406, 407, -1, 57, -1, 59, -1, -1, -1, 376, -1, -1, 66, 67, -1, -1, 70, -1, -1, -1, 74, 75, -1, -1, 78, 79, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 96, 97, 98, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 110, -1, -1, -1, 114, -1, 116, -1, 118, 119, -1, -1, -1, -1, -1, 125, -1, -1, -1, 129, 130, 131, 132, 133, 134, -1, -1, 137, -1, 139, -1, -1, -1, -1, -1, 145, -1, -1, -1, 149, 150, 151, -1, 153, 154, 8, 156, 157, -1, -1, 13, 14, 15, -1, -1, 18, 166, 167, -1, 22, 23, -1, -1, -1, -1, 28, 29, -1, -1, 32, -1, -1, 35, 36, -1, -1, 39, -1, -1, -1, -1, -1, -1, -1, 47, -1, -1, -1, -1, -1, -1, -1, -1, -1, 57, -1, 59, -1, -1, -1, -1, -1, -1, 66, 67, -1, -1, 70, -1, -1, -1, 74, 75, -1, -1, 78, 79, 7, -1, -1, -1, -1, 12, -1, -1, -1, 16, -1, -1, 11, -1, -1, -1, 96, 97, 98, -1, 19, -1, 21, -1, -1, -1, -1, -1, -1, -1, 110, -1, -1, -1, 114, -1, 116, -1, 118, 119, -1, -1, -1, 50, -1, 125, 45, -1, -1, 129, 130, 131, 132, 133, 134, -1, -1, 137, 65, 139, -1, -1, -1, -1, -1, 145, -1, 44, -1, 149, 150, 151, -1, 153, 154, 52, 156, 157, -1, 86, -1, -1, -1, 82, 91, 84, 93, 167, 87, -1, 89, 68, 69, 92, 71, -1, -1, 104, -1, -1, 77, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 111, 112, 121, 122, -1, -1, -1, -1, -1, -1, -1, 100, -1, 102, 103, -1, 105, 106, 107, -1, 109, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 152, -1, 154, -1, -1, -1, 158, -1, -1, -1, 162, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 158 }; /* YYSTOS[STATE-NUM] -- The (internal number of the) accessing symbol of state STATE-NUM. */ static const yytype_uint8 yystos[] = { 0, 1, 8, 13, 14, 15, 18, 22, 23, 28, 29, 32, 35, 36, 39, 47, 57, 59, 66, 67, 70, 74, 75, 78, 79, 96, 97, 98, 110, 114, 116, 118, 119, 125, 129, 130, 131, 132, 133, 134, 137, 139, 145, 149, 150, 151, 153, 154, 156, 157, 167, 183, 184, 185, 186, 187, 192, 193, 194, 195, 199, 202, 208, 215, 218, 221, 224, 231, 232, 243, 244, 166, 58, 31, 58, 242, 58, 58, 27, 48, 51, 124, 126, 131, 135, 196, 197, 198, 6, 10, 17, 64, 94, 108, 138, 219, 220, 9, 90, 94, 211, 212, 143, 225, 219, 20, 24, 76, 115, 123, 127, 144, 148, 204, 61, 63, 143, 188, 189, 143, 143, 143, 143, 143, 229, 230, 143, 188, 240, 53, 54, 55, 56, 81, 83, 85, 88, 213, 214, 240, 143, 143, 239, 143, 143, 58, 26, 61, 63, 136, 188, 189, 58, 143, 143, 226, 203, 204, 143, 242, 5, 30, 46, 49, 113, 140, 141, 222, 223, 11, 19, 21, 45, 82, 84, 87, 89, 92, 111, 112, 200, 201, 189, 58, 178, 236, 237, 238, 58, 235, 0, 185, 166, 188, 188, 33, 52, 73, 234, 180, 143, 143, 143, 143, 143, 58, 143, 198, 220, 58, 58, 58, 212, 31, 28, 35, 38, 72, 99, 155, 205, 206, 143, 143, 40, 41, 42, 43, 128, 142, 146, 147, 216, 217, 185, 230, 188, 58, 58, 58, 58, 58, 58, 58, 58, 214, 143, 209, 26, 26, 209, 209, 80, 177, 204, 242, 242, 242, 242, 242, 242, 242, 223, 58, 58, 37, 58, 152, 241, 58, 242, 242, 242, 242, 58, 58, 58, 201, 59, 120, 227, 228, 58, 237, 58, 166, 7, 12, 16, 50, 65, 86, 91, 93, 104, 121, 122, 152, 154, 158, 162, 190, 191, 4, 60, 62, 143, 161, 233, 168, 169, 245, 246, 143, 3, 25, 95, 101, 117, 160, 163, 207, 206, 241, 241, 241, 241, 143, 58, 242, 242, 217, 44, 52, 68, 69, 71, 77, 100, 102, 103, 105, 106, 107, 109, 158, 210, 209, 209, 189, 143, 189, 58, 228, 34, 242, 58, 58, 58, 58, 58, 58, 191, 177, 177, 133, 246, 247, 248, 250, 166, 209, 26, 58, 242, 242, 177, 166, 181, 248, 180, 179, 188, 170, 249, 177, 171, 251, 252, 242, 177, 181, 252, 166, 242, 180, 172, 173, 174, 175, 176, 253, 254, 177, 177, 177, 177, 177, 181, 254, 166, 242, 242, 242, 242, 242, 166 }; #define yyerrok (yyerrstatus = 0) #define yyclearin (yychar = YYEMPTY) #define YYEMPTY (-2) #define YYEOF 0 #define YYACCEPT goto yyacceptlab #define YYABORT goto yyabortlab #define YYERROR goto yyerrorlab /* Like YYERROR except do call yyerror. This remains here temporarily to ease the transition to the new meaning of YYERROR, for GCC. Once GCC version 2 has supplanted version 1, this can go. */ #define YYFAIL goto yyerrlab #define YYRECOVERING() (!!yyerrstatus) #define YYBACKUP(Token, Value) \ do \ if (yychar == YYEMPTY && yylen == 1) \ { \ yychar = (Token); \ yylval = (Value); \ yytoken = YYTRANSLATE (yychar); \ YYPOPSTACK (1); \ goto yybackup; \ } \ else \ { \ yyerror (YY_("syntax error: cannot back up")); \ YYERROR; \ } \ while (YYID (0)) #define YYTERROR 1 #define YYERRCODE 256 /* YYLLOC_DEFAULT -- Set CURRENT to span from RHS[1] to RHS[N]. If N is 0, then set CURRENT to the empty location which ends the previous symbol: RHS[0] (always defined). */ #define YYRHSLOC(Rhs, K) ((Rhs)[K]) #ifndef YYLLOC_DEFAULT # define YYLLOC_DEFAULT(Current, Rhs, N) \ do \ if (YYID (N)) \ { \ (Current).first_line = YYRHSLOC (Rhs, 1).first_line; \ (Current).first_column = YYRHSLOC (Rhs, 1).first_column; \ (Current).last_line = YYRHSLOC (Rhs, N).last_line; \ (Current).last_column = YYRHSLOC (Rhs, N).last_column; \ } \ else \ { \ (Current).first_line = (Current).last_line = \ YYRHSLOC (Rhs, 0).last_line; \ (Current).first_column = (Current).last_column = \ YYRHSLOC (Rhs, 0).last_column; \ } \ while (YYID (0)) #endif /* YY_LOCATION_PRINT -- Print the location on the stream. This macro was not mandated originally: define only if we know we won't break user code: when these are the locations we know. */ #ifndef YY_LOCATION_PRINT # if YYLTYPE_IS_TRIVIAL # define YY_LOCATION_PRINT(File, Loc) \ fprintf (File, "%d.%d-%d.%d", \ (Loc).first_line, (Loc).first_column, \ (Loc).last_line, (Loc).last_column) # else # define YY_LOCATION_PRINT(File, Loc) ((void) 0) # endif #endif /* YYLEX -- calling `yylex' with the right arguments. */ #ifdef YYLEX_PARAM # define YYLEX yylex (YYLEX_PARAM) #else # define YYLEX yylex () #endif /* Enable debugging if requested. */ #if YYDEBUG # ifndef YYFPRINTF # include <stdio.h> /* INFRINGES ON USER NAME SPACE */ # define YYFPRINTF fprintf # endif # define YYDPRINTF(Args) \ do { \ if (yydebug) \ YYFPRINTF Args; \ } while (YYID (0)) # define YY_SYMBOL_PRINT(Title, Type, Value, Location) \ do { \ if (yydebug) \ { \ YYFPRINTF (stderr, "%s ", Title); \ yy_symbol_print (stderr, \ Type, Value); \ YYFPRINTF (stderr, "\n"); \ } \ } while (YYID (0)) /*--------------------------------. | Print this symbol on YYOUTPUT. | `--------------------------------*/ /*ARGSUSED*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yy_symbol_value_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep) #else static void yy_symbol_value_print (yyoutput, yytype, yyvaluep) FILE *yyoutput; int yytype; YYSTYPE const * const yyvaluep; #endif { if (!yyvaluep) return; # ifdef YYPRINT if (yytype < YYNTOKENS) YYPRINT (yyoutput, yytoknum[yytype], *yyvaluep); # else YYUSE (yyoutput); # endif switch (yytype) { default: break; } } /*--------------------------------. | Print this symbol on YYOUTPUT. | `--------------------------------*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yy_symbol_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep) #else static void yy_symbol_print (yyoutput, yytype, yyvaluep) FILE *yyoutput; int yytype; YYSTYPE const * const yyvaluep; #endif { if (yytype < YYNTOKENS) YYFPRINTF (yyoutput, "token %s (", yytname[yytype]); else YYFPRINTF (yyoutput, "nterm %s (", yytname[yytype]); yy_symbol_value_print (yyoutput, yytype, yyvaluep); YYFPRINTF (yyoutput, ")"); } /*------------------------------------------------------------------. | yy_stack_print -- Print the state stack from its BOTTOM up to its | | TOP (included). | `------------------------------------------------------------------*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yy_stack_print (yytype_int16 *yybottom, yytype_int16 *yytop) #else static void yy_stack_print (yybottom, yytop) yytype_int16 *yybottom; yytype_int16 *yytop; #endif { YYFPRINTF (stderr, "Stack now"); for (; yybottom <= yytop; yybottom++) { int yybot = *yybottom; YYFPRINTF (stderr, " %d", yybot); } YYFPRINTF (stderr, "\n"); } # define YY_STACK_PRINT(Bottom, Top) \ do { \ if (yydebug) \ yy_stack_print ((Bottom), (Top)); \ } while (YYID (0)) /*------------------------------------------------. | Report that the YYRULE is going to be reduced. | `------------------------------------------------*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yy_reduce_print (YYSTYPE *yyvsp, int yyrule) #else static void yy_reduce_print (yyvsp, yyrule) YYSTYPE *yyvsp; int yyrule; #endif { int yynrhs = yyr2[yyrule]; int yyi; unsigned long int yylno = yyrline[yyrule]; YYFPRINTF (stderr, "Reducing stack by rule %d (line %lu):\n", yyrule - 1, yylno); /* The symbols being reduced. */ for (yyi = 0; yyi < yynrhs; yyi++) { YYFPRINTF (stderr, " $%d = ", yyi + 1); yy_symbol_print (stderr, yyrhs[yyprhs[yyrule] + yyi], &(yyvsp[(yyi + 1) - (yynrhs)]) ); YYFPRINTF (stderr, "\n"); } } # define YY_REDUCE_PRINT(Rule) \ do { \ if (yydebug) \ yy_reduce_print (yyvsp, Rule); \ } while (YYID (0)) /* Nonzero means print parse trace. It is left uninitialized so that multiple parsers can coexist. */ int yydebug; #else /* !YYDEBUG */ # define YYDPRINTF(Args) # define YY_SYMBOL_PRINT(Title, Type, Value, Location) # define YY_STACK_PRINT(Bottom, Top) # define YY_REDUCE_PRINT(Rule) #endif /* !YYDEBUG */ /* YYINITDEPTH -- initial size of the parser's stacks. */ #ifndef YYINITDEPTH # define YYINITDEPTH 200 #endif /* YYMAXDEPTH -- maximum size the stacks can grow to (effective only if the built-in stack extension method is used). Do not make this value too large; the results are undefined if YYSTACK_ALLOC_MAXIMUM < YYSTACK_BYTES (YYMAXDEPTH) evaluated with infinite-precision integer arithmetic. */ #ifndef YYMAXDEPTH # define YYMAXDEPTH 10000 #endif #if YYERROR_VERBOSE # ifndef yystrlen # if defined __GLIBC__ && defined _STRING_H # define yystrlen strlen # else /* Return the length of YYSTR. */ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static YYSIZE_T yystrlen (const char *yystr) #else static YYSIZE_T yystrlen (yystr) const char *yystr; #endif { YYSIZE_T yylen; for (yylen = 0; yystr[yylen]; yylen++) continue; return yylen; } # endif # endif # ifndef yystpcpy # if defined __GLIBC__ && defined _STRING_H && defined _GNU_SOURCE # define yystpcpy stpcpy # else /* Copy YYSRC to YYDEST, returning the address of the terminating '\0' in YYDEST. */ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static char * yystpcpy (char *yydest, const char *yysrc) #else static char * yystpcpy (yydest, yysrc) char *yydest; const char *yysrc; #endif { char *yyd = yydest; const char *yys = yysrc; while ((*yyd++ = *yys++) != '\0') continue; return yyd - 1; } # endif # endif # ifndef yytnamerr /* Copy to YYRES the contents of YYSTR after stripping away unnecessary quotes and backslashes, so that it's suitable for yyerror. The heuristic is that double-quoting is unnecessary unless the string contains an apostrophe, a comma, or backslash (other than backslash-backslash). YYSTR is taken from yytname. If YYRES is null, do not copy; instead, return the length of what the result would have been. */ static YYSIZE_T yytnamerr (char *yyres, const char *yystr) { if (*yystr == '"') { YYSIZE_T yyn = 0; char const *yyp = yystr; for (;;) switch (*++yyp) { case '\'': case ',': goto do_not_strip_quotes; case '\\': if (*++yyp != '\\') goto do_not_strip_quotes; /* Fall through. */ default: if (yyres) yyres[yyn] = *yyp; yyn++; break; case '"': if (yyres) yyres[yyn] = '\0'; return yyn; } do_not_strip_quotes: ; } if (! yyres) return yystrlen (yystr); return yystpcpy (yyres, yystr) - yyres; } # endif /* Copy into YYRESULT an error message about the unexpected token YYCHAR while in state YYSTATE. Return the number of bytes copied, including the terminating null byte. If YYRESULT is null, do not copy anything; just return the number of bytes that would be copied. As a special case, return 0 if an ordinary "syntax error" message will do. Return YYSIZE_MAXIMUM if overflow occurs during size calculation. */ static YYSIZE_T yysyntax_error (char *yyresult, int yystate, int yychar) { int yyn = yypact[yystate]; if (! (YYPACT_NINF < yyn && yyn <= YYLAST)) return 0; else { int yytype = YYTRANSLATE (yychar); YYSIZE_T yysize0 = yytnamerr (0, yytname[yytype]); YYSIZE_T yysize = yysize0; YYSIZE_T yysize1; int yysize_overflow = 0; enum { YYERROR_VERBOSE_ARGS_MAXIMUM = 5 }; char const *yyarg[YYERROR_VERBOSE_ARGS_MAXIMUM]; int yyx; # if 0 /* This is so xgettext sees the translatable formats that are constructed on the fly. */ YY_("syntax error, unexpected %s"); YY_("syntax error, unexpected %s, expecting %s"); YY_("syntax error, unexpected %s, expecting %s or %s"); YY_("syntax error, unexpected %s, expecting %s or %s or %s"); YY_("syntax error, unexpected %s, expecting %s or %s or %s or %s"); # endif char *yyfmt; char const *yyf; static char const yyunexpected[] = "syntax error, unexpected %s"; static char const yyexpecting[] = ", expecting %s"; static char const yyor[] = " or %s"; char yyformat[sizeof yyunexpected + sizeof yyexpecting - 1 + ((YYERROR_VERBOSE_ARGS_MAXIMUM - 2) * (sizeof yyor - 1))]; char const *yyprefix = yyexpecting; /* Start YYX at -YYN if negative to avoid negative indexes in YYCHECK. */ int yyxbegin = yyn < 0 ? -yyn : 0; /* Stay within bounds of both yycheck and yytname. */ int yychecklim = YYLAST - yyn + 1; int yyxend = yychecklim < YYNTOKENS ? yychecklim : YYNTOKENS; int yycount = 1; yyarg[0] = yytname[yytype]; yyfmt = yystpcpy (yyformat, yyunexpected); for (yyx = yyxbegin; yyx < yyxend; ++yyx) if (yycheck[yyx + yyn] == yyx && yyx != YYTERROR) { if (yycount == YYERROR_VERBOSE_ARGS_MAXIMUM) { yycount = 1; yysize = yysize0; yyformat[sizeof yyunexpected - 1] = '\0'; break; } yyarg[yycount++] = yytname[yyx]; yysize1 = yysize + yytnamerr (0, yytname[yyx]); yysize_overflow |= (yysize1 < yysize); yysize = yysize1; yyfmt = yystpcpy (yyfmt, yyprefix); yyprefix = yyor; } yyf = YY_(yyformat); yysize1 = yysize + yystrlen (yyf); yysize_overflow |= (yysize1 < yysize); yysize = yysize1; if (yysize_overflow) return YYSIZE_MAXIMUM; if (yyresult) { /* Avoid sprintf, as that infringes on the user's name space. Don't have undefined behavior even if the translation produced a string with the wrong number of "%s"s. */ char *yyp = yyresult; int yyi = 0; while ((*yyp = *yyf) != '\0') { if (*yyp == '%' && yyf[1] == 's' && yyi < yycount) { yyp += yytnamerr (yyp, yyarg[yyi++]); yyf += 2; } else { yyp++; yyf++; } } } return yysize; } } #endif /* YYERROR_VERBOSE */ /*-----------------------------------------------. | Release the memory associated to this symbol. | `-----------------------------------------------*/ /*ARGSUSED*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yydestruct (const char *yymsg, int yytype, YYSTYPE *yyvaluep) #else static void yydestruct (yymsg, yytype, yyvaluep) const char *yymsg; int yytype; YYSTYPE *yyvaluep; #endif { YYUSE (yyvaluep); if (!yymsg) yymsg = "Deleting"; YY_SYMBOL_PRINT (yymsg, yytype, yyvaluep, yylocationp); switch (yytype) { default: break; } } /* Prevent warnings from -Wmissing-prototypes. */ #ifdef YYPARSE_PARAM #if defined __STDC__ || defined __cplusplus int yyparse (void *YYPARSE_PARAM); #else int yyparse (); #endif #else /* ! YYPARSE_PARAM */ #if defined __STDC__ || defined __cplusplus int yyparse (void); #else int yyparse (); #endif #endif /* ! YYPARSE_PARAM */ /* The lookahead symbol. */ int yychar; /* The semantic value of the lookahead symbol. */ YYSTYPE yylval; /* Number of syntax errors so far. */ int yynerrs; /*-------------------------. | yyparse or yypush_parse. | `-------------------------*/ #ifdef YYPARSE_PARAM #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) int yyparse (void *YYPARSE_PARAM) #else int yyparse (YYPARSE_PARAM) void *YYPARSE_PARAM; #endif #else /* ! YYPARSE_PARAM */ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) int yyparse (void) #else int yyparse () #endif #endif { int yystate; /* Number of tokens to shift before error messages enabled. */ int yyerrstatus; /* The stacks and their tools: `yyss': related to states. `yyvs': related to semantic values. Refer to the stacks thru separate pointers, to allow yyoverflow to reallocate them elsewhere. */ /* The state stack. */ yytype_int16 yyssa[YYINITDEPTH]; yytype_int16 *yyss; yytype_int16 *yyssp; /* The semantic value stack. */ YYSTYPE yyvsa[YYINITDEPTH]; YYSTYPE *yyvs; YYSTYPE *yyvsp; YYSIZE_T yystacksize; int yyn; int yyresult; /* Lookahead token as an internal (translated) token number. */ int yytoken; /* The variables used to return semantic value and location from the action routines. */ YYSTYPE yyval; #if YYERROR_VERBOSE /* Buffer for error messages, and its allocated size. */ char yymsgbuf[128]; char *yymsg = yymsgbuf; YYSIZE_T yymsg_alloc = sizeof yymsgbuf; #endif #define YYPOPSTACK(N) (yyvsp -= (N), yyssp -= (N)) /* The number of symbols on the RHS of the reduced rule. Keep to zero when no symbol should be popped. */ int yylen = 0; yytoken = 0; yyss = yyssa; yyvs = yyvsa; yystacksize = YYINITDEPTH; YYDPRINTF ((stderr, "Starting parse\n")); yystate = 0; yyerrstatus = 0; yynerrs = 0; yychar = YYEMPTY; /* Cause a token to be read. */ /* Initialize stack pointers. Waste one element of value and location stack so that they stay on the same level as the state stack. The wasted elements are never initialized. */ yyssp = yyss; yyvsp = yyvs; goto yysetstate; /*------------------------------------------------------------. | yynewstate -- Push a new state, which is found in yystate. | `------------------------------------------------------------*/ yynewstate: /* In all cases, when you get here, the value and location stacks have just been pushed. So pushing a state here evens the stacks. */ yyssp++; yysetstate: *yyssp = yystate; if (yyss + yystacksize - 1 <= yyssp) { /* Get the current used size of the three stacks, in elements. */ YYSIZE_T yysize = yyssp - yyss + 1; #ifdef yyoverflow { /* Give user a chance to reallocate the stack. Use copies of these so that the &'s don't force the real ones into memory. */ YYSTYPE *yyvs1 = yyvs; yytype_int16 *yyss1 = yyss; /* Each stack pointer address is followed by the size of the data in use in that stack, in bytes. This used to be a conditional around just the two extra args, but that might be undefined if yyoverflow is a macro. */ yyoverflow (YY_("memory exhausted"), &yyss1, yysize * sizeof (*yyssp), &yyvs1, yysize * sizeof (*yyvsp), &yystacksize); yyss = yyss1; yyvs = yyvs1; } #else /* no yyoverflow */ # ifndef YYSTACK_RELOCATE goto yyexhaustedlab; # else /* Extend the stack our own way. */ if (YYMAXDEPTH <= yystacksize) goto yyexhaustedlab; yystacksize *= 2; if (YYMAXDEPTH < yystacksize) yystacksize = YYMAXDEPTH; { yytype_int16 *yyss1 = yyss; union yyalloc *yyptr = (union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize)); if (! yyptr) goto yyexhaustedlab; YYSTACK_RELOCATE (yyss_alloc, yyss); YYSTACK_RELOCATE (yyvs_alloc, yyvs); # undef YYSTACK_RELOCATE if (yyss1 != yyssa) YYSTACK_FREE (yyss1); } # endif #endif /* no yyoverflow */ yyssp = yyss + yysize - 1; yyvsp = yyvs + yysize - 1; YYDPRINTF ((stderr, "Stack size increased to %lu\n", (unsigned long int) yystacksize)); if (yyss + yystacksize - 1 <= yyssp) YYABORT; } YYDPRINTF ((stderr, "Entering state %d\n", yystate)); if (yystate == YYFINAL) YYACCEPT; goto yybackup; /*-----------. | yybackup. | `-----------*/ yybackup: /* Do appropriate processing given the current state. Read a lookahead token if we need one and don't already have one. */ /* First try to decide what to do without reference to lookahead token. */ yyn = yypact[yystate]; if (yyn == YYPACT_NINF) goto yydefault; /* Not known => get a lookahead token if don't already have one. */ /* YYCHAR is either YYEMPTY or YYEOF or a valid lookahead symbol. */ if (yychar == YYEMPTY) { YYDPRINTF ((stderr, "Reading a token: ")); yychar = YYLEX; } if (yychar <= YYEOF) { yychar = yytoken = YYEOF; YYDPRINTF ((stderr, "Now at end of input.\n")); } else { yytoken = YYTRANSLATE (yychar); YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc); } /* If the proper action on seeing token YYTOKEN is to reduce or to detect an error, take that action. */ yyn += yytoken; if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken) goto yydefault; yyn = yytable[yyn]; if (yyn <= 0) { if (yyn == 0 || yyn == YYTABLE_NINF) goto yyerrlab; yyn = -yyn; goto yyreduce; } /* Count tokens shifted since error; after three, turn off error status. */ if (yyerrstatus) yyerrstatus--; /* Shift the lookahead token. */ YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc); /* Discard the shifted token. */ yychar = YYEMPTY; yystate = yyn; *++yyvsp = yylval; goto yynewstate; /*-----------------------------------------------------------. | yydefault -- do the default action for the current state. | `-----------------------------------------------------------*/ yydefault: yyn = yydefact[yystate]; if (yyn == 0) goto yyerrlab; goto yyreduce; /*-----------------------------. | yyreduce -- Do a reduction. | `-----------------------------*/ yyreduce: /* yyn is the number of a rule to reduce with. */ yylen = yyr2[yyn]; /* If YYLEN is nonzero, implement the default value of the action: `$$ = $1'. Otherwise, the following line sets YYVAL to garbage. This behavior is undocumented and Bison users should not rely upon it. Assigning to YYVAL unconditionally makes the parser a bit smaller, and it avoids a GCC warning that YYVAL may be used uninitialized. */ yyval = yyvsp[1-yylen]; YY_REDUCE_PRINT (yyn); switch (yyn) { case 5: /* Line 1455 of yacc.c */ #line 320 "ntp_parser.y" { /* I will need to incorporate much more fine grained * error messages. The following should suffice for * the time being. */ msyslog(LOG_ERR, "syntax error in %s line %d, column %d", ip_file->fname, ip_file->err_line_no, ip_file->err_col_no); } break; case 19: /* Line 1455 of yacc.c */ #line 354 "ntp_parser.y" { struct peer_node *my_node = create_peer_node((yyvsp[(1) - (3)].Integer), (yyvsp[(2) - (3)].Address_node), (yyvsp[(3) - (3)].Queue)); if (my_node) enqueue(cfgt.peers, my_node); } break; case 20: /* Line 1455 of yacc.c */ #line 360 "ntp_parser.y" { struct peer_node *my_node = create_peer_node((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Address_node), NULL); if (my_node) enqueue(cfgt.peers, my_node); } break; case 27: /* Line 1455 of yacc.c */ #line 377 "ntp_parser.y" { (yyval.Address_node) = create_address_node((yyvsp[(2) - (2)].String), AF_INET); } break; case 28: /* Line 1455 of yacc.c */ #line 378 "ntp_parser.y" { (yyval.Address_node) = create_address_node((yyvsp[(2) - (2)].String), AF_INET6); } break; case 29: /* Line 1455 of yacc.c */ #line 382 "ntp_parser.y" { (yyval.Address_node) = create_address_node((yyvsp[(1) - (1)].String), 0); } break; case 30: /* Line 1455 of yacc.c */ #line 386 "ntp_parser.y" { (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), (yyvsp[(2) - (2)].Attr_val)); } break; case 31: /* Line 1455 of yacc.c */ #line 387 "ntp_parser.y" { (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (1)].Attr_val)); } break; case 32: /* Line 1455 of yacc.c */ #line 391 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); } break; case 33: /* Line 1455 of yacc.c */ #line 392 "ntp_parser.y" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Double)); } break; case 34: /* Line 1455 of yacc.c */ #line 393 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); } break; case 35: /* Line 1455 of yacc.c */ #line 394 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); } break; case 36: /* Line 1455 of yacc.c */ #line 395 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 37: /* Line 1455 of yacc.c */ #line 396 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 38: /* Line 1455 of yacc.c */ #line 397 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 39: /* Line 1455 of yacc.c */ #line 398 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); } break; case 40: /* Line 1455 of yacc.c */ #line 399 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); } break; case 41: /* Line 1455 of yacc.c */ #line 400 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); } break; case 42: /* Line 1455 of yacc.c */ #line 401 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); } break; case 43: /* Line 1455 of yacc.c */ #line 402 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); } break; case 44: /* Line 1455 of yacc.c */ #line 403 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 45: /* Line 1455 of yacc.c */ #line 404 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 46: /* Line 1455 of yacc.c */ #line 405 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 47: /* Line 1455 of yacc.c */ #line 415 "ntp_parser.y" { struct unpeer_node *my_node = create_unpeer_node((yyvsp[(2) - (2)].Address_node)); if (my_node) enqueue(cfgt.unpeers, my_node); } break; case 50: /* Line 1455 of yacc.c */ #line 434 "ntp_parser.y" { cfgt.broadcastclient = 1; } break; case 51: /* Line 1455 of yacc.c */ #line 436 "ntp_parser.y" { append_queue(cfgt.manycastserver, (yyvsp[(2) - (2)].Queue)); } break; case 52: /* Line 1455 of yacc.c */ #line 438 "ntp_parser.y" { append_queue(cfgt.multicastclient, (yyvsp[(2) - (2)].Queue)); } break; case 53: /* Line 1455 of yacc.c */ #line 449 "ntp_parser.y" { enqueue(cfgt.vars, create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer))); } break; case 54: /* Line 1455 of yacc.c */ #line 451 "ntp_parser.y" { cfgt.auth.control_key = (yyvsp[(2) - (2)].Integer); } break; case 55: /* Line 1455 of yacc.c */ #line 453 "ntp_parser.y" { cfgt.auth.cryptosw++; append_queue(cfgt.auth.crypto_cmd_list, (yyvsp[(2) - (2)].Queue)); } break; case 56: /* Line 1455 of yacc.c */ #line 458 "ntp_parser.y" { cfgt.auth.keys = (yyvsp[(2) - (2)].String); } break; case 57: /* Line 1455 of yacc.c */ #line 460 "ntp_parser.y" { cfgt.auth.keysdir = (yyvsp[(2) - (2)].String); } break; case 58: /* Line 1455 of yacc.c */ #line 462 "ntp_parser.y" { cfgt.auth.request_key = (yyvsp[(2) - (2)].Integer); } break; case 59: /* Line 1455 of yacc.c */ #line 464 "ntp_parser.y" { cfgt.auth.revoke = (yyvsp[(2) - (2)].Integer); } break; case 60: /* Line 1455 of yacc.c */ #line 466 "ntp_parser.y" { cfgt.auth.trusted_key_list = (yyvsp[(2) - (2)].Queue); } break; case 61: /* Line 1455 of yacc.c */ #line 468 "ntp_parser.y" { cfgt.auth.ntp_signd_socket = (yyvsp[(2) - (2)].String); } break; case 63: /* Line 1455 of yacc.c */ #line 474 "ntp_parser.y" { (yyval.Queue) = create_queue(); } break; case 64: /* Line 1455 of yacc.c */ #line 479 "ntp_parser.y" { if ((yyvsp[(2) - (2)].Attr_val) != NULL) (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), (yyvsp[(2) - (2)].Attr_val)); else (yyval.Queue) = (yyvsp[(1) - (2)].Queue); } break; case 65: /* Line 1455 of yacc.c */ #line 486 "ntp_parser.y" { if ((yyvsp[(1) - (1)].Attr_val) != NULL) (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (1)].Attr_val)); else (yyval.Queue) = create_queue(); } break; case 66: /* Line 1455 of yacc.c */ #line 496 "ntp_parser.y" { (yyval.Attr_val) = create_attr_sval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].String)); } break; case 67: /* Line 1455 of yacc.c */ #line 498 "ntp_parser.y" { (yyval.Attr_val) = create_attr_sval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].String)); } break; case 68: /* Line 1455 of yacc.c */ #line 500 "ntp_parser.y" { (yyval.Attr_val) = create_attr_sval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].String)); } break; case 69: /* Line 1455 of yacc.c */ #line 502 "ntp_parser.y" { (yyval.Attr_val) = create_attr_sval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].String)); } break; case 70: /* Line 1455 of yacc.c */ #line 504 "ntp_parser.y" { (yyval.Attr_val) = create_attr_sval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].String)); } break; case 71: /* Line 1455 of yacc.c */ #line 506 "ntp_parser.y" { (yyval.Attr_val) = create_attr_sval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].String)); } break; case 72: /* Line 1455 of yacc.c */ #line 508 "ntp_parser.y" { (yyval.Attr_val) = NULL; cfgt.auth.revoke = (yyvsp[(2) - (2)].Integer); msyslog(LOG_WARNING, "'crypto revoke %d' is deprecated, " "please use 'revoke %d' instead.", cfgt.auth.revoke, cfgt.auth.revoke); } break; case 73: /* Line 1455 of yacc.c */ #line 525 "ntp_parser.y" { append_queue(cfgt.orphan_cmds,(yyvsp[(2) - (2)].Queue)); } break; case 74: /* Line 1455 of yacc.c */ #line 529 "ntp_parser.y" { (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), (yyvsp[(2) - (2)].Attr_val)); } break; case 75: /* Line 1455 of yacc.c */ #line 530 "ntp_parser.y" { (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (1)].Attr_val)); } break; case 76: /* Line 1455 of yacc.c */ #line 535 "ntp_parser.y" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (double)(yyvsp[(2) - (2)].Integer)); } break; case 77: /* Line 1455 of yacc.c */ #line 537 "ntp_parser.y" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (double)(yyvsp[(2) - (2)].Integer)); } break; case 78: /* Line 1455 of yacc.c */ #line 539 "ntp_parser.y" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (double)(yyvsp[(2) - (2)].Integer)); } break; case 79: /* Line 1455 of yacc.c */ #line 541 "ntp_parser.y" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (double)(yyvsp[(2) - (2)].Integer)); } break; case 80: /* Line 1455 of yacc.c */ #line 543 "ntp_parser.y" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (double)(yyvsp[(2) - (2)].Integer)); } break; case 81: /* Line 1455 of yacc.c */ #line 545 "ntp_parser.y" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Double)); } break; case 82: /* Line 1455 of yacc.c */ #line 547 "ntp_parser.y" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Double)); } break; case 83: /* Line 1455 of yacc.c */ #line 549 "ntp_parser.y" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Double)); } break; case 84: /* Line 1455 of yacc.c */ #line 551 "ntp_parser.y" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Double)); } break; case 85: /* Line 1455 of yacc.c */ #line 553 "ntp_parser.y" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (double)(yyvsp[(2) - (2)].Integer)); } break; case 86: /* Line 1455 of yacc.c */ #line 555 "ntp_parser.y" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (double)(yyvsp[(2) - (2)].Integer)); } break; case 87: /* Line 1455 of yacc.c */ #line 565 "ntp_parser.y" { append_queue(cfgt.stats_list, (yyvsp[(2) - (2)].Queue)); } break; case 88: /* Line 1455 of yacc.c */ #line 567 "ntp_parser.y" { if (input_from_file) cfgt.stats_dir = (yyvsp[(2) - (2)].String); else { free((yyvsp[(2) - (2)].String)); yyerror("statsdir remote configuration ignored"); } } break; case 89: /* Line 1455 of yacc.c */ #line 576 "ntp_parser.y" { enqueue(cfgt.filegen_opts, create_filegen_node((yyvsp[(2) - (3)].Integer), (yyvsp[(3) - (3)].Queue))); } break; case 90: /* Line 1455 of yacc.c */ #line 583 "ntp_parser.y" { (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), create_ival((yyvsp[(2) - (2)].Integer))); } break; case 91: /* Line 1455 of yacc.c */ #line 584 "ntp_parser.y" { (yyval.Queue) = enqueue_in_new_queue(create_ival((yyvsp[(1) - (1)].Integer))); } break; case 100: /* Line 1455 of yacc.c */ #line 600 "ntp_parser.y" { if ((yyvsp[(2) - (2)].Attr_val) != NULL) (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), (yyvsp[(2) - (2)].Attr_val)); else (yyval.Queue) = (yyvsp[(1) - (2)].Queue); } break; case 101: /* Line 1455 of yacc.c */ #line 607 "ntp_parser.y" { if ((yyvsp[(1) - (1)].Attr_val) != NULL) (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (1)].Attr_val)); else (yyval.Queue) = create_queue(); } break; case 102: /* Line 1455 of yacc.c */ #line 617 "ntp_parser.y" { if (input_from_file) (yyval.Attr_val) = create_attr_sval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].String)); else { (yyval.Attr_val) = NULL; free((yyvsp[(2) - (2)].String)); yyerror("filegen file remote configuration ignored"); } } break; case 103: /* Line 1455 of yacc.c */ #line 627 "ntp_parser.y" { if (input_from_file) (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); else { (yyval.Attr_val) = NULL; yyerror("filegen type remote configuration ignored"); } } break; case 104: /* Line 1455 of yacc.c */ #line 636 "ntp_parser.y" { if (input_from_file) (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); else { (yyval.Attr_val) = NULL; yyerror("filegen link remote configuration ignored"); } } break; case 105: /* Line 1455 of yacc.c */ #line 645 "ntp_parser.y" { if (input_from_file) (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); else { (yyval.Attr_val) = NULL; yyerror("filegen nolink remote configuration ignored"); } } break; case 106: /* Line 1455 of yacc.c */ #line 653 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); } break; case 107: /* Line 1455 of yacc.c */ #line 654 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); } break; case 115: /* Line 1455 of yacc.c */ #line 674 "ntp_parser.y" { append_queue(cfgt.discard_opts, (yyvsp[(2) - (2)].Queue)); } break; case 116: /* Line 1455 of yacc.c */ #line 678 "ntp_parser.y" { append_queue(cfgt.mru_opts, (yyvsp[(2) - (2)].Queue)); } break; case 117: /* Line 1455 of yacc.c */ #line 682 "ntp_parser.y" { enqueue(cfgt.restrict_opts, create_restrict_node((yyvsp[(2) - (3)].Address_node), NULL, (yyvsp[(3) - (3)].Queue), ip_file->line_no)); } break; case 118: /* Line 1455 of yacc.c */ #line 687 "ntp_parser.y" { enqueue(cfgt.restrict_opts, create_restrict_node((yyvsp[(2) - (5)].Address_node), (yyvsp[(4) - (5)].Address_node), (yyvsp[(5) - (5)].Queue), ip_file->line_no)); } break; case 119: /* Line 1455 of yacc.c */ #line 692 "ntp_parser.y" { enqueue(cfgt.restrict_opts, create_restrict_node(NULL, NULL, (yyvsp[(3) - (3)].Queue), ip_file->line_no)); } break; case 120: /* Line 1455 of yacc.c */ #line 697 "ntp_parser.y" { enqueue(cfgt.restrict_opts, create_restrict_node( create_address_node( estrdup("0.0.0.0"), AF_INET), create_address_node( estrdup("0.0.0.0"), AF_INET), (yyvsp[(4) - (4)].Queue), ip_file->line_no)); } break; case 121: /* Line 1455 of yacc.c */ #line 710 "ntp_parser.y" { enqueue(cfgt.restrict_opts, create_restrict_node( create_address_node( estrdup("::"), AF_INET6), create_address_node( estrdup("::"), AF_INET6), (yyvsp[(4) - (4)].Queue), ip_file->line_no)); } break; case 122: /* Line 1455 of yacc.c */ #line 723 "ntp_parser.y" { enqueue(cfgt.restrict_opts, create_restrict_node( NULL, NULL, enqueue((yyvsp[(3) - (3)].Queue), create_ival((yyvsp[(2) - (3)].Integer))), ip_file->line_no)); } break; case 123: /* Line 1455 of yacc.c */ #line 734 "ntp_parser.y" { (yyval.Queue) = create_queue(); } break; case 124: /* Line 1455 of yacc.c */ #line 736 "ntp_parser.y" { (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), create_ival((yyvsp[(2) - (2)].Integer))); } break; case 139: /* Line 1455 of yacc.c */ #line 758 "ntp_parser.y" { (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), (yyvsp[(2) - (2)].Attr_val)); } break; case 140: /* Line 1455 of yacc.c */ #line 760 "ntp_parser.y" { (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (1)].Attr_val)); } break; case 141: /* Line 1455 of yacc.c */ #line 764 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 142: /* Line 1455 of yacc.c */ #line 765 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 143: /* Line 1455 of yacc.c */ #line 766 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 144: /* Line 1455 of yacc.c */ #line 771 "ntp_parser.y" { (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), (yyvsp[(2) - (2)].Attr_val)); } break; case 145: /* Line 1455 of yacc.c */ #line 773 "ntp_parser.y" { (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (1)].Attr_val)); } break; case 146: /* Line 1455 of yacc.c */ #line 777 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 147: /* Line 1455 of yacc.c */ #line 778 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 148: /* Line 1455 of yacc.c */ #line 779 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 149: /* Line 1455 of yacc.c */ #line 780 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 150: /* Line 1455 of yacc.c */ #line 781 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 151: /* Line 1455 of yacc.c */ #line 782 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 152: /* Line 1455 of yacc.c */ #line 783 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 153: /* Line 1455 of yacc.c */ #line 784 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 154: /* Line 1455 of yacc.c */ #line 793 "ntp_parser.y" { enqueue(cfgt.fudge, create_addr_opts_node((yyvsp[(2) - (3)].Address_node), (yyvsp[(3) - (3)].Queue))); } break; case 155: /* Line 1455 of yacc.c */ #line 798 "ntp_parser.y" { enqueue((yyvsp[(1) - (2)].Queue), (yyvsp[(2) - (2)].Attr_val)); } break; case 156: /* Line 1455 of yacc.c */ #line 800 "ntp_parser.y" { (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (1)].Attr_val)); } break; case 157: /* Line 1455 of yacc.c */ #line 804 "ntp_parser.y" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Double)); } break; case 158: /* Line 1455 of yacc.c */ #line 805 "ntp_parser.y" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Double)); } break; case 159: /* Line 1455 of yacc.c */ #line 806 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 160: /* Line 1455 of yacc.c */ #line 807 "ntp_parser.y" { (yyval.Attr_val) = create_attr_sval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].String)); } break; case 161: /* Line 1455 of yacc.c */ #line 808 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 162: /* Line 1455 of yacc.c */ #line 809 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 163: /* Line 1455 of yacc.c */ #line 810 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 164: /* Line 1455 of yacc.c */ #line 811 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 165: /* Line 1455 of yacc.c */ #line 820 "ntp_parser.y" { append_queue(cfgt.enable_opts, (yyvsp[(2) - (2)].Queue)); } break; case 166: /* Line 1455 of yacc.c */ #line 822 "ntp_parser.y" { append_queue(cfgt.disable_opts, (yyvsp[(2) - (2)].Queue)); } break; case 167: /* Line 1455 of yacc.c */ #line 827 "ntp_parser.y" { if ((yyvsp[(2) - (2)].Attr_val) != NULL) (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), (yyvsp[(2) - (2)].Attr_val)); else (yyval.Queue) = (yyvsp[(1) - (2)].Queue); } break; case 168: /* Line 1455 of yacc.c */ #line 834 "ntp_parser.y" { if ((yyvsp[(1) - (1)].Attr_val) != NULL) (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (1)].Attr_val)); else (yyval.Queue) = create_queue(); } break; case 169: /* Line 1455 of yacc.c */ #line 843 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); } break; case 170: /* Line 1455 of yacc.c */ #line 844 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); } break; case 171: /* Line 1455 of yacc.c */ #line 845 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); } break; case 172: /* Line 1455 of yacc.c */ #line 846 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); } break; case 173: /* Line 1455 of yacc.c */ #line 847 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); } break; case 174: /* Line 1455 of yacc.c */ #line 848 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); } break; case 175: /* Line 1455 of yacc.c */ #line 850 "ntp_parser.y" { if (input_from_file) (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); else { (yyval.Attr_val) = NULL; yyerror("enable/disable stats remote configuration ignored"); } } break; case 176: /* Line 1455 of yacc.c */ #line 865 "ntp_parser.y" { append_queue(cfgt.tinker, (yyvsp[(2) - (2)].Queue)); } break; case 177: /* Line 1455 of yacc.c */ #line 869 "ntp_parser.y" { (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), (yyvsp[(2) - (2)].Attr_val)); } break; case 178: /* Line 1455 of yacc.c */ #line 870 "ntp_parser.y" { (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (1)].Attr_val)); } break; case 179: /* Line 1455 of yacc.c */ #line 874 "ntp_parser.y" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Double)); } break; case 180: /* Line 1455 of yacc.c */ #line 875 "ntp_parser.y" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Double)); } break; case 181: /* Line 1455 of yacc.c */ #line 876 "ntp_parser.y" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Double)); } break; case 182: /* Line 1455 of yacc.c */ #line 877 "ntp_parser.y" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Double)); } break; case 183: /* Line 1455 of yacc.c */ #line 878 "ntp_parser.y" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Double)); } break; case 184: /* Line 1455 of yacc.c */ #line 879 "ntp_parser.y" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Double)); } break; case 185: /* Line 1455 of yacc.c */ #line 880 "ntp_parser.y" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Double)); } break; case 187: /* Line 1455 of yacc.c */ #line 891 "ntp_parser.y" { if (curr_include_level >= MAXINCLUDELEVEL) { fprintf(stderr, "getconfig: Maximum include file level exceeded.\n"); msyslog(LOG_ERR, "getconfig: Maximum include file level exceeded."); } else { fp[curr_include_level + 1] = F_OPEN(FindConfig((yyvsp[(2) - (3)].String)), "r"); if (fp[curr_include_level + 1] == NULL) { fprintf(stderr, "getconfig: Couldn't open <%s>\n", FindConfig((yyvsp[(2) - (3)].String))); msyslog(LOG_ERR, "getconfig: Couldn't open <%s>", FindConfig((yyvsp[(2) - (3)].String))); } else ip_file = fp[++curr_include_level]; } } break; case 188: /* Line 1455 of yacc.c */ #line 907 "ntp_parser.y" { while (curr_include_level != -1) FCLOSE(fp[curr_include_level--]); } break; case 189: /* Line 1455 of yacc.c */ #line 913 "ntp_parser.y" { enqueue(cfgt.vars, create_attr_dval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Double))); } break; case 190: /* Line 1455 of yacc.c */ #line 915 "ntp_parser.y" { enqueue(cfgt.vars, create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer))); } break; case 191: /* Line 1455 of yacc.c */ #line 917 "ntp_parser.y" { enqueue(cfgt.vars, create_attr_dval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Double))); } break; case 192: /* Line 1455 of yacc.c */ #line 919 "ntp_parser.y" { /* Null action, possibly all null parms */ } break; case 193: /* Line 1455 of yacc.c */ #line 921 "ntp_parser.y" { enqueue(cfgt.vars, create_attr_sval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].String))); } break; case 194: /* Line 1455 of yacc.c */ #line 924 "ntp_parser.y" { enqueue(cfgt.vars, create_attr_sval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].String))); } break; case 195: /* Line 1455 of yacc.c */ #line 926 "ntp_parser.y" { if (input_from_file) enqueue(cfgt.vars, create_attr_sval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].String))); else { free((yyvsp[(2) - (2)].String)); yyerror("logfile remote configuration ignored"); } } break; case 196: /* Line 1455 of yacc.c */ #line 937 "ntp_parser.y" { append_queue(cfgt.logconfig, (yyvsp[(2) - (2)].Queue)); } break; case 197: /* Line 1455 of yacc.c */ #line 939 "ntp_parser.y" { append_queue(cfgt.phone, (yyvsp[(2) - (2)].Queue)); } break; case 198: /* Line 1455 of yacc.c */ #line 941 "ntp_parser.y" { if (input_from_file) enqueue(cfgt.vars, create_attr_sval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].String))); else { free((yyvsp[(2) - (2)].String)); yyerror("saveconfigdir remote configuration ignored"); } } break; case 199: /* Line 1455 of yacc.c */ #line 951 "ntp_parser.y" { enqueue(cfgt.setvar, (yyvsp[(2) - (2)].Set_var)); } break; case 200: /* Line 1455 of yacc.c */ #line 953 "ntp_parser.y" { enqueue(cfgt.trap, create_addr_opts_node((yyvsp[(2) - (2)].Address_node), NULL)); } break; case 201: /* Line 1455 of yacc.c */ #line 955 "ntp_parser.y" { enqueue(cfgt.trap, create_addr_opts_node((yyvsp[(2) - (3)].Address_node), (yyvsp[(3) - (3)].Queue))); } break; case 202: /* Line 1455 of yacc.c */ #line 957 "ntp_parser.y" { append_queue(cfgt.ttl, (yyvsp[(2) - (2)].Queue)); } break; case 203: /* Line 1455 of yacc.c */ #line 959 "ntp_parser.y" { enqueue(cfgt.qos, create_attr_sval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].String))); } break; case 204: /* Line 1455 of yacc.c */ #line 964 "ntp_parser.y" { enqueue(cfgt.vars, create_attr_sval(T_Driftfile, (yyvsp[(1) - (1)].String))); } break; case 205: /* Line 1455 of yacc.c */ #line 966 "ntp_parser.y" { enqueue(cfgt.vars, create_attr_dval(T_WanderThreshold, (yyvsp[(2) - (2)].Double))); enqueue(cfgt.vars, create_attr_sval(T_Driftfile, (yyvsp[(1) - (2)].String))); } break; case 206: /* Line 1455 of yacc.c */ #line 969 "ntp_parser.y" { enqueue(cfgt.vars, create_attr_sval(T_Driftfile, "\0")); } break; case 207: /* Line 1455 of yacc.c */ #line 974 "ntp_parser.y" { (yyval.Set_var) = create_setvar_node((yyvsp[(1) - (4)].String), (yyvsp[(3) - (4)].String), (yyvsp[(4) - (4)].Integer)); } break; case 208: /* Line 1455 of yacc.c */ #line 976 "ntp_parser.y" { (yyval.Set_var) = create_setvar_node((yyvsp[(1) - (3)].String), (yyvsp[(3) - (3)].String), 0); } break; case 209: /* Line 1455 of yacc.c */ #line 981 "ntp_parser.y" { (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), (yyvsp[(2) - (2)].Attr_val)); } break; case 210: /* Line 1455 of yacc.c */ #line 982 "ntp_parser.y" { (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (1)].Attr_val)); } break; case 211: /* Line 1455 of yacc.c */ #line 986 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 212: /* Line 1455 of yacc.c */ #line 987 "ntp_parser.y" { (yyval.Attr_val) = create_attr_pval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Address_node)); } break; case 213: /* Line 1455 of yacc.c */ #line 991 "ntp_parser.y" { (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), (yyvsp[(2) - (2)].Attr_val)); } break; case 214: /* Line 1455 of yacc.c */ #line 992 "ntp_parser.y" { (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (1)].Attr_val)); } break; case 215: /* Line 1455 of yacc.c */ #line 997 "ntp_parser.y" { char prefix; char * type; switch ((yyvsp[(1) - (1)].String)[0]) { case '+': case '-': case '=': prefix = (yyvsp[(1) - (1)].String)[0]; type = (yyvsp[(1) - (1)].String) + 1; break; default: prefix = '='; type = (yyvsp[(1) - (1)].String); } (yyval.Attr_val) = create_attr_sval(prefix, estrdup(type)); YYFREE((yyvsp[(1) - (1)].String)); } break; case 216: /* Line 1455 of yacc.c */ #line 1022 "ntp_parser.y" { enqueue(cfgt.nic_rules, create_nic_rule_node((yyvsp[(3) - (3)].Integer), NULL, (yyvsp[(2) - (3)].Integer))); } break; case 217: /* Line 1455 of yacc.c */ #line 1027 "ntp_parser.y" { enqueue(cfgt.nic_rules, create_nic_rule_node(0, (yyvsp[(3) - (3)].String), (yyvsp[(2) - (3)].Integer))); } break; case 227: /* Line 1455 of yacc.c */ #line 1058 "ntp_parser.y" { (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), create_ival((yyvsp[(2) - (2)].Integer))); } break; case 228: /* Line 1455 of yacc.c */ #line 1059 "ntp_parser.y" { (yyval.Queue) = enqueue_in_new_queue(create_ival((yyvsp[(1) - (1)].Integer))); } break; case 229: /* Line 1455 of yacc.c */ #line 1064 "ntp_parser.y" { (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), (yyvsp[(2) - (2)].Attr_val)); } break; case 230: /* Line 1455 of yacc.c */ #line 1066 "ntp_parser.y" { (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (1)].Attr_val)); } break; case 231: /* Line 1455 of yacc.c */ #line 1071 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival('i', (yyvsp[(1) - (1)].Integer)); } break; case 233: /* Line 1455 of yacc.c */ #line 1077 "ntp_parser.y" { (yyval.Attr_val) = create_attr_shorts('-', (yyvsp[(2) - (5)].Integer), (yyvsp[(4) - (5)].Integer)); } break; case 234: /* Line 1455 of yacc.c */ #line 1081 "ntp_parser.y" { (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), create_pval((yyvsp[(2) - (2)].String))); } break; case 235: /* Line 1455 of yacc.c */ #line 1082 "ntp_parser.y" { (yyval.Queue) = enqueue_in_new_queue(create_pval((yyvsp[(1) - (1)].String))); } break; case 236: /* Line 1455 of yacc.c */ #line 1086 "ntp_parser.y" { (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), (yyvsp[(2) - (2)].Address_node)); } break; case 237: /* Line 1455 of yacc.c */ #line 1087 "ntp_parser.y" { (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (1)].Address_node)); } break; case 238: /* Line 1455 of yacc.c */ #line 1092 "ntp_parser.y" { if ((yyvsp[(1) - (1)].Integer) != 0 && (yyvsp[(1) - (1)].Integer) != 1) { yyerror("Integer value is not boolean (0 or 1). Assuming 1"); (yyval.Integer) = 1; } else (yyval.Integer) = (yyvsp[(1) - (1)].Integer); } break; case 239: /* Line 1455 of yacc.c */ #line 1100 "ntp_parser.y" { (yyval.Integer) = 1; } break; case 240: /* Line 1455 of yacc.c */ #line 1101 "ntp_parser.y" { (yyval.Integer) = 0; } break; case 241: /* Line 1455 of yacc.c */ #line 1105 "ntp_parser.y" { (yyval.Double) = (double)(yyvsp[(1) - (1)].Integer); } break; case 243: /* Line 1455 of yacc.c */ #line 1116 "ntp_parser.y" { cfgt.sim_details = create_sim_node((yyvsp[(3) - (5)].Queue), (yyvsp[(4) - (5)].Queue)); /* Reset the old_config_style variable */ old_config_style = 1; } break; case 244: /* Line 1455 of yacc.c */ #line 1130 "ntp_parser.y" { old_config_style = 0; } break; case 245: /* Line 1455 of yacc.c */ #line 1134 "ntp_parser.y" { (yyval.Queue) = enqueue((yyvsp[(1) - (3)].Queue), (yyvsp[(2) - (3)].Attr_val)); } break; case 246: /* Line 1455 of yacc.c */ #line 1135 "ntp_parser.y" { (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (2)].Attr_val)); } break; case 247: /* Line 1455 of yacc.c */ #line 1139 "ntp_parser.y" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (3)].Integer), (yyvsp[(3) - (3)].Double)); } break; case 248: /* Line 1455 of yacc.c */ #line 1140 "ntp_parser.y" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (3)].Integer), (yyvsp[(3) - (3)].Double)); } break; case 249: /* Line 1455 of yacc.c */ #line 1144 "ntp_parser.y" { (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), (yyvsp[(2) - (2)].Sim_server)); } break; case 250: /* Line 1455 of yacc.c */ #line 1145 "ntp_parser.y" { (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (1)].Sim_server)); } break; case 251: /* Line 1455 of yacc.c */ #line 1150 "ntp_parser.y" { (yyval.Sim_server) = create_sim_server((yyvsp[(1) - (5)].Address_node), (yyvsp[(3) - (5)].Double), (yyvsp[(4) - (5)].Queue)); } break; case 252: /* Line 1455 of yacc.c */ #line 1154 "ntp_parser.y" { (yyval.Double) = (yyvsp[(3) - (4)].Double); } break; case 253: /* Line 1455 of yacc.c */ #line 1158 "ntp_parser.y" { (yyval.Address_node) = (yyvsp[(3) - (3)].Address_node); } break; case 254: /* Line 1455 of yacc.c */ #line 1162 "ntp_parser.y" { (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), (yyvsp[(2) - (2)].Sim_script)); } break; case 255: /* Line 1455 of yacc.c */ #line 1163 "ntp_parser.y" { (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (1)].Sim_script)); } break; case 256: /* Line 1455 of yacc.c */ #line 1168 "ntp_parser.y" { (yyval.Sim_script) = create_sim_script_info((yyvsp[(3) - (6)].Double), (yyvsp[(5) - (6)].Queue)); } break; case 257: /* Line 1455 of yacc.c */ #line 1172 "ntp_parser.y" { (yyval.Queue) = enqueue((yyvsp[(1) - (3)].Queue), (yyvsp[(2) - (3)].Attr_val)); } break; case 258: /* Line 1455 of yacc.c */ #line 1173 "ntp_parser.y" { (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (2)].Attr_val)); } break; case 259: /* Line 1455 of yacc.c */ #line 1178 "ntp_parser.y" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (3)].Integer), (yyvsp[(3) - (3)].Double)); } break; case 260: /* Line 1455 of yacc.c */ #line 1180 "ntp_parser.y" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (3)].Integer), (yyvsp[(3) - (3)].Double)); } break; case 261: /* Line 1455 of yacc.c */ #line 1182 "ntp_parser.y" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (3)].Integer), (yyvsp[(3) - (3)].Double)); } break; case 262: /* Line 1455 of yacc.c */ #line 1184 "ntp_parser.y" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (3)].Integer), (yyvsp[(3) - (3)].Double)); } break; case 263: /* Line 1455 of yacc.c */ #line 1186 "ntp_parser.y" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (3)].Integer), (yyvsp[(3) - (3)].Double)); } break; /* Line 1455 of yacc.c */ #line 3836 "ntp_parser.c" default: break; } YY_SYMBOL_PRINT ("-> $$ =", yyr1[yyn], &yyval, &yyloc); YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); *++yyvsp = yyval; /* Now `shift' the result of the reduction. Determine what state that goes to, based on the state we popped back to and the rule number reduced by. */ yyn = yyr1[yyn]; yystate = yypgoto[yyn - YYNTOKENS] + *yyssp; if (0 <= yystate && yystate <= YYLAST && yycheck[yystate] == *yyssp) yystate = yytable[yystate]; else yystate = yydefgoto[yyn - YYNTOKENS]; goto yynewstate; /*------------------------------------. | yyerrlab -- here on detecting error | `------------------------------------*/ yyerrlab: /* If not already recovering from an error, report this error. */ if (!yyerrstatus) { ++yynerrs; #if ! YYERROR_VERBOSE yyerror (YY_("syntax error")); #else { YYSIZE_T yysize = yysyntax_error (0, yystate, yychar); if (yymsg_alloc < yysize && yymsg_alloc < YYSTACK_ALLOC_MAXIMUM) { YYSIZE_T yyalloc = 2 * yysize; if (! (yysize <= yyalloc && yyalloc <= YYSTACK_ALLOC_MAXIMUM)) yyalloc = YYSTACK_ALLOC_MAXIMUM; if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); yymsg = (char *) YYSTACK_ALLOC (yyalloc); if (yymsg) yymsg_alloc = yyalloc; else { yymsg = yymsgbuf; yymsg_alloc = sizeof yymsgbuf; } } if (0 < yysize && yysize <= yymsg_alloc) { (void) yysyntax_error (yymsg, yystate, yychar); yyerror (yymsg); } else { yyerror (YY_("syntax error")); if (yysize != 0) goto yyexhaustedlab; } } #endif } if (yyerrstatus == 3) { /* If just tried and failed to reuse lookahead token after an error, discard it. */ if (yychar <= YYEOF) { /* Return failure if at end of input. */ if (yychar == YYEOF) YYABORT; } else { yydestruct ("Error: discarding", yytoken, &yylval); yychar = YYEMPTY; } } /* Else will try to reuse lookahead token after shifting the error token. */ goto yyerrlab1; /*---------------------------------------------------. | yyerrorlab -- error raised explicitly by YYERROR. | `---------------------------------------------------*/ yyerrorlab: /* Pacify compilers like GCC when the user code never invokes YYERROR and the label yyerrorlab therefore never appears in user code. */ if (/*CONSTCOND*/ 0) goto yyerrorlab; /* Do not reclaim the symbols of the rule which action triggered this YYERROR. */ YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); yystate = *yyssp; goto yyerrlab1; /*-------------------------------------------------------------. | yyerrlab1 -- common code for both syntax error and YYERROR. | `-------------------------------------------------------------*/ yyerrlab1: yyerrstatus = 3; /* Each real token shifted decrements this. */ for (;;) { yyn = yypact[yystate]; if (yyn != YYPACT_NINF) { yyn += YYTERROR; if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYTERROR) { yyn = yytable[yyn]; if (0 < yyn) break; } } /* Pop the current state because it cannot handle the error token. */ if (yyssp == yyss) YYABORT; yydestruct ("Error: popping", yystos[yystate], yyvsp); YYPOPSTACK (1); yystate = *yyssp; YY_STACK_PRINT (yyss, yyssp); } *++yyvsp = yylval; /* Shift the error token. */ YY_SYMBOL_PRINT ("Shifting", yystos[yyn], yyvsp, yylsp); yystate = yyn; goto yynewstate; /*-------------------------------------. | yyacceptlab -- YYACCEPT comes here. | `-------------------------------------*/ yyacceptlab: yyresult = 0; goto yyreturn; /*-----------------------------------. | yyabortlab -- YYABORT comes here. | `-----------------------------------*/ yyabortlab: yyresult = 1; goto yyreturn; #if !defined(yyoverflow) || YYERROR_VERBOSE /*-------------------------------------------------. | yyexhaustedlab -- memory exhaustion comes here. | `-------------------------------------------------*/ yyexhaustedlab: yyerror (YY_("memory exhausted")); yyresult = 2; /* Fall through. */ #endif yyreturn: if (yychar != YYEMPTY) yydestruct ("Cleanup: discarding lookahead", yytoken, &yylval); /* Do not reclaim the symbols of the rule which action triggered this YYABORT or YYACCEPT. */ YYPOPSTACK (yylen); YY_STACK_PRINT (yyss, yyssp); while (yyssp != yyss) { yydestruct ("Cleanup: popping", yystos[*yyssp], yyvsp); YYPOPSTACK (1); } #ifndef yyoverflow if (yyss != yyssa) YYSTACK_FREE (yyss); #endif #if YYERROR_VERBOSE if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); #endif /* Make sure YYID is used. */ return YYID (yyresult); } /* Line 1675 of yacc.c */ #line 1190 "ntp_parser.y" void yyerror (char *msg) { int retval; ip_file->err_line_no = ip_file->prev_token_line_no; ip_file->err_col_no = ip_file->prev_token_col_no; msyslog(LOG_ERR, "line %d column %d %s", ip_file->err_line_no, ip_file->err_col_no, msg); if (!input_from_file) { /* Save the error message in the correct buffer */ retval = snprintf(remote_config.err_msg + remote_config.err_pos, MAXLINE - remote_config.err_pos, "column %d %s", ip_file->err_col_no, msg); /* Increment the value of err_pos */ if (retval > 0) remote_config.err_pos += retval; /* Increment the number of errors */ ++remote_config.no_errors; } } /* * token_name - convert T_ token integers to text * example: token_name(T_Server) returns "T_Server" */ const char * token_name( int token ) { return yytname[YYTRANSLATE(token)]; } /* Initial Testing function -- ignore int main(int argc, char *argv[]) { ip_file = FOPEN(argv[1], "r"); if (!ip_file) { fprintf(stderr, "ERROR!! Could not open file: %s\n", argv[1]); } key_scanner = create_keyword_scanner(keyword_list); print_keyword_scanner(key_scanner, 0); yyparse(); return 0; } */
./CrossVul/dataset_final_sorted/CWE-20/c/good_1657_1
crossvul-cpp_data_bad_2162_3
/* * Kernel-based Virtual Machine driver for Linux * * This module enables machines with Intel VT-x extensions to run virtual * machines without emulation or binary translation. * * Copyright (C) 2006 Qumranet, Inc. * Copyright 2010 Red Hat, Inc. and/or its affiliates. * * Authors: * Avi Kivity <avi@qumranet.com> * Yaniv Kamay <yaniv@qumranet.com> * * This work is licensed under the terms of the GNU GPL, version 2. See * the COPYING file in the top-level directory. * */ #include "irq.h" #include "mmu.h" #include "cpuid.h" #include <linux/kvm_host.h> #include <linux/module.h> #include <linux/kernel.h> #include <linux/mm.h> #include <linux/highmem.h> #include <linux/sched.h> #include <linux/moduleparam.h> #include <linux/mod_devicetable.h> #include <linux/ftrace_event.h> #include <linux/slab.h> #include <linux/tboot.h> #include "kvm_cache_regs.h" #include "x86.h" #include <asm/io.h> #include <asm/desc.h> #include <asm/vmx.h> #include <asm/virtext.h> #include <asm/mce.h> #include <asm/i387.h> #include <asm/xcr.h> #include <asm/perf_event.h> #include <asm/kexec.h> #include "trace.h" #define __ex(x) __kvm_handle_fault_on_reboot(x) #define __ex_clear(x, reg) \ ____kvm_handle_fault_on_reboot(x, "xor " reg " , " reg) MODULE_AUTHOR("Qumranet"); MODULE_LICENSE("GPL"); static const struct x86_cpu_id vmx_cpu_id[] = { X86_FEATURE_MATCH(X86_FEATURE_VMX), {} }; MODULE_DEVICE_TABLE(x86cpu, vmx_cpu_id); static bool __read_mostly enable_vpid = 1; module_param_named(vpid, enable_vpid, bool, 0444); static bool __read_mostly flexpriority_enabled = 1; module_param_named(flexpriority, flexpriority_enabled, bool, S_IRUGO); static bool __read_mostly enable_ept = 1; module_param_named(ept, enable_ept, bool, S_IRUGO); static bool __read_mostly enable_unrestricted_guest = 1; module_param_named(unrestricted_guest, enable_unrestricted_guest, bool, S_IRUGO); static bool __read_mostly enable_ept_ad_bits = 1; module_param_named(eptad, enable_ept_ad_bits, bool, S_IRUGO); static bool __read_mostly emulate_invalid_guest_state = true; module_param(emulate_invalid_guest_state, bool, S_IRUGO); static bool __read_mostly vmm_exclusive = 1; module_param(vmm_exclusive, bool, S_IRUGO); static bool __read_mostly fasteoi = 1; module_param(fasteoi, bool, S_IRUGO); static bool __read_mostly enable_apicv = 1; module_param(enable_apicv, bool, S_IRUGO); static bool __read_mostly enable_shadow_vmcs = 1; module_param_named(enable_shadow_vmcs, enable_shadow_vmcs, bool, S_IRUGO); /* * If nested=1, nested virtualization is supported, i.e., guests may use * VMX and be a hypervisor for its own guests. If nested=0, guests may not * use VMX instructions. */ static bool __read_mostly nested = 0; module_param(nested, bool, S_IRUGO); #define KVM_GUEST_CR0_MASK (X86_CR0_NW | X86_CR0_CD) #define KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST (X86_CR0_WP | X86_CR0_NE) #define KVM_VM_CR0_ALWAYS_ON \ (KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST | X86_CR0_PG | X86_CR0_PE) #define KVM_CR4_GUEST_OWNED_BITS \ (X86_CR4_PVI | X86_CR4_DE | X86_CR4_PCE | X86_CR4_OSFXSR \ | X86_CR4_OSXMMEXCPT) #define KVM_PMODE_VM_CR4_ALWAYS_ON (X86_CR4_PAE | X86_CR4_VMXE) #define KVM_RMODE_VM_CR4_ALWAYS_ON (X86_CR4_VME | X86_CR4_PAE | X86_CR4_VMXE) #define RMODE_GUEST_OWNED_EFLAGS_BITS (~(X86_EFLAGS_IOPL | X86_EFLAGS_VM)) /* * These 2 parameters are used to config the controls for Pause-Loop Exiting: * ple_gap: upper bound on the amount of time between two successive * executions of PAUSE in a loop. Also indicate if ple enabled. * According to test, this time is usually smaller than 128 cycles. * ple_window: upper bound on the amount of time a guest is allowed to execute * in a PAUSE loop. Tests indicate that most spinlocks are held for * less than 2^12 cycles * Time is measured based on a counter that runs at the same rate as the TSC, * refer SDM volume 3b section 21.6.13 & 22.1.3. */ #define KVM_VMX_DEFAULT_PLE_GAP 128 #define KVM_VMX_DEFAULT_PLE_WINDOW 4096 static int ple_gap = KVM_VMX_DEFAULT_PLE_GAP; module_param(ple_gap, int, S_IRUGO); static int ple_window = KVM_VMX_DEFAULT_PLE_WINDOW; module_param(ple_window, int, S_IRUGO); extern const ulong vmx_return; #define NR_AUTOLOAD_MSRS 8 #define VMCS02_POOL_SIZE 1 struct vmcs { u32 revision_id; u32 abort; char data[0]; }; /* * Track a VMCS that may be loaded on a certain CPU. If it is (cpu!=-1), also * remember whether it was VMLAUNCHed, and maintain a linked list of all VMCSs * loaded on this CPU (so we can clear them if the CPU goes down). */ struct loaded_vmcs { struct vmcs *vmcs; int cpu; int launched; struct list_head loaded_vmcss_on_cpu_link; }; struct shared_msr_entry { unsigned index; u64 data; u64 mask; }; /* * struct vmcs12 describes the state that our guest hypervisor (L1) keeps for a * single nested guest (L2), hence the name vmcs12. Any VMX implementation has * a VMCS structure, and vmcs12 is our emulated VMX's VMCS. This structure is * stored in guest memory specified by VMPTRLD, but is opaque to the guest, * which must access it using VMREAD/VMWRITE/VMCLEAR instructions. * More than one of these structures may exist, if L1 runs multiple L2 guests. * nested_vmx_run() will use the data here to build a vmcs02: a VMCS for the * underlying hardware which will be used to run L2. * This structure is packed to ensure that its layout is identical across * machines (necessary for live migration). * If there are changes in this struct, VMCS12_REVISION must be changed. */ typedef u64 natural_width; struct __packed vmcs12 { /* According to the Intel spec, a VMCS region must start with the * following two fields. Then follow implementation-specific data. */ u32 revision_id; u32 abort; u32 launch_state; /* set to 0 by VMCLEAR, to 1 by VMLAUNCH */ u32 padding[7]; /* room for future expansion */ u64 io_bitmap_a; u64 io_bitmap_b; u64 msr_bitmap; u64 vm_exit_msr_store_addr; u64 vm_exit_msr_load_addr; u64 vm_entry_msr_load_addr; u64 tsc_offset; u64 virtual_apic_page_addr; u64 apic_access_addr; u64 ept_pointer; u64 guest_physical_address; u64 vmcs_link_pointer; u64 guest_ia32_debugctl; u64 guest_ia32_pat; u64 guest_ia32_efer; u64 guest_ia32_perf_global_ctrl; u64 guest_pdptr0; u64 guest_pdptr1; u64 guest_pdptr2; u64 guest_pdptr3; u64 host_ia32_pat; u64 host_ia32_efer; u64 host_ia32_perf_global_ctrl; u64 padding64[8]; /* room for future expansion */ /* * To allow migration of L1 (complete with its L2 guests) between * machines of different natural widths (32 or 64 bit), we cannot have * unsigned long fields with no explict size. We use u64 (aliased * natural_width) instead. Luckily, x86 is little-endian. */ natural_width cr0_guest_host_mask; natural_width cr4_guest_host_mask; natural_width cr0_read_shadow; natural_width cr4_read_shadow; natural_width cr3_target_value0; natural_width cr3_target_value1; natural_width cr3_target_value2; natural_width cr3_target_value3; natural_width exit_qualification; natural_width guest_linear_address; natural_width guest_cr0; natural_width guest_cr3; natural_width guest_cr4; natural_width guest_es_base; natural_width guest_cs_base; natural_width guest_ss_base; natural_width guest_ds_base; natural_width guest_fs_base; natural_width guest_gs_base; natural_width guest_ldtr_base; natural_width guest_tr_base; natural_width guest_gdtr_base; natural_width guest_idtr_base; natural_width guest_dr7; natural_width guest_rsp; natural_width guest_rip; natural_width guest_rflags; natural_width guest_pending_dbg_exceptions; natural_width guest_sysenter_esp; natural_width guest_sysenter_eip; natural_width host_cr0; natural_width host_cr3; natural_width host_cr4; natural_width host_fs_base; natural_width host_gs_base; natural_width host_tr_base; natural_width host_gdtr_base; natural_width host_idtr_base; natural_width host_ia32_sysenter_esp; natural_width host_ia32_sysenter_eip; natural_width host_rsp; natural_width host_rip; natural_width paddingl[8]; /* room for future expansion */ u32 pin_based_vm_exec_control; u32 cpu_based_vm_exec_control; u32 exception_bitmap; u32 page_fault_error_code_mask; u32 page_fault_error_code_match; u32 cr3_target_count; u32 vm_exit_controls; u32 vm_exit_msr_store_count; u32 vm_exit_msr_load_count; u32 vm_entry_controls; u32 vm_entry_msr_load_count; u32 vm_entry_intr_info_field; u32 vm_entry_exception_error_code; u32 vm_entry_instruction_len; u32 tpr_threshold; u32 secondary_vm_exec_control; u32 vm_instruction_error; u32 vm_exit_reason; u32 vm_exit_intr_info; u32 vm_exit_intr_error_code; u32 idt_vectoring_info_field; u32 idt_vectoring_error_code; u32 vm_exit_instruction_len; u32 vmx_instruction_info; u32 guest_es_limit; u32 guest_cs_limit; u32 guest_ss_limit; u32 guest_ds_limit; u32 guest_fs_limit; u32 guest_gs_limit; u32 guest_ldtr_limit; u32 guest_tr_limit; u32 guest_gdtr_limit; u32 guest_idtr_limit; u32 guest_es_ar_bytes; u32 guest_cs_ar_bytes; u32 guest_ss_ar_bytes; u32 guest_ds_ar_bytes; u32 guest_fs_ar_bytes; u32 guest_gs_ar_bytes; u32 guest_ldtr_ar_bytes; u32 guest_tr_ar_bytes; u32 guest_interruptibility_info; u32 guest_activity_state; u32 guest_sysenter_cs; u32 host_ia32_sysenter_cs; u32 vmx_preemption_timer_value; u32 padding32[7]; /* room for future expansion */ u16 virtual_processor_id; u16 guest_es_selector; u16 guest_cs_selector; u16 guest_ss_selector; u16 guest_ds_selector; u16 guest_fs_selector; u16 guest_gs_selector; u16 guest_ldtr_selector; u16 guest_tr_selector; u16 host_es_selector; u16 host_cs_selector; u16 host_ss_selector; u16 host_ds_selector; u16 host_fs_selector; u16 host_gs_selector; u16 host_tr_selector; }; /* * VMCS12_REVISION is an arbitrary id that should be changed if the content or * layout of struct vmcs12 is changed. MSR_IA32_VMX_BASIC returns this id, and * VMPTRLD verifies that the VMCS region that L1 is loading contains this id. */ #define VMCS12_REVISION 0x11e57ed0 /* * VMCS12_SIZE is the number of bytes L1 should allocate for the VMXON region * and any VMCS region. Although only sizeof(struct vmcs12) are used by the * current implementation, 4K are reserved to avoid future complications. */ #define VMCS12_SIZE 0x1000 /* Used to remember the last vmcs02 used for some recently used vmcs12s */ struct vmcs02_list { struct list_head list; gpa_t vmptr; struct loaded_vmcs vmcs02; }; /* * The nested_vmx structure is part of vcpu_vmx, and holds information we need * for correct emulation of VMX (i.e., nested VMX) on this vcpu. */ struct nested_vmx { /* Has the level1 guest done vmxon? */ bool vmxon; /* The guest-physical address of the current VMCS L1 keeps for L2 */ gpa_t current_vmptr; /* The host-usable pointer to the above */ struct page *current_vmcs12_page; struct vmcs12 *current_vmcs12; struct vmcs *current_shadow_vmcs; /* * Indicates if the shadow vmcs must be updated with the * data hold by vmcs12 */ bool sync_shadow_vmcs; /* vmcs02_list cache of VMCSs recently used to run L2 guests */ struct list_head vmcs02_pool; int vmcs02_num; u64 vmcs01_tsc_offset; /* L2 must run next, and mustn't decide to exit to L1. */ bool nested_run_pending; /* * Guest pages referred to in vmcs02 with host-physical pointers, so * we must keep them pinned while L2 runs. */ struct page *apic_access_page; u64 msr_ia32_feature_control; }; #define POSTED_INTR_ON 0 /* Posted-Interrupt Descriptor */ struct pi_desc { u32 pir[8]; /* Posted interrupt requested */ u32 control; /* bit 0 of control is outstanding notification bit */ u32 rsvd[7]; } __aligned(64); static bool pi_test_and_set_on(struct pi_desc *pi_desc) { return test_and_set_bit(POSTED_INTR_ON, (unsigned long *)&pi_desc->control); } static bool pi_test_and_clear_on(struct pi_desc *pi_desc) { return test_and_clear_bit(POSTED_INTR_ON, (unsigned long *)&pi_desc->control); } static int pi_test_and_set_pir(int vector, struct pi_desc *pi_desc) { return test_and_set_bit(vector, (unsigned long *)pi_desc->pir); } struct vcpu_vmx { struct kvm_vcpu vcpu; unsigned long host_rsp; u8 fail; u8 cpl; bool nmi_known_unmasked; u32 exit_intr_info; u32 idt_vectoring_info; ulong rflags; struct shared_msr_entry *guest_msrs; int nmsrs; int save_nmsrs; unsigned long host_idt_base; #ifdef CONFIG_X86_64 u64 msr_host_kernel_gs_base; u64 msr_guest_kernel_gs_base; #endif /* * loaded_vmcs points to the VMCS currently used in this vcpu. For a * non-nested (L1) guest, it always points to vmcs01. For a nested * guest (L2), it points to a different VMCS. */ struct loaded_vmcs vmcs01; struct loaded_vmcs *loaded_vmcs; bool __launched; /* temporary, used in vmx_vcpu_run */ struct msr_autoload { unsigned nr; struct vmx_msr_entry guest[NR_AUTOLOAD_MSRS]; struct vmx_msr_entry host[NR_AUTOLOAD_MSRS]; } msr_autoload; struct { int loaded; u16 fs_sel, gs_sel, ldt_sel; #ifdef CONFIG_X86_64 u16 ds_sel, es_sel; #endif int gs_ldt_reload_needed; int fs_reload_needed; } host_state; struct { int vm86_active; ulong save_rflags; struct kvm_segment segs[8]; } rmode; struct { u32 bitmask; /* 4 bits per segment (1 bit per field) */ struct kvm_save_segment { u16 selector; unsigned long base; u32 limit; u32 ar; } seg[8]; } segment_cache; int vpid; bool emulation_required; /* Support for vnmi-less CPUs */ int soft_vnmi_blocked; ktime_t entry_time; s64 vnmi_blocked_time; u32 exit_reason; bool rdtscp_enabled; /* Posted interrupt descriptor */ struct pi_desc pi_desc; /* Support for a guest hypervisor (nested VMX) */ struct nested_vmx nested; }; enum segment_cache_field { SEG_FIELD_SEL = 0, SEG_FIELD_BASE = 1, SEG_FIELD_LIMIT = 2, SEG_FIELD_AR = 3, SEG_FIELD_NR = 4 }; static inline struct vcpu_vmx *to_vmx(struct kvm_vcpu *vcpu) { return container_of(vcpu, struct vcpu_vmx, vcpu); } #define VMCS12_OFFSET(x) offsetof(struct vmcs12, x) #define FIELD(number, name) [number] = VMCS12_OFFSET(name) #define FIELD64(number, name) [number] = VMCS12_OFFSET(name), \ [number##_HIGH] = VMCS12_OFFSET(name)+4 static const unsigned long shadow_read_only_fields[] = { /* * We do NOT shadow fields that are modified when L0 * traps and emulates any vmx instruction (e.g. VMPTRLD, * VMXON...) executed by L1. * For example, VM_INSTRUCTION_ERROR is read * by L1 if a vmx instruction fails (part of the error path). * Note the code assumes this logic. If for some reason * we start shadowing these fields then we need to * force a shadow sync when L0 emulates vmx instructions * (e.g. force a sync if VM_INSTRUCTION_ERROR is modified * by nested_vmx_failValid) */ VM_EXIT_REASON, VM_EXIT_INTR_INFO, VM_EXIT_INSTRUCTION_LEN, IDT_VECTORING_INFO_FIELD, IDT_VECTORING_ERROR_CODE, VM_EXIT_INTR_ERROR_CODE, EXIT_QUALIFICATION, GUEST_LINEAR_ADDRESS, GUEST_PHYSICAL_ADDRESS }; static const int max_shadow_read_only_fields = ARRAY_SIZE(shadow_read_only_fields); static const unsigned long shadow_read_write_fields[] = { GUEST_RIP, GUEST_RSP, GUEST_CR0, GUEST_CR3, GUEST_CR4, GUEST_INTERRUPTIBILITY_INFO, GUEST_RFLAGS, GUEST_CS_SELECTOR, GUEST_CS_AR_BYTES, GUEST_CS_LIMIT, GUEST_CS_BASE, GUEST_ES_BASE, CR0_GUEST_HOST_MASK, CR0_READ_SHADOW, CR4_READ_SHADOW, TSC_OFFSET, EXCEPTION_BITMAP, CPU_BASED_VM_EXEC_CONTROL, VM_ENTRY_EXCEPTION_ERROR_CODE, VM_ENTRY_INTR_INFO_FIELD, VM_ENTRY_INSTRUCTION_LEN, VM_ENTRY_EXCEPTION_ERROR_CODE, HOST_FS_BASE, HOST_GS_BASE, HOST_FS_SELECTOR, HOST_GS_SELECTOR }; static const int max_shadow_read_write_fields = ARRAY_SIZE(shadow_read_write_fields); static const unsigned short vmcs_field_to_offset_table[] = { FIELD(VIRTUAL_PROCESSOR_ID, virtual_processor_id), FIELD(GUEST_ES_SELECTOR, guest_es_selector), FIELD(GUEST_CS_SELECTOR, guest_cs_selector), FIELD(GUEST_SS_SELECTOR, guest_ss_selector), FIELD(GUEST_DS_SELECTOR, guest_ds_selector), FIELD(GUEST_FS_SELECTOR, guest_fs_selector), FIELD(GUEST_GS_SELECTOR, guest_gs_selector), FIELD(GUEST_LDTR_SELECTOR, guest_ldtr_selector), FIELD(GUEST_TR_SELECTOR, guest_tr_selector), FIELD(HOST_ES_SELECTOR, host_es_selector), FIELD(HOST_CS_SELECTOR, host_cs_selector), FIELD(HOST_SS_SELECTOR, host_ss_selector), FIELD(HOST_DS_SELECTOR, host_ds_selector), FIELD(HOST_FS_SELECTOR, host_fs_selector), FIELD(HOST_GS_SELECTOR, host_gs_selector), FIELD(HOST_TR_SELECTOR, host_tr_selector), FIELD64(IO_BITMAP_A, io_bitmap_a), FIELD64(IO_BITMAP_B, io_bitmap_b), FIELD64(MSR_BITMAP, msr_bitmap), FIELD64(VM_EXIT_MSR_STORE_ADDR, vm_exit_msr_store_addr), FIELD64(VM_EXIT_MSR_LOAD_ADDR, vm_exit_msr_load_addr), FIELD64(VM_ENTRY_MSR_LOAD_ADDR, vm_entry_msr_load_addr), FIELD64(TSC_OFFSET, tsc_offset), FIELD64(VIRTUAL_APIC_PAGE_ADDR, virtual_apic_page_addr), FIELD64(APIC_ACCESS_ADDR, apic_access_addr), FIELD64(EPT_POINTER, ept_pointer), FIELD64(GUEST_PHYSICAL_ADDRESS, guest_physical_address), FIELD64(VMCS_LINK_POINTER, vmcs_link_pointer), FIELD64(GUEST_IA32_DEBUGCTL, guest_ia32_debugctl), FIELD64(GUEST_IA32_PAT, guest_ia32_pat), FIELD64(GUEST_IA32_EFER, guest_ia32_efer), FIELD64(GUEST_IA32_PERF_GLOBAL_CTRL, guest_ia32_perf_global_ctrl), FIELD64(GUEST_PDPTR0, guest_pdptr0), FIELD64(GUEST_PDPTR1, guest_pdptr1), FIELD64(GUEST_PDPTR2, guest_pdptr2), FIELD64(GUEST_PDPTR3, guest_pdptr3), FIELD64(HOST_IA32_PAT, host_ia32_pat), FIELD64(HOST_IA32_EFER, host_ia32_efer), FIELD64(HOST_IA32_PERF_GLOBAL_CTRL, host_ia32_perf_global_ctrl), FIELD(PIN_BASED_VM_EXEC_CONTROL, pin_based_vm_exec_control), FIELD(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control), FIELD(EXCEPTION_BITMAP, exception_bitmap), FIELD(PAGE_FAULT_ERROR_CODE_MASK, page_fault_error_code_mask), FIELD(PAGE_FAULT_ERROR_CODE_MATCH, page_fault_error_code_match), FIELD(CR3_TARGET_COUNT, cr3_target_count), FIELD(VM_EXIT_CONTROLS, vm_exit_controls), FIELD(VM_EXIT_MSR_STORE_COUNT, vm_exit_msr_store_count), FIELD(VM_EXIT_MSR_LOAD_COUNT, vm_exit_msr_load_count), FIELD(VM_ENTRY_CONTROLS, vm_entry_controls), FIELD(VM_ENTRY_MSR_LOAD_COUNT, vm_entry_msr_load_count), FIELD(VM_ENTRY_INTR_INFO_FIELD, vm_entry_intr_info_field), FIELD(VM_ENTRY_EXCEPTION_ERROR_CODE, vm_entry_exception_error_code), FIELD(VM_ENTRY_INSTRUCTION_LEN, vm_entry_instruction_len), FIELD(TPR_THRESHOLD, tpr_threshold), FIELD(SECONDARY_VM_EXEC_CONTROL, secondary_vm_exec_control), FIELD(VM_INSTRUCTION_ERROR, vm_instruction_error), FIELD(VM_EXIT_REASON, vm_exit_reason), FIELD(VM_EXIT_INTR_INFO, vm_exit_intr_info), FIELD(VM_EXIT_INTR_ERROR_CODE, vm_exit_intr_error_code), FIELD(IDT_VECTORING_INFO_FIELD, idt_vectoring_info_field), FIELD(IDT_VECTORING_ERROR_CODE, idt_vectoring_error_code), FIELD(VM_EXIT_INSTRUCTION_LEN, vm_exit_instruction_len), FIELD(VMX_INSTRUCTION_INFO, vmx_instruction_info), FIELD(GUEST_ES_LIMIT, guest_es_limit), FIELD(GUEST_CS_LIMIT, guest_cs_limit), FIELD(GUEST_SS_LIMIT, guest_ss_limit), FIELD(GUEST_DS_LIMIT, guest_ds_limit), FIELD(GUEST_FS_LIMIT, guest_fs_limit), FIELD(GUEST_GS_LIMIT, guest_gs_limit), FIELD(GUEST_LDTR_LIMIT, guest_ldtr_limit), FIELD(GUEST_TR_LIMIT, guest_tr_limit), FIELD(GUEST_GDTR_LIMIT, guest_gdtr_limit), FIELD(GUEST_IDTR_LIMIT, guest_idtr_limit), FIELD(GUEST_ES_AR_BYTES, guest_es_ar_bytes), FIELD(GUEST_CS_AR_BYTES, guest_cs_ar_bytes), FIELD(GUEST_SS_AR_BYTES, guest_ss_ar_bytes), FIELD(GUEST_DS_AR_BYTES, guest_ds_ar_bytes), FIELD(GUEST_FS_AR_BYTES, guest_fs_ar_bytes), FIELD(GUEST_GS_AR_BYTES, guest_gs_ar_bytes), FIELD(GUEST_LDTR_AR_BYTES, guest_ldtr_ar_bytes), FIELD(GUEST_TR_AR_BYTES, guest_tr_ar_bytes), FIELD(GUEST_INTERRUPTIBILITY_INFO, guest_interruptibility_info), FIELD(GUEST_ACTIVITY_STATE, guest_activity_state), FIELD(GUEST_SYSENTER_CS, guest_sysenter_cs), FIELD(HOST_IA32_SYSENTER_CS, host_ia32_sysenter_cs), FIELD(VMX_PREEMPTION_TIMER_VALUE, vmx_preemption_timer_value), FIELD(CR0_GUEST_HOST_MASK, cr0_guest_host_mask), FIELD(CR4_GUEST_HOST_MASK, cr4_guest_host_mask), FIELD(CR0_READ_SHADOW, cr0_read_shadow), FIELD(CR4_READ_SHADOW, cr4_read_shadow), FIELD(CR3_TARGET_VALUE0, cr3_target_value0), FIELD(CR3_TARGET_VALUE1, cr3_target_value1), FIELD(CR3_TARGET_VALUE2, cr3_target_value2), FIELD(CR3_TARGET_VALUE3, cr3_target_value3), FIELD(EXIT_QUALIFICATION, exit_qualification), FIELD(GUEST_LINEAR_ADDRESS, guest_linear_address), FIELD(GUEST_CR0, guest_cr0), FIELD(GUEST_CR3, guest_cr3), FIELD(GUEST_CR4, guest_cr4), FIELD(GUEST_ES_BASE, guest_es_base), FIELD(GUEST_CS_BASE, guest_cs_base), FIELD(GUEST_SS_BASE, guest_ss_base), FIELD(GUEST_DS_BASE, guest_ds_base), FIELD(GUEST_FS_BASE, guest_fs_base), FIELD(GUEST_GS_BASE, guest_gs_base), FIELD(GUEST_LDTR_BASE, guest_ldtr_base), FIELD(GUEST_TR_BASE, guest_tr_base), FIELD(GUEST_GDTR_BASE, guest_gdtr_base), FIELD(GUEST_IDTR_BASE, guest_idtr_base), FIELD(GUEST_DR7, guest_dr7), FIELD(GUEST_RSP, guest_rsp), FIELD(GUEST_RIP, guest_rip), FIELD(GUEST_RFLAGS, guest_rflags), FIELD(GUEST_PENDING_DBG_EXCEPTIONS, guest_pending_dbg_exceptions), FIELD(GUEST_SYSENTER_ESP, guest_sysenter_esp), FIELD(GUEST_SYSENTER_EIP, guest_sysenter_eip), FIELD(HOST_CR0, host_cr0), FIELD(HOST_CR3, host_cr3), FIELD(HOST_CR4, host_cr4), FIELD(HOST_FS_BASE, host_fs_base), FIELD(HOST_GS_BASE, host_gs_base), FIELD(HOST_TR_BASE, host_tr_base), FIELD(HOST_GDTR_BASE, host_gdtr_base), FIELD(HOST_IDTR_BASE, host_idtr_base), FIELD(HOST_IA32_SYSENTER_ESP, host_ia32_sysenter_esp), FIELD(HOST_IA32_SYSENTER_EIP, host_ia32_sysenter_eip), FIELD(HOST_RSP, host_rsp), FIELD(HOST_RIP, host_rip), }; static const int max_vmcs_field = ARRAY_SIZE(vmcs_field_to_offset_table); static inline short vmcs_field_to_offset(unsigned long field) { if (field >= max_vmcs_field || vmcs_field_to_offset_table[field] == 0) return -1; return vmcs_field_to_offset_table[field]; } static inline struct vmcs12 *get_vmcs12(struct kvm_vcpu *vcpu) { return to_vmx(vcpu)->nested.current_vmcs12; } static struct page *nested_get_page(struct kvm_vcpu *vcpu, gpa_t addr) { struct page *page = gfn_to_page(vcpu->kvm, addr >> PAGE_SHIFT); if (is_error_page(page)) return NULL; return page; } static void nested_release_page(struct page *page) { kvm_release_page_dirty(page); } static void nested_release_page_clean(struct page *page) { kvm_release_page_clean(page); } static u64 construct_eptp(unsigned long root_hpa); static void kvm_cpu_vmxon(u64 addr); static void kvm_cpu_vmxoff(void); static void vmx_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3); static int vmx_set_tss_addr(struct kvm *kvm, unsigned int addr); static void vmx_set_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var, int seg); static void vmx_get_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var, int seg); static bool guest_state_valid(struct kvm_vcpu *vcpu); static u32 vmx_segment_access_rights(struct kvm_segment *var); static void vmx_sync_pir_to_irr_dummy(struct kvm_vcpu *vcpu); static void copy_vmcs12_to_shadow(struct vcpu_vmx *vmx); static void copy_shadow_to_vmcs12(struct vcpu_vmx *vmx); static DEFINE_PER_CPU(struct vmcs *, vmxarea); static DEFINE_PER_CPU(struct vmcs *, current_vmcs); /* * We maintain a per-CPU linked-list of VMCS loaded on that CPU. This is needed * when a CPU is brought down, and we need to VMCLEAR all VMCSs loaded on it. */ static DEFINE_PER_CPU(struct list_head, loaded_vmcss_on_cpu); static DEFINE_PER_CPU(struct desc_ptr, host_gdt); static unsigned long *vmx_io_bitmap_a; static unsigned long *vmx_io_bitmap_b; static unsigned long *vmx_msr_bitmap_legacy; static unsigned long *vmx_msr_bitmap_longmode; static unsigned long *vmx_msr_bitmap_legacy_x2apic; static unsigned long *vmx_msr_bitmap_longmode_x2apic; static unsigned long *vmx_vmread_bitmap; static unsigned long *vmx_vmwrite_bitmap; static bool cpu_has_load_ia32_efer; static bool cpu_has_load_perf_global_ctrl; static DECLARE_BITMAP(vmx_vpid_bitmap, VMX_NR_VPIDS); static DEFINE_SPINLOCK(vmx_vpid_lock); static struct vmcs_config { int size; int order; u32 revision_id; u32 pin_based_exec_ctrl; u32 cpu_based_exec_ctrl; u32 cpu_based_2nd_exec_ctrl; u32 vmexit_ctrl; u32 vmentry_ctrl; } vmcs_config; static struct vmx_capability { u32 ept; u32 vpid; } vmx_capability; #define VMX_SEGMENT_FIELD(seg) \ [VCPU_SREG_##seg] = { \ .selector = GUEST_##seg##_SELECTOR, \ .base = GUEST_##seg##_BASE, \ .limit = GUEST_##seg##_LIMIT, \ .ar_bytes = GUEST_##seg##_AR_BYTES, \ } static const struct kvm_vmx_segment_field { unsigned selector; unsigned base; unsigned limit; unsigned ar_bytes; } kvm_vmx_segment_fields[] = { VMX_SEGMENT_FIELD(CS), VMX_SEGMENT_FIELD(DS), VMX_SEGMENT_FIELD(ES), VMX_SEGMENT_FIELD(FS), VMX_SEGMENT_FIELD(GS), VMX_SEGMENT_FIELD(SS), VMX_SEGMENT_FIELD(TR), VMX_SEGMENT_FIELD(LDTR), }; static u64 host_efer; static void ept_save_pdptrs(struct kvm_vcpu *vcpu); /* * Keep MSR_STAR at the end, as setup_msrs() will try to optimize it * away by decrementing the array size. */ static const u32 vmx_msr_index[] = { #ifdef CONFIG_X86_64 MSR_SYSCALL_MASK, MSR_LSTAR, MSR_CSTAR, #endif MSR_EFER, MSR_TSC_AUX, MSR_STAR, }; #define NR_VMX_MSR ARRAY_SIZE(vmx_msr_index) static inline bool is_page_fault(u32 intr_info) { return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK | INTR_INFO_VALID_MASK)) == (INTR_TYPE_HARD_EXCEPTION | PF_VECTOR | INTR_INFO_VALID_MASK); } static inline bool is_no_device(u32 intr_info) { return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK | INTR_INFO_VALID_MASK)) == (INTR_TYPE_HARD_EXCEPTION | NM_VECTOR | INTR_INFO_VALID_MASK); } static inline bool is_invalid_opcode(u32 intr_info) { return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK | INTR_INFO_VALID_MASK)) == (INTR_TYPE_HARD_EXCEPTION | UD_VECTOR | INTR_INFO_VALID_MASK); } static inline bool is_external_interrupt(u32 intr_info) { return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VALID_MASK)) == (INTR_TYPE_EXT_INTR | INTR_INFO_VALID_MASK); } static inline bool is_machine_check(u32 intr_info) { return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK | INTR_INFO_VALID_MASK)) == (INTR_TYPE_HARD_EXCEPTION | MC_VECTOR | INTR_INFO_VALID_MASK); } static inline bool cpu_has_vmx_msr_bitmap(void) { return vmcs_config.cpu_based_exec_ctrl & CPU_BASED_USE_MSR_BITMAPS; } static inline bool cpu_has_vmx_tpr_shadow(void) { return vmcs_config.cpu_based_exec_ctrl & CPU_BASED_TPR_SHADOW; } static inline bool vm_need_tpr_shadow(struct kvm *kvm) { return (cpu_has_vmx_tpr_shadow()) && (irqchip_in_kernel(kvm)); } static inline bool cpu_has_secondary_exec_ctrls(void) { return vmcs_config.cpu_based_exec_ctrl & CPU_BASED_ACTIVATE_SECONDARY_CONTROLS; } static inline bool cpu_has_vmx_virtualize_apic_accesses(void) { return vmcs_config.cpu_based_2nd_exec_ctrl & SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES; } static inline bool cpu_has_vmx_virtualize_x2apic_mode(void) { return vmcs_config.cpu_based_2nd_exec_ctrl & SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE; } static inline bool cpu_has_vmx_apic_register_virt(void) { return vmcs_config.cpu_based_2nd_exec_ctrl & SECONDARY_EXEC_APIC_REGISTER_VIRT; } static inline bool cpu_has_vmx_virtual_intr_delivery(void) { return vmcs_config.cpu_based_2nd_exec_ctrl & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY; } static inline bool cpu_has_vmx_posted_intr(void) { return vmcs_config.pin_based_exec_ctrl & PIN_BASED_POSTED_INTR; } static inline bool cpu_has_vmx_apicv(void) { return cpu_has_vmx_apic_register_virt() && cpu_has_vmx_virtual_intr_delivery() && cpu_has_vmx_posted_intr(); } static inline bool cpu_has_vmx_flexpriority(void) { return cpu_has_vmx_tpr_shadow() && cpu_has_vmx_virtualize_apic_accesses(); } static inline bool cpu_has_vmx_ept_execute_only(void) { return vmx_capability.ept & VMX_EPT_EXECUTE_ONLY_BIT; } static inline bool cpu_has_vmx_eptp_uncacheable(void) { return vmx_capability.ept & VMX_EPTP_UC_BIT; } static inline bool cpu_has_vmx_eptp_writeback(void) { return vmx_capability.ept & VMX_EPTP_WB_BIT; } static inline bool cpu_has_vmx_ept_2m_page(void) { return vmx_capability.ept & VMX_EPT_2MB_PAGE_BIT; } static inline bool cpu_has_vmx_ept_1g_page(void) { return vmx_capability.ept & VMX_EPT_1GB_PAGE_BIT; } static inline bool cpu_has_vmx_ept_4levels(void) { return vmx_capability.ept & VMX_EPT_PAGE_WALK_4_BIT; } static inline bool cpu_has_vmx_ept_ad_bits(void) { return vmx_capability.ept & VMX_EPT_AD_BIT; } static inline bool cpu_has_vmx_invept_context(void) { return vmx_capability.ept & VMX_EPT_EXTENT_CONTEXT_BIT; } static inline bool cpu_has_vmx_invept_global(void) { return vmx_capability.ept & VMX_EPT_EXTENT_GLOBAL_BIT; } static inline bool cpu_has_vmx_invvpid_single(void) { return vmx_capability.vpid & VMX_VPID_EXTENT_SINGLE_CONTEXT_BIT; } static inline bool cpu_has_vmx_invvpid_global(void) { return vmx_capability.vpid & VMX_VPID_EXTENT_GLOBAL_CONTEXT_BIT; } static inline bool cpu_has_vmx_ept(void) { return vmcs_config.cpu_based_2nd_exec_ctrl & SECONDARY_EXEC_ENABLE_EPT; } static inline bool cpu_has_vmx_unrestricted_guest(void) { return vmcs_config.cpu_based_2nd_exec_ctrl & SECONDARY_EXEC_UNRESTRICTED_GUEST; } static inline bool cpu_has_vmx_ple(void) { return vmcs_config.cpu_based_2nd_exec_ctrl & SECONDARY_EXEC_PAUSE_LOOP_EXITING; } static inline bool vm_need_virtualize_apic_accesses(struct kvm *kvm) { return flexpriority_enabled && irqchip_in_kernel(kvm); } static inline bool cpu_has_vmx_vpid(void) { return vmcs_config.cpu_based_2nd_exec_ctrl & SECONDARY_EXEC_ENABLE_VPID; } static inline bool cpu_has_vmx_rdtscp(void) { return vmcs_config.cpu_based_2nd_exec_ctrl & SECONDARY_EXEC_RDTSCP; } static inline bool cpu_has_vmx_invpcid(void) { return vmcs_config.cpu_based_2nd_exec_ctrl & SECONDARY_EXEC_ENABLE_INVPCID; } static inline bool cpu_has_virtual_nmis(void) { return vmcs_config.pin_based_exec_ctrl & PIN_BASED_VIRTUAL_NMIS; } static inline bool cpu_has_vmx_wbinvd_exit(void) { return vmcs_config.cpu_based_2nd_exec_ctrl & SECONDARY_EXEC_WBINVD_EXITING; } static inline bool cpu_has_vmx_shadow_vmcs(void) { u64 vmx_msr; rdmsrl(MSR_IA32_VMX_MISC, vmx_msr); /* check if the cpu supports writing r/o exit information fields */ if (!(vmx_msr & MSR_IA32_VMX_MISC_VMWRITE_SHADOW_RO_FIELDS)) return false; return vmcs_config.cpu_based_2nd_exec_ctrl & SECONDARY_EXEC_SHADOW_VMCS; } static inline bool report_flexpriority(void) { return flexpriority_enabled; } static inline bool nested_cpu_has(struct vmcs12 *vmcs12, u32 bit) { return vmcs12->cpu_based_vm_exec_control & bit; } static inline bool nested_cpu_has2(struct vmcs12 *vmcs12, u32 bit) { return (vmcs12->cpu_based_vm_exec_control & CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) && (vmcs12->secondary_vm_exec_control & bit); } static inline bool nested_cpu_has_virtual_nmis(struct vmcs12 *vmcs12, struct kvm_vcpu *vcpu) { return vmcs12->pin_based_vm_exec_control & PIN_BASED_VIRTUAL_NMIS; } static inline int nested_cpu_has_ept(struct vmcs12 *vmcs12) { return nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_EPT); } static inline bool is_exception(u32 intr_info) { return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VALID_MASK)) == (INTR_TYPE_HARD_EXCEPTION | INTR_INFO_VALID_MASK); } static void nested_vmx_vmexit(struct kvm_vcpu *vcpu); static void nested_vmx_entry_failure(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12, u32 reason, unsigned long qualification); static int __find_msr_index(struct vcpu_vmx *vmx, u32 msr) { int i; for (i = 0; i < vmx->nmsrs; ++i) if (vmx_msr_index[vmx->guest_msrs[i].index] == msr) return i; return -1; } static inline void __invvpid(int ext, u16 vpid, gva_t gva) { struct { u64 vpid : 16; u64 rsvd : 48; u64 gva; } operand = { vpid, 0, gva }; asm volatile (__ex(ASM_VMX_INVVPID) /* CF==1 or ZF==1 --> rc = -1 */ "; ja 1f ; ud2 ; 1:" : : "a"(&operand), "c"(ext) : "cc", "memory"); } static inline void __invept(int ext, u64 eptp, gpa_t gpa) { struct { u64 eptp, gpa; } operand = {eptp, gpa}; asm volatile (__ex(ASM_VMX_INVEPT) /* CF==1 or ZF==1 --> rc = -1 */ "; ja 1f ; ud2 ; 1:\n" : : "a" (&operand), "c" (ext) : "cc", "memory"); } static struct shared_msr_entry *find_msr_entry(struct vcpu_vmx *vmx, u32 msr) { int i; i = __find_msr_index(vmx, msr); if (i >= 0) return &vmx->guest_msrs[i]; return NULL; } static void vmcs_clear(struct vmcs *vmcs) { u64 phys_addr = __pa(vmcs); u8 error; asm volatile (__ex(ASM_VMX_VMCLEAR_RAX) "; setna %0" : "=qm"(error) : "a"(&phys_addr), "m"(phys_addr) : "cc", "memory"); if (error) printk(KERN_ERR "kvm: vmclear fail: %p/%llx\n", vmcs, phys_addr); } static inline void loaded_vmcs_init(struct loaded_vmcs *loaded_vmcs) { vmcs_clear(loaded_vmcs->vmcs); loaded_vmcs->cpu = -1; loaded_vmcs->launched = 0; } static void vmcs_load(struct vmcs *vmcs) { u64 phys_addr = __pa(vmcs); u8 error; asm volatile (__ex(ASM_VMX_VMPTRLD_RAX) "; setna %0" : "=qm"(error) : "a"(&phys_addr), "m"(phys_addr) : "cc", "memory"); if (error) printk(KERN_ERR "kvm: vmptrld %p/%llx failed\n", vmcs, phys_addr); } #ifdef CONFIG_KEXEC /* * This bitmap is used to indicate whether the vmclear * operation is enabled on all cpus. All disabled by * default. */ static cpumask_t crash_vmclear_enabled_bitmap = CPU_MASK_NONE; static inline void crash_enable_local_vmclear(int cpu) { cpumask_set_cpu(cpu, &crash_vmclear_enabled_bitmap); } static inline void crash_disable_local_vmclear(int cpu) { cpumask_clear_cpu(cpu, &crash_vmclear_enabled_bitmap); } static inline int crash_local_vmclear_enabled(int cpu) { return cpumask_test_cpu(cpu, &crash_vmclear_enabled_bitmap); } static void crash_vmclear_local_loaded_vmcss(void) { int cpu = raw_smp_processor_id(); struct loaded_vmcs *v; if (!crash_local_vmclear_enabled(cpu)) return; list_for_each_entry(v, &per_cpu(loaded_vmcss_on_cpu, cpu), loaded_vmcss_on_cpu_link) vmcs_clear(v->vmcs); } #else static inline void crash_enable_local_vmclear(int cpu) { } static inline void crash_disable_local_vmclear(int cpu) { } #endif /* CONFIG_KEXEC */ static void __loaded_vmcs_clear(void *arg) { struct loaded_vmcs *loaded_vmcs = arg; int cpu = raw_smp_processor_id(); if (loaded_vmcs->cpu != cpu) return; /* vcpu migration can race with cpu offline */ if (per_cpu(current_vmcs, cpu) == loaded_vmcs->vmcs) per_cpu(current_vmcs, cpu) = NULL; crash_disable_local_vmclear(cpu); list_del(&loaded_vmcs->loaded_vmcss_on_cpu_link); /* * we should ensure updating loaded_vmcs->loaded_vmcss_on_cpu_link * is before setting loaded_vmcs->vcpu to -1 which is done in * loaded_vmcs_init. Otherwise, other cpu can see vcpu = -1 fist * then adds the vmcs into percpu list before it is deleted. */ smp_wmb(); loaded_vmcs_init(loaded_vmcs); crash_enable_local_vmclear(cpu); } static void loaded_vmcs_clear(struct loaded_vmcs *loaded_vmcs) { int cpu = loaded_vmcs->cpu; if (cpu != -1) smp_call_function_single(cpu, __loaded_vmcs_clear, loaded_vmcs, 1); } static inline void vpid_sync_vcpu_single(struct vcpu_vmx *vmx) { if (vmx->vpid == 0) return; if (cpu_has_vmx_invvpid_single()) __invvpid(VMX_VPID_EXTENT_SINGLE_CONTEXT, vmx->vpid, 0); } static inline void vpid_sync_vcpu_global(void) { if (cpu_has_vmx_invvpid_global()) __invvpid(VMX_VPID_EXTENT_ALL_CONTEXT, 0, 0); } static inline void vpid_sync_context(struct vcpu_vmx *vmx) { if (cpu_has_vmx_invvpid_single()) vpid_sync_vcpu_single(vmx); else vpid_sync_vcpu_global(); } static inline void ept_sync_global(void) { if (cpu_has_vmx_invept_global()) __invept(VMX_EPT_EXTENT_GLOBAL, 0, 0); } static inline void ept_sync_context(u64 eptp) { if (enable_ept) { if (cpu_has_vmx_invept_context()) __invept(VMX_EPT_EXTENT_CONTEXT, eptp, 0); else ept_sync_global(); } } static __always_inline unsigned long vmcs_readl(unsigned long field) { unsigned long value; asm volatile (__ex_clear(ASM_VMX_VMREAD_RDX_RAX, "%0") : "=a"(value) : "d"(field) : "cc"); return value; } static __always_inline u16 vmcs_read16(unsigned long field) { return vmcs_readl(field); } static __always_inline u32 vmcs_read32(unsigned long field) { return vmcs_readl(field); } static __always_inline u64 vmcs_read64(unsigned long field) { #ifdef CONFIG_X86_64 return vmcs_readl(field); #else return vmcs_readl(field) | ((u64)vmcs_readl(field+1) << 32); #endif } static noinline void vmwrite_error(unsigned long field, unsigned long value) { printk(KERN_ERR "vmwrite error: reg %lx value %lx (err %d)\n", field, value, vmcs_read32(VM_INSTRUCTION_ERROR)); dump_stack(); } static void vmcs_writel(unsigned long field, unsigned long value) { u8 error; asm volatile (__ex(ASM_VMX_VMWRITE_RAX_RDX) "; setna %0" : "=q"(error) : "a"(value), "d"(field) : "cc"); if (unlikely(error)) vmwrite_error(field, value); } static void vmcs_write16(unsigned long field, u16 value) { vmcs_writel(field, value); } static void vmcs_write32(unsigned long field, u32 value) { vmcs_writel(field, value); } static void vmcs_write64(unsigned long field, u64 value) { vmcs_writel(field, value); #ifndef CONFIG_X86_64 asm volatile (""); vmcs_writel(field+1, value >> 32); #endif } static void vmcs_clear_bits(unsigned long field, u32 mask) { vmcs_writel(field, vmcs_readl(field) & ~mask); } static void vmcs_set_bits(unsigned long field, u32 mask) { vmcs_writel(field, vmcs_readl(field) | mask); } static void vmx_segment_cache_clear(struct vcpu_vmx *vmx) { vmx->segment_cache.bitmask = 0; } static bool vmx_segment_cache_test_set(struct vcpu_vmx *vmx, unsigned seg, unsigned field) { bool ret; u32 mask = 1 << (seg * SEG_FIELD_NR + field); if (!(vmx->vcpu.arch.regs_avail & (1 << VCPU_EXREG_SEGMENTS))) { vmx->vcpu.arch.regs_avail |= (1 << VCPU_EXREG_SEGMENTS); vmx->segment_cache.bitmask = 0; } ret = vmx->segment_cache.bitmask & mask; vmx->segment_cache.bitmask |= mask; return ret; } static u16 vmx_read_guest_seg_selector(struct vcpu_vmx *vmx, unsigned seg) { u16 *p = &vmx->segment_cache.seg[seg].selector; if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_SEL)) *p = vmcs_read16(kvm_vmx_segment_fields[seg].selector); return *p; } static ulong vmx_read_guest_seg_base(struct vcpu_vmx *vmx, unsigned seg) { ulong *p = &vmx->segment_cache.seg[seg].base; if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_BASE)) *p = vmcs_readl(kvm_vmx_segment_fields[seg].base); return *p; } static u32 vmx_read_guest_seg_limit(struct vcpu_vmx *vmx, unsigned seg) { u32 *p = &vmx->segment_cache.seg[seg].limit; if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_LIMIT)) *p = vmcs_read32(kvm_vmx_segment_fields[seg].limit); return *p; } static u32 vmx_read_guest_seg_ar(struct vcpu_vmx *vmx, unsigned seg) { u32 *p = &vmx->segment_cache.seg[seg].ar; if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_AR)) *p = vmcs_read32(kvm_vmx_segment_fields[seg].ar_bytes); return *p; } static void update_exception_bitmap(struct kvm_vcpu *vcpu) { u32 eb; eb = (1u << PF_VECTOR) | (1u << UD_VECTOR) | (1u << MC_VECTOR) | (1u << NM_VECTOR) | (1u << DB_VECTOR); if ((vcpu->guest_debug & (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP)) == (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP)) eb |= 1u << BP_VECTOR; if (to_vmx(vcpu)->rmode.vm86_active) eb = ~0; if (enable_ept) eb &= ~(1u << PF_VECTOR); /* bypass_guest_pf = 0 */ if (vcpu->fpu_active) eb &= ~(1u << NM_VECTOR); /* When we are running a nested L2 guest and L1 specified for it a * certain exception bitmap, we must trap the same exceptions and pass * them to L1. When running L2, we will only handle the exceptions * specified above if L1 did not want them. */ if (is_guest_mode(vcpu)) eb |= get_vmcs12(vcpu)->exception_bitmap; vmcs_write32(EXCEPTION_BITMAP, eb); } static void clear_atomic_switch_msr_special(unsigned long entry, unsigned long exit) { vmcs_clear_bits(VM_ENTRY_CONTROLS, entry); vmcs_clear_bits(VM_EXIT_CONTROLS, exit); } static void clear_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr) { unsigned i; struct msr_autoload *m = &vmx->msr_autoload; switch (msr) { case MSR_EFER: if (cpu_has_load_ia32_efer) { clear_atomic_switch_msr_special(VM_ENTRY_LOAD_IA32_EFER, VM_EXIT_LOAD_IA32_EFER); return; } break; case MSR_CORE_PERF_GLOBAL_CTRL: if (cpu_has_load_perf_global_ctrl) { clear_atomic_switch_msr_special( VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL, VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL); return; } break; } for (i = 0; i < m->nr; ++i) if (m->guest[i].index == msr) break; if (i == m->nr) return; --m->nr; m->guest[i] = m->guest[m->nr]; m->host[i] = m->host[m->nr]; vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->nr); vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->nr); } static void add_atomic_switch_msr_special(unsigned long entry, unsigned long exit, unsigned long guest_val_vmcs, unsigned long host_val_vmcs, u64 guest_val, u64 host_val) { vmcs_write64(guest_val_vmcs, guest_val); vmcs_write64(host_val_vmcs, host_val); vmcs_set_bits(VM_ENTRY_CONTROLS, entry); vmcs_set_bits(VM_EXIT_CONTROLS, exit); } static void add_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr, u64 guest_val, u64 host_val) { unsigned i; struct msr_autoload *m = &vmx->msr_autoload; switch (msr) { case MSR_EFER: if (cpu_has_load_ia32_efer) { add_atomic_switch_msr_special(VM_ENTRY_LOAD_IA32_EFER, VM_EXIT_LOAD_IA32_EFER, GUEST_IA32_EFER, HOST_IA32_EFER, guest_val, host_val); return; } break; case MSR_CORE_PERF_GLOBAL_CTRL: if (cpu_has_load_perf_global_ctrl) { add_atomic_switch_msr_special( VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL, VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL, GUEST_IA32_PERF_GLOBAL_CTRL, HOST_IA32_PERF_GLOBAL_CTRL, guest_val, host_val); return; } break; } for (i = 0; i < m->nr; ++i) if (m->guest[i].index == msr) break; if (i == NR_AUTOLOAD_MSRS) { printk_once(KERN_WARNING"Not enough mst switch entries. " "Can't add msr %x\n", msr); return; } else if (i == m->nr) { ++m->nr; vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->nr); vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->nr); } m->guest[i].index = msr; m->guest[i].value = guest_val; m->host[i].index = msr; m->host[i].value = host_val; } static void reload_tss(void) { /* * VT restores TR but not its size. Useless. */ struct desc_ptr *gdt = &__get_cpu_var(host_gdt); struct desc_struct *descs; descs = (void *)gdt->address; descs[GDT_ENTRY_TSS].type = 9; /* available TSS */ load_TR_desc(); } static bool update_transition_efer(struct vcpu_vmx *vmx, int efer_offset) { u64 guest_efer; u64 ignore_bits; guest_efer = vmx->vcpu.arch.efer; /* * NX is emulated; LMA and LME handled by hardware; SCE meaningless * outside long mode */ ignore_bits = EFER_NX | EFER_SCE; #ifdef CONFIG_X86_64 ignore_bits |= EFER_LMA | EFER_LME; /* SCE is meaningful only in long mode on Intel */ if (guest_efer & EFER_LMA) ignore_bits &= ~(u64)EFER_SCE; #endif guest_efer &= ~ignore_bits; guest_efer |= host_efer & ignore_bits; vmx->guest_msrs[efer_offset].data = guest_efer; vmx->guest_msrs[efer_offset].mask = ~ignore_bits; clear_atomic_switch_msr(vmx, MSR_EFER); /* On ept, can't emulate nx, and must switch nx atomically */ if (enable_ept && ((vmx->vcpu.arch.efer ^ host_efer) & EFER_NX)) { guest_efer = vmx->vcpu.arch.efer; if (!(guest_efer & EFER_LMA)) guest_efer &= ~EFER_LME; add_atomic_switch_msr(vmx, MSR_EFER, guest_efer, host_efer); return false; } return true; } static unsigned long segment_base(u16 selector) { struct desc_ptr *gdt = &__get_cpu_var(host_gdt); struct desc_struct *d; unsigned long table_base; unsigned long v; if (!(selector & ~3)) return 0; table_base = gdt->address; if (selector & 4) { /* from ldt */ u16 ldt_selector = kvm_read_ldt(); if (!(ldt_selector & ~3)) return 0; table_base = segment_base(ldt_selector); } d = (struct desc_struct *)(table_base + (selector & ~7)); v = get_desc_base(d); #ifdef CONFIG_X86_64 if (d->s == 0 && (d->type == 2 || d->type == 9 || d->type == 11)) v |= ((unsigned long)((struct ldttss_desc64 *)d)->base3) << 32; #endif return v; } static inline unsigned long kvm_read_tr_base(void) { u16 tr; asm("str %0" : "=g"(tr)); return segment_base(tr); } static void vmx_save_host_state(struct kvm_vcpu *vcpu) { struct vcpu_vmx *vmx = to_vmx(vcpu); int i; if (vmx->host_state.loaded) return; vmx->host_state.loaded = 1; /* * Set host fs and gs selectors. Unfortunately, 22.2.3 does not * allow segment selectors with cpl > 0 or ti == 1. */ vmx->host_state.ldt_sel = kvm_read_ldt(); vmx->host_state.gs_ldt_reload_needed = vmx->host_state.ldt_sel; savesegment(fs, vmx->host_state.fs_sel); if (!(vmx->host_state.fs_sel & 7)) { vmcs_write16(HOST_FS_SELECTOR, vmx->host_state.fs_sel); vmx->host_state.fs_reload_needed = 0; } else { vmcs_write16(HOST_FS_SELECTOR, 0); vmx->host_state.fs_reload_needed = 1; } savesegment(gs, vmx->host_state.gs_sel); if (!(vmx->host_state.gs_sel & 7)) vmcs_write16(HOST_GS_SELECTOR, vmx->host_state.gs_sel); else { vmcs_write16(HOST_GS_SELECTOR, 0); vmx->host_state.gs_ldt_reload_needed = 1; } #ifdef CONFIG_X86_64 savesegment(ds, vmx->host_state.ds_sel); savesegment(es, vmx->host_state.es_sel); #endif #ifdef CONFIG_X86_64 vmcs_writel(HOST_FS_BASE, read_msr(MSR_FS_BASE)); vmcs_writel(HOST_GS_BASE, read_msr(MSR_GS_BASE)); #else vmcs_writel(HOST_FS_BASE, segment_base(vmx->host_state.fs_sel)); vmcs_writel(HOST_GS_BASE, segment_base(vmx->host_state.gs_sel)); #endif #ifdef CONFIG_X86_64 rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base); if (is_long_mode(&vmx->vcpu)) wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base); #endif for (i = 0; i < vmx->save_nmsrs; ++i) kvm_set_shared_msr(vmx->guest_msrs[i].index, vmx->guest_msrs[i].data, vmx->guest_msrs[i].mask); } static void __vmx_load_host_state(struct vcpu_vmx *vmx) { if (!vmx->host_state.loaded) return; ++vmx->vcpu.stat.host_state_reload; vmx->host_state.loaded = 0; #ifdef CONFIG_X86_64 if (is_long_mode(&vmx->vcpu)) rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base); #endif if (vmx->host_state.gs_ldt_reload_needed) { kvm_load_ldt(vmx->host_state.ldt_sel); #ifdef CONFIG_X86_64 load_gs_index(vmx->host_state.gs_sel); #else loadsegment(gs, vmx->host_state.gs_sel); #endif } if (vmx->host_state.fs_reload_needed) loadsegment(fs, vmx->host_state.fs_sel); #ifdef CONFIG_X86_64 if (unlikely(vmx->host_state.ds_sel | vmx->host_state.es_sel)) { loadsegment(ds, vmx->host_state.ds_sel); loadsegment(es, vmx->host_state.es_sel); } #endif reload_tss(); #ifdef CONFIG_X86_64 wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base); #endif /* * If the FPU is not active (through the host task or * the guest vcpu), then restore the cr0.TS bit. */ if (!user_has_fpu() && !vmx->vcpu.guest_fpu_loaded) stts(); load_gdt(&__get_cpu_var(host_gdt)); } static void vmx_load_host_state(struct vcpu_vmx *vmx) { preempt_disable(); __vmx_load_host_state(vmx); preempt_enable(); } /* * Switches to specified vcpu, until a matching vcpu_put(), but assumes * vcpu mutex is already taken. */ static void vmx_vcpu_load(struct kvm_vcpu *vcpu, int cpu) { struct vcpu_vmx *vmx = to_vmx(vcpu); u64 phys_addr = __pa(per_cpu(vmxarea, cpu)); if (!vmm_exclusive) kvm_cpu_vmxon(phys_addr); else if (vmx->loaded_vmcs->cpu != cpu) loaded_vmcs_clear(vmx->loaded_vmcs); if (per_cpu(current_vmcs, cpu) != vmx->loaded_vmcs->vmcs) { per_cpu(current_vmcs, cpu) = vmx->loaded_vmcs->vmcs; vmcs_load(vmx->loaded_vmcs->vmcs); } if (vmx->loaded_vmcs->cpu != cpu) { struct desc_ptr *gdt = &__get_cpu_var(host_gdt); unsigned long sysenter_esp; kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu); local_irq_disable(); crash_disable_local_vmclear(cpu); /* * Read loaded_vmcs->cpu should be before fetching * loaded_vmcs->loaded_vmcss_on_cpu_link. * See the comments in __loaded_vmcs_clear(). */ smp_rmb(); list_add(&vmx->loaded_vmcs->loaded_vmcss_on_cpu_link, &per_cpu(loaded_vmcss_on_cpu, cpu)); crash_enable_local_vmclear(cpu); local_irq_enable(); /* * Linux uses per-cpu TSS and GDT, so set these when switching * processors. */ vmcs_writel(HOST_TR_BASE, kvm_read_tr_base()); /* 22.2.4 */ vmcs_writel(HOST_GDTR_BASE, gdt->address); /* 22.2.4 */ rdmsrl(MSR_IA32_SYSENTER_ESP, sysenter_esp); vmcs_writel(HOST_IA32_SYSENTER_ESP, sysenter_esp); /* 22.2.3 */ vmx->loaded_vmcs->cpu = cpu; } } static void vmx_vcpu_put(struct kvm_vcpu *vcpu) { __vmx_load_host_state(to_vmx(vcpu)); if (!vmm_exclusive) { __loaded_vmcs_clear(to_vmx(vcpu)->loaded_vmcs); vcpu->cpu = -1; kvm_cpu_vmxoff(); } } static void vmx_fpu_activate(struct kvm_vcpu *vcpu) { ulong cr0; if (vcpu->fpu_active) return; vcpu->fpu_active = 1; cr0 = vmcs_readl(GUEST_CR0); cr0 &= ~(X86_CR0_TS | X86_CR0_MP); cr0 |= kvm_read_cr0_bits(vcpu, X86_CR0_TS | X86_CR0_MP); vmcs_writel(GUEST_CR0, cr0); update_exception_bitmap(vcpu); vcpu->arch.cr0_guest_owned_bits = X86_CR0_TS; if (is_guest_mode(vcpu)) vcpu->arch.cr0_guest_owned_bits &= ~get_vmcs12(vcpu)->cr0_guest_host_mask; vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits); } static void vmx_decache_cr0_guest_bits(struct kvm_vcpu *vcpu); /* * Return the cr0 value that a nested guest would read. This is a combination * of the real cr0 used to run the guest (guest_cr0), and the bits shadowed by * its hypervisor (cr0_read_shadow). */ static inline unsigned long nested_read_cr0(struct vmcs12 *fields) { return (fields->guest_cr0 & ~fields->cr0_guest_host_mask) | (fields->cr0_read_shadow & fields->cr0_guest_host_mask); } static inline unsigned long nested_read_cr4(struct vmcs12 *fields) { return (fields->guest_cr4 & ~fields->cr4_guest_host_mask) | (fields->cr4_read_shadow & fields->cr4_guest_host_mask); } static void vmx_fpu_deactivate(struct kvm_vcpu *vcpu) { /* Note that there is no vcpu->fpu_active = 0 here. The caller must * set this *before* calling this function. */ vmx_decache_cr0_guest_bits(vcpu); vmcs_set_bits(GUEST_CR0, X86_CR0_TS | X86_CR0_MP); update_exception_bitmap(vcpu); vcpu->arch.cr0_guest_owned_bits = 0; vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits); if (is_guest_mode(vcpu)) { /* * L1's specified read shadow might not contain the TS bit, * so now that we turned on shadowing of this bit, we need to * set this bit of the shadow. Like in nested_vmx_run we need * nested_read_cr0(vmcs12), but vmcs12->guest_cr0 is not yet * up-to-date here because we just decached cr0.TS (and we'll * only update vmcs12->guest_cr0 on nested exit). */ struct vmcs12 *vmcs12 = get_vmcs12(vcpu); vmcs12->guest_cr0 = (vmcs12->guest_cr0 & ~X86_CR0_TS) | (vcpu->arch.cr0 & X86_CR0_TS); vmcs_writel(CR0_READ_SHADOW, nested_read_cr0(vmcs12)); } else vmcs_writel(CR0_READ_SHADOW, vcpu->arch.cr0); } static unsigned long vmx_get_rflags(struct kvm_vcpu *vcpu) { unsigned long rflags, save_rflags; if (!test_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail)) { __set_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail); rflags = vmcs_readl(GUEST_RFLAGS); if (to_vmx(vcpu)->rmode.vm86_active) { rflags &= RMODE_GUEST_OWNED_EFLAGS_BITS; save_rflags = to_vmx(vcpu)->rmode.save_rflags; rflags |= save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS; } to_vmx(vcpu)->rflags = rflags; } return to_vmx(vcpu)->rflags; } static void vmx_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags) { __set_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail); to_vmx(vcpu)->rflags = rflags; if (to_vmx(vcpu)->rmode.vm86_active) { to_vmx(vcpu)->rmode.save_rflags = rflags; rflags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM; } vmcs_writel(GUEST_RFLAGS, rflags); } static u32 vmx_get_interrupt_shadow(struct kvm_vcpu *vcpu, int mask) { u32 interruptibility = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO); int ret = 0; if (interruptibility & GUEST_INTR_STATE_STI) ret |= KVM_X86_SHADOW_INT_STI; if (interruptibility & GUEST_INTR_STATE_MOV_SS) ret |= KVM_X86_SHADOW_INT_MOV_SS; return ret & mask; } static void vmx_set_interrupt_shadow(struct kvm_vcpu *vcpu, int mask) { u32 interruptibility_old = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO); u32 interruptibility = interruptibility_old; interruptibility &= ~(GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS); if (mask & KVM_X86_SHADOW_INT_MOV_SS) interruptibility |= GUEST_INTR_STATE_MOV_SS; else if (mask & KVM_X86_SHADOW_INT_STI) interruptibility |= GUEST_INTR_STATE_STI; if ((interruptibility != interruptibility_old)) vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, interruptibility); } static void skip_emulated_instruction(struct kvm_vcpu *vcpu) { unsigned long rip; rip = kvm_rip_read(vcpu); rip += vmcs_read32(VM_EXIT_INSTRUCTION_LEN); kvm_rip_write(vcpu, rip); /* skipping an emulated instruction also counts */ vmx_set_interrupt_shadow(vcpu, 0); } /* * KVM wants to inject page-faults which it got to the guest. This function * checks whether in a nested guest, we need to inject them to L1 or L2. * This function assumes it is called with the exit reason in vmcs02 being * a #PF exception (this is the only case in which KVM injects a #PF when L2 * is running). */ static int nested_pf_handled(struct kvm_vcpu *vcpu) { struct vmcs12 *vmcs12 = get_vmcs12(vcpu); /* TODO: also check PFEC_MATCH/MASK, not just EB.PF. */ if (!(vmcs12->exception_bitmap & (1u << PF_VECTOR))) return 0; nested_vmx_vmexit(vcpu); return 1; } static void vmx_queue_exception(struct kvm_vcpu *vcpu, unsigned nr, bool has_error_code, u32 error_code, bool reinject) { struct vcpu_vmx *vmx = to_vmx(vcpu); u32 intr_info = nr | INTR_INFO_VALID_MASK; if (nr == PF_VECTOR && is_guest_mode(vcpu) && !vmx->nested.nested_run_pending && nested_pf_handled(vcpu)) return; if (has_error_code) { vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE, error_code); intr_info |= INTR_INFO_DELIVER_CODE_MASK; } if (vmx->rmode.vm86_active) { int inc_eip = 0; if (kvm_exception_is_soft(nr)) inc_eip = vcpu->arch.event_exit_inst_len; if (kvm_inject_realmode_interrupt(vcpu, nr, inc_eip) != EMULATE_DONE) kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu); return; } if (kvm_exception_is_soft(nr)) { vmcs_write32(VM_ENTRY_INSTRUCTION_LEN, vmx->vcpu.arch.event_exit_inst_len); intr_info |= INTR_TYPE_SOFT_EXCEPTION; } else intr_info |= INTR_TYPE_HARD_EXCEPTION; vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr_info); } static bool vmx_rdtscp_supported(void) { return cpu_has_vmx_rdtscp(); } static bool vmx_invpcid_supported(void) { return cpu_has_vmx_invpcid() && enable_ept; } /* * Swap MSR entry in host/guest MSR entry array. */ static void move_msr_up(struct vcpu_vmx *vmx, int from, int to) { struct shared_msr_entry tmp; tmp = vmx->guest_msrs[to]; vmx->guest_msrs[to] = vmx->guest_msrs[from]; vmx->guest_msrs[from] = tmp; } static void vmx_set_msr_bitmap(struct kvm_vcpu *vcpu) { unsigned long *msr_bitmap; if (irqchip_in_kernel(vcpu->kvm) && apic_x2apic_mode(vcpu->arch.apic)) { if (is_long_mode(vcpu)) msr_bitmap = vmx_msr_bitmap_longmode_x2apic; else msr_bitmap = vmx_msr_bitmap_legacy_x2apic; } else { if (is_long_mode(vcpu)) msr_bitmap = vmx_msr_bitmap_longmode; else msr_bitmap = vmx_msr_bitmap_legacy; } vmcs_write64(MSR_BITMAP, __pa(msr_bitmap)); } /* * Set up the vmcs to automatically save and restore system * msrs. Don't touch the 64-bit msrs if the guest is in legacy * mode, as fiddling with msrs is very expensive. */ static void setup_msrs(struct vcpu_vmx *vmx) { int save_nmsrs, index; save_nmsrs = 0; #ifdef CONFIG_X86_64 if (is_long_mode(&vmx->vcpu)) { index = __find_msr_index(vmx, MSR_SYSCALL_MASK); if (index >= 0) move_msr_up(vmx, index, save_nmsrs++); index = __find_msr_index(vmx, MSR_LSTAR); if (index >= 0) move_msr_up(vmx, index, save_nmsrs++); index = __find_msr_index(vmx, MSR_CSTAR); if (index >= 0) move_msr_up(vmx, index, save_nmsrs++); index = __find_msr_index(vmx, MSR_TSC_AUX); if (index >= 0 && vmx->rdtscp_enabled) move_msr_up(vmx, index, save_nmsrs++); /* * MSR_STAR is only needed on long mode guests, and only * if efer.sce is enabled. */ index = __find_msr_index(vmx, MSR_STAR); if ((index >= 0) && (vmx->vcpu.arch.efer & EFER_SCE)) move_msr_up(vmx, index, save_nmsrs++); } #endif index = __find_msr_index(vmx, MSR_EFER); if (index >= 0 && update_transition_efer(vmx, index)) move_msr_up(vmx, index, save_nmsrs++); vmx->save_nmsrs = save_nmsrs; if (cpu_has_vmx_msr_bitmap()) vmx_set_msr_bitmap(&vmx->vcpu); } /* * reads and returns guest's timestamp counter "register" * guest_tsc = host_tsc + tsc_offset -- 21.3 */ static u64 guest_read_tsc(void) { u64 host_tsc, tsc_offset; rdtscll(host_tsc); tsc_offset = vmcs_read64(TSC_OFFSET); return host_tsc + tsc_offset; } /* * Like guest_read_tsc, but always returns L1's notion of the timestamp * counter, even if a nested guest (L2) is currently running. */ u64 vmx_read_l1_tsc(struct kvm_vcpu *vcpu, u64 host_tsc) { u64 tsc_offset; tsc_offset = is_guest_mode(vcpu) ? to_vmx(vcpu)->nested.vmcs01_tsc_offset : vmcs_read64(TSC_OFFSET); return host_tsc + tsc_offset; } /* * Engage any workarounds for mis-matched TSC rates. Currently limited to * software catchup for faster rates on slower CPUs. */ static void vmx_set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz, bool scale) { if (!scale) return; if (user_tsc_khz > tsc_khz) { vcpu->arch.tsc_catchup = 1; vcpu->arch.tsc_always_catchup = 1; } else WARN(1, "user requested TSC rate below hardware speed\n"); } static u64 vmx_read_tsc_offset(struct kvm_vcpu *vcpu) { return vmcs_read64(TSC_OFFSET); } /* * writes 'offset' into guest's timestamp counter offset register */ static void vmx_write_tsc_offset(struct kvm_vcpu *vcpu, u64 offset) { if (is_guest_mode(vcpu)) { /* * We're here if L1 chose not to trap WRMSR to TSC. According * to the spec, this should set L1's TSC; The offset that L1 * set for L2 remains unchanged, and still needs to be added * to the newly set TSC to get L2's TSC. */ struct vmcs12 *vmcs12; to_vmx(vcpu)->nested.vmcs01_tsc_offset = offset; /* recalculate vmcs02.TSC_OFFSET: */ vmcs12 = get_vmcs12(vcpu); vmcs_write64(TSC_OFFSET, offset + (nested_cpu_has(vmcs12, CPU_BASED_USE_TSC_OFFSETING) ? vmcs12->tsc_offset : 0)); } else { trace_kvm_write_tsc_offset(vcpu->vcpu_id, vmcs_read64(TSC_OFFSET), offset); vmcs_write64(TSC_OFFSET, offset); } } static void vmx_adjust_tsc_offset(struct kvm_vcpu *vcpu, s64 adjustment, bool host) { u64 offset = vmcs_read64(TSC_OFFSET); vmcs_write64(TSC_OFFSET, offset + adjustment); if (is_guest_mode(vcpu)) { /* Even when running L2, the adjustment needs to apply to L1 */ to_vmx(vcpu)->nested.vmcs01_tsc_offset += adjustment; } else trace_kvm_write_tsc_offset(vcpu->vcpu_id, offset, offset + adjustment); } static u64 vmx_compute_tsc_offset(struct kvm_vcpu *vcpu, u64 target_tsc) { return target_tsc - native_read_tsc(); } static bool guest_cpuid_has_vmx(struct kvm_vcpu *vcpu) { struct kvm_cpuid_entry2 *best = kvm_find_cpuid_entry(vcpu, 1, 0); return best && (best->ecx & (1 << (X86_FEATURE_VMX & 31))); } /* * nested_vmx_allowed() checks whether a guest should be allowed to use VMX * instructions and MSRs (i.e., nested VMX). Nested VMX is disabled for * all guests if the "nested" module option is off, and can also be disabled * for a single guest by disabling its VMX cpuid bit. */ static inline bool nested_vmx_allowed(struct kvm_vcpu *vcpu) { return nested && guest_cpuid_has_vmx(vcpu); } /* * nested_vmx_setup_ctls_msrs() sets up variables containing the values to be * returned for the various VMX controls MSRs when nested VMX is enabled. * The same values should also be used to verify that vmcs12 control fields are * valid during nested entry from L1 to L2. * Each of these control msrs has a low and high 32-bit half: A low bit is on * if the corresponding bit in the (32-bit) control field *must* be on, and a * bit in the high half is on if the corresponding bit in the control field * may be on. See also vmx_control_verify(). * TODO: allow these variables to be modified (downgraded) by module options * or other means. */ static u32 nested_vmx_procbased_ctls_low, nested_vmx_procbased_ctls_high; static u32 nested_vmx_secondary_ctls_low, nested_vmx_secondary_ctls_high; static u32 nested_vmx_pinbased_ctls_low, nested_vmx_pinbased_ctls_high; static u32 nested_vmx_exit_ctls_low, nested_vmx_exit_ctls_high; static u32 nested_vmx_entry_ctls_low, nested_vmx_entry_ctls_high; static u32 nested_vmx_misc_low, nested_vmx_misc_high; static __init void nested_vmx_setup_ctls_msrs(void) { /* * Note that as a general rule, the high half of the MSRs (bits in * the control fields which may be 1) should be initialized by the * intersection of the underlying hardware's MSR (i.e., features which * can be supported) and the list of features we want to expose - * because they are known to be properly supported in our code. * Also, usually, the low half of the MSRs (bits which must be 1) can * be set to 0, meaning that L1 may turn off any of these bits. The * reason is that if one of these bits is necessary, it will appear * in vmcs01 and prepare_vmcs02, when it bitwise-or's the control * fields of vmcs01 and vmcs02, will turn these bits off - and * nested_vmx_exit_handled() will not pass related exits to L1. * These rules have exceptions below. */ /* pin-based controls */ rdmsr(MSR_IA32_VMX_PINBASED_CTLS, nested_vmx_pinbased_ctls_low, nested_vmx_pinbased_ctls_high); /* * According to the Intel spec, if bit 55 of VMX_BASIC is off (as it is * in our case), bits 1, 2 and 4 (i.e., 0x16) must be 1 in this MSR. */ nested_vmx_pinbased_ctls_low |= PIN_BASED_ALWAYSON_WITHOUT_TRUE_MSR; nested_vmx_pinbased_ctls_high &= PIN_BASED_EXT_INTR_MASK | PIN_BASED_NMI_EXITING | PIN_BASED_VIRTUAL_NMIS | PIN_BASED_VMX_PREEMPTION_TIMER; nested_vmx_pinbased_ctls_high |= PIN_BASED_ALWAYSON_WITHOUT_TRUE_MSR; /* * Exit controls * If bit 55 of VMX_BASIC is off, bits 0-8 and 10, 11, 13, 14, 16 and * 17 must be 1. */ nested_vmx_exit_ctls_low = VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR; /* Note that guest use of VM_EXIT_ACK_INTR_ON_EXIT is not supported. */ #ifdef CONFIG_X86_64 nested_vmx_exit_ctls_high = VM_EXIT_HOST_ADDR_SPACE_SIZE; #else nested_vmx_exit_ctls_high = 0; #endif nested_vmx_exit_ctls_high |= (VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR | VM_EXIT_LOAD_IA32_EFER); /* entry controls */ rdmsr(MSR_IA32_VMX_ENTRY_CTLS, nested_vmx_entry_ctls_low, nested_vmx_entry_ctls_high); /* If bit 55 of VMX_BASIC is off, bits 0-8 and 12 must be 1. */ nested_vmx_entry_ctls_low = VM_ENTRY_ALWAYSON_WITHOUT_TRUE_MSR; nested_vmx_entry_ctls_high &= VM_ENTRY_LOAD_IA32_PAT | VM_ENTRY_IA32E_MODE; nested_vmx_entry_ctls_high |= (VM_ENTRY_ALWAYSON_WITHOUT_TRUE_MSR | VM_ENTRY_LOAD_IA32_EFER); /* cpu-based controls */ rdmsr(MSR_IA32_VMX_PROCBASED_CTLS, nested_vmx_procbased_ctls_low, nested_vmx_procbased_ctls_high); nested_vmx_procbased_ctls_low = 0; nested_vmx_procbased_ctls_high &= CPU_BASED_VIRTUAL_INTR_PENDING | CPU_BASED_USE_TSC_OFFSETING | CPU_BASED_HLT_EXITING | CPU_BASED_INVLPG_EXITING | CPU_BASED_MWAIT_EXITING | CPU_BASED_CR3_LOAD_EXITING | CPU_BASED_CR3_STORE_EXITING | #ifdef CONFIG_X86_64 CPU_BASED_CR8_LOAD_EXITING | CPU_BASED_CR8_STORE_EXITING | #endif CPU_BASED_MOV_DR_EXITING | CPU_BASED_UNCOND_IO_EXITING | CPU_BASED_USE_IO_BITMAPS | CPU_BASED_MONITOR_EXITING | CPU_BASED_RDPMC_EXITING | CPU_BASED_RDTSC_EXITING | CPU_BASED_PAUSE_EXITING | CPU_BASED_ACTIVATE_SECONDARY_CONTROLS; /* * We can allow some features even when not supported by the * hardware. For example, L1 can specify an MSR bitmap - and we * can use it to avoid exits to L1 - even when L0 runs L2 * without MSR bitmaps. */ nested_vmx_procbased_ctls_high |= CPU_BASED_USE_MSR_BITMAPS; /* secondary cpu-based controls */ rdmsr(MSR_IA32_VMX_PROCBASED_CTLS2, nested_vmx_secondary_ctls_low, nested_vmx_secondary_ctls_high); nested_vmx_secondary_ctls_low = 0; nested_vmx_secondary_ctls_high &= SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES | SECONDARY_EXEC_WBINVD_EXITING; /* miscellaneous data */ rdmsr(MSR_IA32_VMX_MISC, nested_vmx_misc_low, nested_vmx_misc_high); nested_vmx_misc_low &= VMX_MISC_PREEMPTION_TIMER_RATE_MASK | VMX_MISC_SAVE_EFER_LMA; nested_vmx_misc_high = 0; } static inline bool vmx_control_verify(u32 control, u32 low, u32 high) { /* * Bits 0 in high must be 0, and bits 1 in low must be 1. */ return ((control & high) | low) == control; } static inline u64 vmx_control_msr(u32 low, u32 high) { return low | ((u64)high << 32); } /* * If we allow our guest to use VMX instructions (i.e., nested VMX), we should * also let it use VMX-specific MSRs. * vmx_get_vmx_msr() and vmx_set_vmx_msr() return 1 when we handled a * VMX-specific MSR, or 0 when we haven't (and the caller should handle it * like all other MSRs). */ static int vmx_get_vmx_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 *pdata) { if (!nested_vmx_allowed(vcpu) && msr_index >= MSR_IA32_VMX_BASIC && msr_index <= MSR_IA32_VMX_TRUE_ENTRY_CTLS) { /* * According to the spec, processors which do not support VMX * should throw a #GP(0) when VMX capability MSRs are read. */ kvm_queue_exception_e(vcpu, GP_VECTOR, 0); return 1; } switch (msr_index) { case MSR_IA32_FEATURE_CONTROL: if (nested_vmx_allowed(vcpu)) { *pdata = to_vmx(vcpu)->nested.msr_ia32_feature_control; break; } return 0; case MSR_IA32_VMX_BASIC: /* * This MSR reports some information about VMX support. We * should return information about the VMX we emulate for the * guest, and the VMCS structure we give it - not about the * VMX support of the underlying hardware. */ *pdata = VMCS12_REVISION | ((u64)VMCS12_SIZE << VMX_BASIC_VMCS_SIZE_SHIFT) | (VMX_BASIC_MEM_TYPE_WB << VMX_BASIC_MEM_TYPE_SHIFT); break; case MSR_IA32_VMX_TRUE_PINBASED_CTLS: case MSR_IA32_VMX_PINBASED_CTLS: *pdata = vmx_control_msr(nested_vmx_pinbased_ctls_low, nested_vmx_pinbased_ctls_high); break; case MSR_IA32_VMX_TRUE_PROCBASED_CTLS: case MSR_IA32_VMX_PROCBASED_CTLS: *pdata = vmx_control_msr(nested_vmx_procbased_ctls_low, nested_vmx_procbased_ctls_high); break; case MSR_IA32_VMX_TRUE_EXIT_CTLS: case MSR_IA32_VMX_EXIT_CTLS: *pdata = vmx_control_msr(nested_vmx_exit_ctls_low, nested_vmx_exit_ctls_high); break; case MSR_IA32_VMX_TRUE_ENTRY_CTLS: case MSR_IA32_VMX_ENTRY_CTLS: *pdata = vmx_control_msr(nested_vmx_entry_ctls_low, nested_vmx_entry_ctls_high); break; case MSR_IA32_VMX_MISC: *pdata = vmx_control_msr(nested_vmx_misc_low, nested_vmx_misc_high); break; /* * These MSRs specify bits which the guest must keep fixed (on or off) * while L1 is in VMXON mode (in L1's root mode, or running an L2). * We picked the standard core2 setting. */ #define VMXON_CR0_ALWAYSON (X86_CR0_PE | X86_CR0_PG | X86_CR0_NE) #define VMXON_CR4_ALWAYSON X86_CR4_VMXE case MSR_IA32_VMX_CR0_FIXED0: *pdata = VMXON_CR0_ALWAYSON; break; case MSR_IA32_VMX_CR0_FIXED1: *pdata = -1ULL; break; case MSR_IA32_VMX_CR4_FIXED0: *pdata = VMXON_CR4_ALWAYSON; break; case MSR_IA32_VMX_CR4_FIXED1: *pdata = -1ULL; break; case MSR_IA32_VMX_VMCS_ENUM: *pdata = 0x1f; break; case MSR_IA32_VMX_PROCBASED_CTLS2: *pdata = vmx_control_msr(nested_vmx_secondary_ctls_low, nested_vmx_secondary_ctls_high); break; case MSR_IA32_VMX_EPT_VPID_CAP: /* Currently, no nested ept or nested vpid */ *pdata = 0; break; default: return 0; } return 1; } static int vmx_set_vmx_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info) { u32 msr_index = msr_info->index; u64 data = msr_info->data; bool host_initialized = msr_info->host_initiated; if (!nested_vmx_allowed(vcpu)) return 0; if (msr_index == MSR_IA32_FEATURE_CONTROL) { if (!host_initialized && to_vmx(vcpu)->nested.msr_ia32_feature_control & FEATURE_CONTROL_LOCKED) return 0; to_vmx(vcpu)->nested.msr_ia32_feature_control = data; return 1; } /* * No need to treat VMX capability MSRs specially: If we don't handle * them, handle_wrmsr will #GP(0), which is correct (they are readonly) */ return 0; } /* * Reads an msr value (of 'msr_index') into 'pdata'. * Returns 0 on success, non-0 otherwise. * Assumes vcpu_load() was already called. */ static int vmx_get_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 *pdata) { u64 data; struct shared_msr_entry *msr; if (!pdata) { printk(KERN_ERR "BUG: get_msr called with NULL pdata\n"); return -EINVAL; } switch (msr_index) { #ifdef CONFIG_X86_64 case MSR_FS_BASE: data = vmcs_readl(GUEST_FS_BASE); break; case MSR_GS_BASE: data = vmcs_readl(GUEST_GS_BASE); break; case MSR_KERNEL_GS_BASE: vmx_load_host_state(to_vmx(vcpu)); data = to_vmx(vcpu)->msr_guest_kernel_gs_base; break; #endif case MSR_EFER: return kvm_get_msr_common(vcpu, msr_index, pdata); case MSR_IA32_TSC: data = guest_read_tsc(); break; case MSR_IA32_SYSENTER_CS: data = vmcs_read32(GUEST_SYSENTER_CS); break; case MSR_IA32_SYSENTER_EIP: data = vmcs_readl(GUEST_SYSENTER_EIP); break; case MSR_IA32_SYSENTER_ESP: data = vmcs_readl(GUEST_SYSENTER_ESP); break; case MSR_TSC_AUX: if (!to_vmx(vcpu)->rdtscp_enabled) return 1; /* Otherwise falls through */ default: if (vmx_get_vmx_msr(vcpu, msr_index, pdata)) return 0; msr = find_msr_entry(to_vmx(vcpu), msr_index); if (msr) { data = msr->data; break; } return kvm_get_msr_common(vcpu, msr_index, pdata); } *pdata = data; return 0; } /* * Writes msr value into into the appropriate "register". * Returns 0 on success, non-0 otherwise. * Assumes vcpu_load() was already called. */ static int vmx_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info) { struct vcpu_vmx *vmx = to_vmx(vcpu); struct shared_msr_entry *msr; int ret = 0; u32 msr_index = msr_info->index; u64 data = msr_info->data; switch (msr_index) { case MSR_EFER: ret = kvm_set_msr_common(vcpu, msr_info); break; #ifdef CONFIG_X86_64 case MSR_FS_BASE: vmx_segment_cache_clear(vmx); vmcs_writel(GUEST_FS_BASE, data); break; case MSR_GS_BASE: vmx_segment_cache_clear(vmx); vmcs_writel(GUEST_GS_BASE, data); break; case MSR_KERNEL_GS_BASE: vmx_load_host_state(vmx); vmx->msr_guest_kernel_gs_base = data; break; #endif case MSR_IA32_SYSENTER_CS: vmcs_write32(GUEST_SYSENTER_CS, data); break; case MSR_IA32_SYSENTER_EIP: vmcs_writel(GUEST_SYSENTER_EIP, data); break; case MSR_IA32_SYSENTER_ESP: vmcs_writel(GUEST_SYSENTER_ESP, data); break; case MSR_IA32_TSC: kvm_write_tsc(vcpu, msr_info); break; case MSR_IA32_CR_PAT: if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) { vmcs_write64(GUEST_IA32_PAT, data); vcpu->arch.pat = data; break; } ret = kvm_set_msr_common(vcpu, msr_info); break; case MSR_IA32_TSC_ADJUST: ret = kvm_set_msr_common(vcpu, msr_info); break; case MSR_TSC_AUX: if (!vmx->rdtscp_enabled) return 1; /* Check reserved bit, higher 32 bits should be zero */ if ((data >> 32) != 0) return 1; /* Otherwise falls through */ default: if (vmx_set_vmx_msr(vcpu, msr_info)) break; msr = find_msr_entry(vmx, msr_index); if (msr) { msr->data = data; if (msr - vmx->guest_msrs < vmx->save_nmsrs) { preempt_disable(); kvm_set_shared_msr(msr->index, msr->data, msr->mask); preempt_enable(); } break; } ret = kvm_set_msr_common(vcpu, msr_info); } return ret; } static void vmx_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg) { __set_bit(reg, (unsigned long *)&vcpu->arch.regs_avail); switch (reg) { case VCPU_REGS_RSP: vcpu->arch.regs[VCPU_REGS_RSP] = vmcs_readl(GUEST_RSP); break; case VCPU_REGS_RIP: vcpu->arch.regs[VCPU_REGS_RIP] = vmcs_readl(GUEST_RIP); break; case VCPU_EXREG_PDPTR: if (enable_ept) ept_save_pdptrs(vcpu); break; default: break; } } static __init int cpu_has_kvm_support(void) { return cpu_has_vmx(); } static __init int vmx_disabled_by_bios(void) { u64 msr; rdmsrl(MSR_IA32_FEATURE_CONTROL, msr); if (msr & FEATURE_CONTROL_LOCKED) { /* launched w/ TXT and VMX disabled */ if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX) && tboot_enabled()) return 1; /* launched w/o TXT and VMX only enabled w/ TXT */ if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX) && (msr & FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX) && !tboot_enabled()) { printk(KERN_WARNING "kvm: disable TXT in the BIOS or " "activate TXT before enabling KVM\n"); return 1; } /* launched w/o TXT and VMX disabled */ if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX) && !tboot_enabled()) return 1; } return 0; } static void kvm_cpu_vmxon(u64 addr) { asm volatile (ASM_VMX_VMXON_RAX : : "a"(&addr), "m"(addr) : "memory", "cc"); } static int hardware_enable(void *garbage) { int cpu = raw_smp_processor_id(); u64 phys_addr = __pa(per_cpu(vmxarea, cpu)); u64 old, test_bits; if (read_cr4() & X86_CR4_VMXE) return -EBUSY; INIT_LIST_HEAD(&per_cpu(loaded_vmcss_on_cpu, cpu)); /* * Now we can enable the vmclear operation in kdump * since the loaded_vmcss_on_cpu list on this cpu * has been initialized. * * Though the cpu is not in VMX operation now, there * is no problem to enable the vmclear operation * for the loaded_vmcss_on_cpu list is empty! */ crash_enable_local_vmclear(cpu); rdmsrl(MSR_IA32_FEATURE_CONTROL, old); test_bits = FEATURE_CONTROL_LOCKED; test_bits |= FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX; if (tboot_enabled()) test_bits |= FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX; if ((old & test_bits) != test_bits) { /* enable and lock */ wrmsrl(MSR_IA32_FEATURE_CONTROL, old | test_bits); } write_cr4(read_cr4() | X86_CR4_VMXE); /* FIXME: not cpu hotplug safe */ if (vmm_exclusive) { kvm_cpu_vmxon(phys_addr); ept_sync_global(); } native_store_gdt(&__get_cpu_var(host_gdt)); return 0; } static void vmclear_local_loaded_vmcss(void) { int cpu = raw_smp_processor_id(); struct loaded_vmcs *v, *n; list_for_each_entry_safe(v, n, &per_cpu(loaded_vmcss_on_cpu, cpu), loaded_vmcss_on_cpu_link) __loaded_vmcs_clear(v); } /* Just like cpu_vmxoff(), but with the __kvm_handle_fault_on_reboot() * tricks. */ static void kvm_cpu_vmxoff(void) { asm volatile (__ex(ASM_VMX_VMXOFF) : : : "cc"); } static void hardware_disable(void *garbage) { if (vmm_exclusive) { vmclear_local_loaded_vmcss(); kvm_cpu_vmxoff(); } write_cr4(read_cr4() & ~X86_CR4_VMXE); } static __init int adjust_vmx_controls(u32 ctl_min, u32 ctl_opt, u32 msr, u32 *result) { u32 vmx_msr_low, vmx_msr_high; u32 ctl = ctl_min | ctl_opt; rdmsr(msr, vmx_msr_low, vmx_msr_high); ctl &= vmx_msr_high; /* bit == 0 in high word ==> must be zero */ ctl |= vmx_msr_low; /* bit == 1 in low word ==> must be one */ /* Ensure minimum (required) set of control bits are supported. */ if (ctl_min & ~ctl) return -EIO; *result = ctl; return 0; } static __init bool allow_1_setting(u32 msr, u32 ctl) { u32 vmx_msr_low, vmx_msr_high; rdmsr(msr, vmx_msr_low, vmx_msr_high); return vmx_msr_high & ctl; } static __init int setup_vmcs_config(struct vmcs_config *vmcs_conf) { u32 vmx_msr_low, vmx_msr_high; u32 min, opt, min2, opt2; u32 _pin_based_exec_control = 0; u32 _cpu_based_exec_control = 0; u32 _cpu_based_2nd_exec_control = 0; u32 _vmexit_control = 0; u32 _vmentry_control = 0; min = CPU_BASED_HLT_EXITING | #ifdef CONFIG_X86_64 CPU_BASED_CR8_LOAD_EXITING | CPU_BASED_CR8_STORE_EXITING | #endif CPU_BASED_CR3_LOAD_EXITING | CPU_BASED_CR3_STORE_EXITING | CPU_BASED_USE_IO_BITMAPS | CPU_BASED_MOV_DR_EXITING | CPU_BASED_USE_TSC_OFFSETING | CPU_BASED_MWAIT_EXITING | CPU_BASED_MONITOR_EXITING | CPU_BASED_INVLPG_EXITING | CPU_BASED_RDPMC_EXITING; opt = CPU_BASED_TPR_SHADOW | CPU_BASED_USE_MSR_BITMAPS | CPU_BASED_ACTIVATE_SECONDARY_CONTROLS; if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PROCBASED_CTLS, &_cpu_based_exec_control) < 0) return -EIO; #ifdef CONFIG_X86_64 if ((_cpu_based_exec_control & CPU_BASED_TPR_SHADOW)) _cpu_based_exec_control &= ~CPU_BASED_CR8_LOAD_EXITING & ~CPU_BASED_CR8_STORE_EXITING; #endif if (_cpu_based_exec_control & CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) { min2 = 0; opt2 = SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES | SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE | SECONDARY_EXEC_WBINVD_EXITING | SECONDARY_EXEC_ENABLE_VPID | SECONDARY_EXEC_ENABLE_EPT | SECONDARY_EXEC_UNRESTRICTED_GUEST | SECONDARY_EXEC_PAUSE_LOOP_EXITING | SECONDARY_EXEC_RDTSCP | SECONDARY_EXEC_ENABLE_INVPCID | SECONDARY_EXEC_APIC_REGISTER_VIRT | SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY | SECONDARY_EXEC_SHADOW_VMCS; if (adjust_vmx_controls(min2, opt2, MSR_IA32_VMX_PROCBASED_CTLS2, &_cpu_based_2nd_exec_control) < 0) return -EIO; } #ifndef CONFIG_X86_64 if (!(_cpu_based_2nd_exec_control & SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)) _cpu_based_exec_control &= ~CPU_BASED_TPR_SHADOW; #endif if (!(_cpu_based_exec_control & CPU_BASED_TPR_SHADOW)) _cpu_based_2nd_exec_control &= ~( SECONDARY_EXEC_APIC_REGISTER_VIRT | SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE | SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY); if (_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_EPT) { /* CR3 accesses and invlpg don't need to cause VM Exits when EPT enabled */ _cpu_based_exec_control &= ~(CPU_BASED_CR3_LOAD_EXITING | CPU_BASED_CR3_STORE_EXITING | CPU_BASED_INVLPG_EXITING); rdmsr(MSR_IA32_VMX_EPT_VPID_CAP, vmx_capability.ept, vmx_capability.vpid); } min = 0; #ifdef CONFIG_X86_64 min |= VM_EXIT_HOST_ADDR_SPACE_SIZE; #endif opt = VM_EXIT_SAVE_IA32_PAT | VM_EXIT_LOAD_IA32_PAT | VM_EXIT_ACK_INTR_ON_EXIT; if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_EXIT_CTLS, &_vmexit_control) < 0) return -EIO; min = PIN_BASED_EXT_INTR_MASK | PIN_BASED_NMI_EXITING; opt = PIN_BASED_VIRTUAL_NMIS | PIN_BASED_POSTED_INTR; if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PINBASED_CTLS, &_pin_based_exec_control) < 0) return -EIO; if (!(_cpu_based_2nd_exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY) || !(_vmexit_control & VM_EXIT_ACK_INTR_ON_EXIT)) _pin_based_exec_control &= ~PIN_BASED_POSTED_INTR; min = 0; opt = VM_ENTRY_LOAD_IA32_PAT; if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_ENTRY_CTLS, &_vmentry_control) < 0) return -EIO; rdmsr(MSR_IA32_VMX_BASIC, vmx_msr_low, vmx_msr_high); /* IA-32 SDM Vol 3B: VMCS size is never greater than 4kB. */ if ((vmx_msr_high & 0x1fff) > PAGE_SIZE) return -EIO; #ifdef CONFIG_X86_64 /* IA-32 SDM Vol 3B: 64-bit CPUs always have VMX_BASIC_MSR[48]==0. */ if (vmx_msr_high & (1u<<16)) return -EIO; #endif /* Require Write-Back (WB) memory type for VMCS accesses. */ if (((vmx_msr_high >> 18) & 15) != 6) return -EIO; vmcs_conf->size = vmx_msr_high & 0x1fff; vmcs_conf->order = get_order(vmcs_config.size); vmcs_conf->revision_id = vmx_msr_low; vmcs_conf->pin_based_exec_ctrl = _pin_based_exec_control; vmcs_conf->cpu_based_exec_ctrl = _cpu_based_exec_control; vmcs_conf->cpu_based_2nd_exec_ctrl = _cpu_based_2nd_exec_control; vmcs_conf->vmexit_ctrl = _vmexit_control; vmcs_conf->vmentry_ctrl = _vmentry_control; cpu_has_load_ia32_efer = allow_1_setting(MSR_IA32_VMX_ENTRY_CTLS, VM_ENTRY_LOAD_IA32_EFER) && allow_1_setting(MSR_IA32_VMX_EXIT_CTLS, VM_EXIT_LOAD_IA32_EFER); cpu_has_load_perf_global_ctrl = allow_1_setting(MSR_IA32_VMX_ENTRY_CTLS, VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL) && allow_1_setting(MSR_IA32_VMX_EXIT_CTLS, VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL); /* * Some cpus support VM_ENTRY_(LOAD|SAVE)_IA32_PERF_GLOBAL_CTRL * but due to arrata below it can't be used. Workaround is to use * msr load mechanism to switch IA32_PERF_GLOBAL_CTRL. * * VM Exit May Incorrectly Clear IA32_PERF_GLOBAL_CTRL [34:32] * * AAK155 (model 26) * AAP115 (model 30) * AAT100 (model 37) * BC86,AAY89,BD102 (model 44) * BA97 (model 46) * */ if (cpu_has_load_perf_global_ctrl && boot_cpu_data.x86 == 0x6) { switch (boot_cpu_data.x86_model) { case 26: case 30: case 37: case 44: case 46: cpu_has_load_perf_global_ctrl = false; printk_once(KERN_WARNING"kvm: VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL " "does not work properly. Using workaround\n"); break; default: break; } } return 0; } static struct vmcs *alloc_vmcs_cpu(int cpu) { int node = cpu_to_node(cpu); struct page *pages; struct vmcs *vmcs; pages = alloc_pages_exact_node(node, GFP_KERNEL, vmcs_config.order); if (!pages) return NULL; vmcs = page_address(pages); memset(vmcs, 0, vmcs_config.size); vmcs->revision_id = vmcs_config.revision_id; /* vmcs revision id */ return vmcs; } static struct vmcs *alloc_vmcs(void) { return alloc_vmcs_cpu(raw_smp_processor_id()); } static void free_vmcs(struct vmcs *vmcs) { free_pages((unsigned long)vmcs, vmcs_config.order); } /* * Free a VMCS, but before that VMCLEAR it on the CPU where it was last loaded */ static void free_loaded_vmcs(struct loaded_vmcs *loaded_vmcs) { if (!loaded_vmcs->vmcs) return; loaded_vmcs_clear(loaded_vmcs); free_vmcs(loaded_vmcs->vmcs); loaded_vmcs->vmcs = NULL; } static void free_kvm_area(void) { int cpu; for_each_possible_cpu(cpu) { free_vmcs(per_cpu(vmxarea, cpu)); per_cpu(vmxarea, cpu) = NULL; } } static __init int alloc_kvm_area(void) { int cpu; for_each_possible_cpu(cpu) { struct vmcs *vmcs; vmcs = alloc_vmcs_cpu(cpu); if (!vmcs) { free_kvm_area(); return -ENOMEM; } per_cpu(vmxarea, cpu) = vmcs; } return 0; } static __init int hardware_setup(void) { if (setup_vmcs_config(&vmcs_config) < 0) return -EIO; if (boot_cpu_has(X86_FEATURE_NX)) kvm_enable_efer_bits(EFER_NX); if (!cpu_has_vmx_vpid()) enable_vpid = 0; if (!cpu_has_vmx_shadow_vmcs()) enable_shadow_vmcs = 0; if (!cpu_has_vmx_ept() || !cpu_has_vmx_ept_4levels()) { enable_ept = 0; enable_unrestricted_guest = 0; enable_ept_ad_bits = 0; } if (!cpu_has_vmx_ept_ad_bits()) enable_ept_ad_bits = 0; if (!cpu_has_vmx_unrestricted_guest()) enable_unrestricted_guest = 0; if (!cpu_has_vmx_flexpriority()) flexpriority_enabled = 0; if (!cpu_has_vmx_tpr_shadow()) kvm_x86_ops->update_cr8_intercept = NULL; if (enable_ept && !cpu_has_vmx_ept_2m_page()) kvm_disable_largepages(); if (!cpu_has_vmx_ple()) ple_gap = 0; if (!cpu_has_vmx_apicv()) enable_apicv = 0; if (enable_apicv) kvm_x86_ops->update_cr8_intercept = NULL; else { kvm_x86_ops->hwapic_irr_update = NULL; kvm_x86_ops->deliver_posted_interrupt = NULL; kvm_x86_ops->sync_pir_to_irr = vmx_sync_pir_to_irr_dummy; } if (nested) nested_vmx_setup_ctls_msrs(); return alloc_kvm_area(); } static __exit void hardware_unsetup(void) { free_kvm_area(); } static bool emulation_required(struct kvm_vcpu *vcpu) { return emulate_invalid_guest_state && !guest_state_valid(vcpu); } static void fix_pmode_seg(struct kvm_vcpu *vcpu, int seg, struct kvm_segment *save) { if (!emulate_invalid_guest_state) { /* * CS and SS RPL should be equal during guest entry according * to VMX spec, but in reality it is not always so. Since vcpu * is in the middle of the transition from real mode to * protected mode it is safe to assume that RPL 0 is a good * default value. */ if (seg == VCPU_SREG_CS || seg == VCPU_SREG_SS) save->selector &= ~SELECTOR_RPL_MASK; save->dpl = save->selector & SELECTOR_RPL_MASK; save->s = 1; } vmx_set_segment(vcpu, save, seg); } static void enter_pmode(struct kvm_vcpu *vcpu) { unsigned long flags; struct vcpu_vmx *vmx = to_vmx(vcpu); /* * Update real mode segment cache. It may be not up-to-date if sement * register was written while vcpu was in a guest mode. */ vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES); vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS); vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS); vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS); vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS); vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS); vmx->rmode.vm86_active = 0; vmx_segment_cache_clear(vmx); vmx_set_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR); flags = vmcs_readl(GUEST_RFLAGS); flags &= RMODE_GUEST_OWNED_EFLAGS_BITS; flags |= vmx->rmode.save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS; vmcs_writel(GUEST_RFLAGS, flags); vmcs_writel(GUEST_CR4, (vmcs_readl(GUEST_CR4) & ~X86_CR4_VME) | (vmcs_readl(CR4_READ_SHADOW) & X86_CR4_VME)); update_exception_bitmap(vcpu); fix_pmode_seg(vcpu, VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]); fix_pmode_seg(vcpu, VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]); fix_pmode_seg(vcpu, VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]); fix_pmode_seg(vcpu, VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]); fix_pmode_seg(vcpu, VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]); fix_pmode_seg(vcpu, VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]); /* CPL is always 0 when CPU enters protected mode */ __set_bit(VCPU_EXREG_CPL, (ulong *)&vcpu->arch.regs_avail); vmx->cpl = 0; } static void fix_rmode_seg(int seg, struct kvm_segment *save) { const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg]; struct kvm_segment var = *save; var.dpl = 0x3; if (seg == VCPU_SREG_CS) var.type = 0x3; if (!emulate_invalid_guest_state) { var.selector = var.base >> 4; var.base = var.base & 0xffff0; var.limit = 0xffff; var.g = 0; var.db = 0; var.present = 1; var.s = 1; var.l = 0; var.unusable = 0; var.type = 0x3; var.avl = 0; if (save->base & 0xf) printk_once(KERN_WARNING "kvm: segment base is not " "paragraph aligned when entering " "protected mode (seg=%d)", seg); } vmcs_write16(sf->selector, var.selector); vmcs_write32(sf->base, var.base); vmcs_write32(sf->limit, var.limit); vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(&var)); } static void enter_rmode(struct kvm_vcpu *vcpu) { unsigned long flags; struct vcpu_vmx *vmx = to_vmx(vcpu); vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR); vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES); vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS); vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS); vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS); vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS); vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS); vmx->rmode.vm86_active = 1; /* * Very old userspace does not call KVM_SET_TSS_ADDR before entering * vcpu. Warn the user that an update is overdue. */ if (!vcpu->kvm->arch.tss_addr) printk_once(KERN_WARNING "kvm: KVM_SET_TSS_ADDR need to be " "called before entering vcpu\n"); vmx_segment_cache_clear(vmx); vmcs_writel(GUEST_TR_BASE, vcpu->kvm->arch.tss_addr); vmcs_write32(GUEST_TR_LIMIT, RMODE_TSS_SIZE - 1); vmcs_write32(GUEST_TR_AR_BYTES, 0x008b); flags = vmcs_readl(GUEST_RFLAGS); vmx->rmode.save_rflags = flags; flags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM; vmcs_writel(GUEST_RFLAGS, flags); vmcs_writel(GUEST_CR4, vmcs_readl(GUEST_CR4) | X86_CR4_VME); update_exception_bitmap(vcpu); fix_rmode_seg(VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]); fix_rmode_seg(VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]); fix_rmode_seg(VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]); fix_rmode_seg(VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]); fix_rmode_seg(VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]); fix_rmode_seg(VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]); kvm_mmu_reset_context(vcpu); } static void vmx_set_efer(struct kvm_vcpu *vcpu, u64 efer) { struct vcpu_vmx *vmx = to_vmx(vcpu); struct shared_msr_entry *msr = find_msr_entry(vmx, MSR_EFER); if (!msr) return; /* * Force kernel_gs_base reloading before EFER changes, as control * of this msr depends on is_long_mode(). */ vmx_load_host_state(to_vmx(vcpu)); vcpu->arch.efer = efer; if (efer & EFER_LMA) { vmcs_write32(VM_ENTRY_CONTROLS, vmcs_read32(VM_ENTRY_CONTROLS) | VM_ENTRY_IA32E_MODE); msr->data = efer; } else { vmcs_write32(VM_ENTRY_CONTROLS, vmcs_read32(VM_ENTRY_CONTROLS) & ~VM_ENTRY_IA32E_MODE); msr->data = efer & ~EFER_LME; } setup_msrs(vmx); } #ifdef CONFIG_X86_64 static void enter_lmode(struct kvm_vcpu *vcpu) { u32 guest_tr_ar; vmx_segment_cache_clear(to_vmx(vcpu)); guest_tr_ar = vmcs_read32(GUEST_TR_AR_BYTES); if ((guest_tr_ar & AR_TYPE_MASK) != AR_TYPE_BUSY_64_TSS) { pr_debug_ratelimited("%s: tss fixup for long mode. \n", __func__); vmcs_write32(GUEST_TR_AR_BYTES, (guest_tr_ar & ~AR_TYPE_MASK) | AR_TYPE_BUSY_64_TSS); } vmx_set_efer(vcpu, vcpu->arch.efer | EFER_LMA); } static void exit_lmode(struct kvm_vcpu *vcpu) { vmcs_write32(VM_ENTRY_CONTROLS, vmcs_read32(VM_ENTRY_CONTROLS) & ~VM_ENTRY_IA32E_MODE); vmx_set_efer(vcpu, vcpu->arch.efer & ~EFER_LMA); } #endif static void vmx_flush_tlb(struct kvm_vcpu *vcpu) { vpid_sync_context(to_vmx(vcpu)); if (enable_ept) { if (!VALID_PAGE(vcpu->arch.mmu.root_hpa)) return; ept_sync_context(construct_eptp(vcpu->arch.mmu.root_hpa)); } } static void vmx_decache_cr0_guest_bits(struct kvm_vcpu *vcpu) { ulong cr0_guest_owned_bits = vcpu->arch.cr0_guest_owned_bits; vcpu->arch.cr0 &= ~cr0_guest_owned_bits; vcpu->arch.cr0 |= vmcs_readl(GUEST_CR0) & cr0_guest_owned_bits; } static void vmx_decache_cr3(struct kvm_vcpu *vcpu) { if (enable_ept && is_paging(vcpu)) vcpu->arch.cr3 = vmcs_readl(GUEST_CR3); __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail); } static void vmx_decache_cr4_guest_bits(struct kvm_vcpu *vcpu) { ulong cr4_guest_owned_bits = vcpu->arch.cr4_guest_owned_bits; vcpu->arch.cr4 &= ~cr4_guest_owned_bits; vcpu->arch.cr4 |= vmcs_readl(GUEST_CR4) & cr4_guest_owned_bits; } static void ept_load_pdptrs(struct kvm_vcpu *vcpu) { if (!test_bit(VCPU_EXREG_PDPTR, (unsigned long *)&vcpu->arch.regs_dirty)) return; if (is_paging(vcpu) && is_pae(vcpu) && !is_long_mode(vcpu)) { vmcs_write64(GUEST_PDPTR0, vcpu->arch.mmu.pdptrs[0]); vmcs_write64(GUEST_PDPTR1, vcpu->arch.mmu.pdptrs[1]); vmcs_write64(GUEST_PDPTR2, vcpu->arch.mmu.pdptrs[2]); vmcs_write64(GUEST_PDPTR3, vcpu->arch.mmu.pdptrs[3]); } } static void ept_save_pdptrs(struct kvm_vcpu *vcpu) { if (is_paging(vcpu) && is_pae(vcpu) && !is_long_mode(vcpu)) { vcpu->arch.mmu.pdptrs[0] = vmcs_read64(GUEST_PDPTR0); vcpu->arch.mmu.pdptrs[1] = vmcs_read64(GUEST_PDPTR1); vcpu->arch.mmu.pdptrs[2] = vmcs_read64(GUEST_PDPTR2); vcpu->arch.mmu.pdptrs[3] = vmcs_read64(GUEST_PDPTR3); } __set_bit(VCPU_EXREG_PDPTR, (unsigned long *)&vcpu->arch.regs_avail); __set_bit(VCPU_EXREG_PDPTR, (unsigned long *)&vcpu->arch.regs_dirty); } static int vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4); static void ept_update_paging_mode_cr0(unsigned long *hw_cr0, unsigned long cr0, struct kvm_vcpu *vcpu) { if (!test_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail)) vmx_decache_cr3(vcpu); if (!(cr0 & X86_CR0_PG)) { /* From paging/starting to nonpaging */ vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, vmcs_read32(CPU_BASED_VM_EXEC_CONTROL) | (CPU_BASED_CR3_LOAD_EXITING | CPU_BASED_CR3_STORE_EXITING)); vcpu->arch.cr0 = cr0; vmx_set_cr4(vcpu, kvm_read_cr4(vcpu)); } else if (!is_paging(vcpu)) { /* From nonpaging to paging */ vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, vmcs_read32(CPU_BASED_VM_EXEC_CONTROL) & ~(CPU_BASED_CR3_LOAD_EXITING | CPU_BASED_CR3_STORE_EXITING)); vcpu->arch.cr0 = cr0; vmx_set_cr4(vcpu, kvm_read_cr4(vcpu)); } if (!(cr0 & X86_CR0_WP)) *hw_cr0 &= ~X86_CR0_WP; } static void vmx_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0) { struct vcpu_vmx *vmx = to_vmx(vcpu); unsigned long hw_cr0; hw_cr0 = (cr0 & ~KVM_GUEST_CR0_MASK); if (enable_unrestricted_guest) hw_cr0 |= KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST; else { hw_cr0 |= KVM_VM_CR0_ALWAYS_ON; if (vmx->rmode.vm86_active && (cr0 & X86_CR0_PE)) enter_pmode(vcpu); if (!vmx->rmode.vm86_active && !(cr0 & X86_CR0_PE)) enter_rmode(vcpu); } #ifdef CONFIG_X86_64 if (vcpu->arch.efer & EFER_LME) { if (!is_paging(vcpu) && (cr0 & X86_CR0_PG)) enter_lmode(vcpu); if (is_paging(vcpu) && !(cr0 & X86_CR0_PG)) exit_lmode(vcpu); } #endif if (enable_ept) ept_update_paging_mode_cr0(&hw_cr0, cr0, vcpu); if (!vcpu->fpu_active) hw_cr0 |= X86_CR0_TS | X86_CR0_MP; vmcs_writel(CR0_READ_SHADOW, cr0); vmcs_writel(GUEST_CR0, hw_cr0); vcpu->arch.cr0 = cr0; /* depends on vcpu->arch.cr0 to be set to a new value */ vmx->emulation_required = emulation_required(vcpu); } static u64 construct_eptp(unsigned long root_hpa) { u64 eptp; /* TODO write the value reading from MSR */ eptp = VMX_EPT_DEFAULT_MT | VMX_EPT_DEFAULT_GAW << VMX_EPT_GAW_EPTP_SHIFT; if (enable_ept_ad_bits) eptp |= VMX_EPT_AD_ENABLE_BIT; eptp |= (root_hpa & PAGE_MASK); return eptp; } static void vmx_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3) { unsigned long guest_cr3; u64 eptp; guest_cr3 = cr3; if (enable_ept) { eptp = construct_eptp(cr3); vmcs_write64(EPT_POINTER, eptp); guest_cr3 = is_paging(vcpu) ? kvm_read_cr3(vcpu) : vcpu->kvm->arch.ept_identity_map_addr; ept_load_pdptrs(vcpu); } vmx_flush_tlb(vcpu); vmcs_writel(GUEST_CR3, guest_cr3); } static int vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4) { unsigned long hw_cr4 = cr4 | (to_vmx(vcpu)->rmode.vm86_active ? KVM_RMODE_VM_CR4_ALWAYS_ON : KVM_PMODE_VM_CR4_ALWAYS_ON); if (cr4 & X86_CR4_VMXE) { /* * To use VMXON (and later other VMX instructions), a guest * must first be able to turn on cr4.VMXE (see handle_vmon()). * So basically the check on whether to allow nested VMX * is here. */ if (!nested_vmx_allowed(vcpu)) return 1; } if (to_vmx(vcpu)->nested.vmxon && ((cr4 & VMXON_CR4_ALWAYSON) != VMXON_CR4_ALWAYSON)) return 1; vcpu->arch.cr4 = cr4; if (enable_ept) { if (!is_paging(vcpu)) { hw_cr4 &= ~X86_CR4_PAE; hw_cr4 |= X86_CR4_PSE; /* * SMEP is disabled if CPU is in non-paging mode in * hardware. However KVM always uses paging mode to * emulate guest non-paging mode with TDP. * To emulate this behavior, SMEP needs to be manually * disabled when guest switches to non-paging mode. */ hw_cr4 &= ~X86_CR4_SMEP; } else if (!(cr4 & X86_CR4_PAE)) { hw_cr4 &= ~X86_CR4_PAE; } } vmcs_writel(CR4_READ_SHADOW, cr4); vmcs_writel(GUEST_CR4, hw_cr4); return 0; } static void vmx_get_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var, int seg) { struct vcpu_vmx *vmx = to_vmx(vcpu); u32 ar; if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) { *var = vmx->rmode.segs[seg]; if (seg == VCPU_SREG_TR || var->selector == vmx_read_guest_seg_selector(vmx, seg)) return; var->base = vmx_read_guest_seg_base(vmx, seg); var->selector = vmx_read_guest_seg_selector(vmx, seg); return; } var->base = vmx_read_guest_seg_base(vmx, seg); var->limit = vmx_read_guest_seg_limit(vmx, seg); var->selector = vmx_read_guest_seg_selector(vmx, seg); ar = vmx_read_guest_seg_ar(vmx, seg); var->unusable = (ar >> 16) & 1; var->type = ar & 15; var->s = (ar >> 4) & 1; var->dpl = (ar >> 5) & 3; /* * Some userspaces do not preserve unusable property. Since usable * segment has to be present according to VMX spec we can use present * property to amend userspace bug by making unusable segment always * nonpresent. vmx_segment_access_rights() already marks nonpresent * segment as unusable. */ var->present = !var->unusable; var->avl = (ar >> 12) & 1; var->l = (ar >> 13) & 1; var->db = (ar >> 14) & 1; var->g = (ar >> 15) & 1; } static u64 vmx_get_segment_base(struct kvm_vcpu *vcpu, int seg) { struct kvm_segment s; if (to_vmx(vcpu)->rmode.vm86_active) { vmx_get_segment(vcpu, &s, seg); return s.base; } return vmx_read_guest_seg_base(to_vmx(vcpu), seg); } static int vmx_get_cpl(struct kvm_vcpu *vcpu) { struct vcpu_vmx *vmx = to_vmx(vcpu); if (!is_protmode(vcpu)) return 0; if (!is_long_mode(vcpu) && (kvm_get_rflags(vcpu) & X86_EFLAGS_VM)) /* if virtual 8086 */ return 3; if (!test_bit(VCPU_EXREG_CPL, (ulong *)&vcpu->arch.regs_avail)) { __set_bit(VCPU_EXREG_CPL, (ulong *)&vcpu->arch.regs_avail); vmx->cpl = vmx_read_guest_seg_selector(vmx, VCPU_SREG_CS) & 3; } return vmx->cpl; } static u32 vmx_segment_access_rights(struct kvm_segment *var) { u32 ar; if (var->unusable || !var->present) ar = 1 << 16; else { ar = var->type & 15; ar |= (var->s & 1) << 4; ar |= (var->dpl & 3) << 5; ar |= (var->present & 1) << 7; ar |= (var->avl & 1) << 12; ar |= (var->l & 1) << 13; ar |= (var->db & 1) << 14; ar |= (var->g & 1) << 15; } return ar; } static void vmx_set_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var, int seg) { struct vcpu_vmx *vmx = to_vmx(vcpu); const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg]; vmx_segment_cache_clear(vmx); if (seg == VCPU_SREG_CS) __clear_bit(VCPU_EXREG_CPL, (ulong *)&vcpu->arch.regs_avail); if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) { vmx->rmode.segs[seg] = *var; if (seg == VCPU_SREG_TR) vmcs_write16(sf->selector, var->selector); else if (var->s) fix_rmode_seg(seg, &vmx->rmode.segs[seg]); goto out; } vmcs_writel(sf->base, var->base); vmcs_write32(sf->limit, var->limit); vmcs_write16(sf->selector, var->selector); /* * Fix the "Accessed" bit in AR field of segment registers for older * qemu binaries. * IA32 arch specifies that at the time of processor reset the * "Accessed" bit in the AR field of segment registers is 1. And qemu * is setting it to 0 in the userland code. This causes invalid guest * state vmexit when "unrestricted guest" mode is turned on. * Fix for this setup issue in cpu_reset is being pushed in the qemu * tree. Newer qemu binaries with that qemu fix would not need this * kvm hack. */ if (enable_unrestricted_guest && (seg != VCPU_SREG_LDTR)) var->type |= 0x1; /* Accessed */ vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(var)); out: vmx->emulation_required |= emulation_required(vcpu); } static void vmx_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l) { u32 ar = vmx_read_guest_seg_ar(to_vmx(vcpu), VCPU_SREG_CS); *db = (ar >> 14) & 1; *l = (ar >> 13) & 1; } static void vmx_get_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt) { dt->size = vmcs_read32(GUEST_IDTR_LIMIT); dt->address = vmcs_readl(GUEST_IDTR_BASE); } static void vmx_set_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt) { vmcs_write32(GUEST_IDTR_LIMIT, dt->size); vmcs_writel(GUEST_IDTR_BASE, dt->address); } static void vmx_get_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt) { dt->size = vmcs_read32(GUEST_GDTR_LIMIT); dt->address = vmcs_readl(GUEST_GDTR_BASE); } static void vmx_set_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt) { vmcs_write32(GUEST_GDTR_LIMIT, dt->size); vmcs_writel(GUEST_GDTR_BASE, dt->address); } static bool rmode_segment_valid(struct kvm_vcpu *vcpu, int seg) { struct kvm_segment var; u32 ar; vmx_get_segment(vcpu, &var, seg); var.dpl = 0x3; if (seg == VCPU_SREG_CS) var.type = 0x3; ar = vmx_segment_access_rights(&var); if (var.base != (var.selector << 4)) return false; if (var.limit != 0xffff) return false; if (ar != 0xf3) return false; return true; } static bool code_segment_valid(struct kvm_vcpu *vcpu) { struct kvm_segment cs; unsigned int cs_rpl; vmx_get_segment(vcpu, &cs, VCPU_SREG_CS); cs_rpl = cs.selector & SELECTOR_RPL_MASK; if (cs.unusable) return false; if (~cs.type & (AR_TYPE_CODE_MASK|AR_TYPE_ACCESSES_MASK)) return false; if (!cs.s) return false; if (cs.type & AR_TYPE_WRITEABLE_MASK) { if (cs.dpl > cs_rpl) return false; } else { if (cs.dpl != cs_rpl) return false; } if (!cs.present) return false; /* TODO: Add Reserved field check, this'll require a new member in the kvm_segment_field structure */ return true; } static bool stack_segment_valid(struct kvm_vcpu *vcpu) { struct kvm_segment ss; unsigned int ss_rpl; vmx_get_segment(vcpu, &ss, VCPU_SREG_SS); ss_rpl = ss.selector & SELECTOR_RPL_MASK; if (ss.unusable) return true; if (ss.type != 3 && ss.type != 7) return false; if (!ss.s) return false; if (ss.dpl != ss_rpl) /* DPL != RPL */ return false; if (!ss.present) return false; return true; } static bool data_segment_valid(struct kvm_vcpu *vcpu, int seg) { struct kvm_segment var; unsigned int rpl; vmx_get_segment(vcpu, &var, seg); rpl = var.selector & SELECTOR_RPL_MASK; if (var.unusable) return true; if (!var.s) return false; if (!var.present) return false; if (~var.type & (AR_TYPE_CODE_MASK|AR_TYPE_WRITEABLE_MASK)) { if (var.dpl < rpl) /* DPL < RPL */ return false; } /* TODO: Add other members to kvm_segment_field to allow checking for other access * rights flags */ return true; } static bool tr_valid(struct kvm_vcpu *vcpu) { struct kvm_segment tr; vmx_get_segment(vcpu, &tr, VCPU_SREG_TR); if (tr.unusable) return false; if (tr.selector & SELECTOR_TI_MASK) /* TI = 1 */ return false; if (tr.type != 3 && tr.type != 11) /* TODO: Check if guest is in IA32e mode */ return false; if (!tr.present) return false; return true; } static bool ldtr_valid(struct kvm_vcpu *vcpu) { struct kvm_segment ldtr; vmx_get_segment(vcpu, &ldtr, VCPU_SREG_LDTR); if (ldtr.unusable) return true; if (ldtr.selector & SELECTOR_TI_MASK) /* TI = 1 */ return false; if (ldtr.type != 2) return false; if (!ldtr.present) return false; return true; } static bool cs_ss_rpl_check(struct kvm_vcpu *vcpu) { struct kvm_segment cs, ss; vmx_get_segment(vcpu, &cs, VCPU_SREG_CS); vmx_get_segment(vcpu, &ss, VCPU_SREG_SS); return ((cs.selector & SELECTOR_RPL_MASK) == (ss.selector & SELECTOR_RPL_MASK)); } /* * Check if guest state is valid. Returns true if valid, false if * not. * We assume that registers are always usable */ static bool guest_state_valid(struct kvm_vcpu *vcpu) { if (enable_unrestricted_guest) return true; /* real mode guest state checks */ if (!is_protmode(vcpu) || (vmx_get_rflags(vcpu) & X86_EFLAGS_VM)) { if (!rmode_segment_valid(vcpu, VCPU_SREG_CS)) return false; if (!rmode_segment_valid(vcpu, VCPU_SREG_SS)) return false; if (!rmode_segment_valid(vcpu, VCPU_SREG_DS)) return false; if (!rmode_segment_valid(vcpu, VCPU_SREG_ES)) return false; if (!rmode_segment_valid(vcpu, VCPU_SREG_FS)) return false; if (!rmode_segment_valid(vcpu, VCPU_SREG_GS)) return false; } else { /* protected mode guest state checks */ if (!cs_ss_rpl_check(vcpu)) return false; if (!code_segment_valid(vcpu)) return false; if (!stack_segment_valid(vcpu)) return false; if (!data_segment_valid(vcpu, VCPU_SREG_DS)) return false; if (!data_segment_valid(vcpu, VCPU_SREG_ES)) return false; if (!data_segment_valid(vcpu, VCPU_SREG_FS)) return false; if (!data_segment_valid(vcpu, VCPU_SREG_GS)) return false; if (!tr_valid(vcpu)) return false; if (!ldtr_valid(vcpu)) return false; } /* TODO: * - Add checks on RIP * - Add checks on RFLAGS */ return true; } static int init_rmode_tss(struct kvm *kvm) { gfn_t fn; u16 data = 0; int r, idx, ret = 0; idx = srcu_read_lock(&kvm->srcu); fn = kvm->arch.tss_addr >> PAGE_SHIFT; r = kvm_clear_guest_page(kvm, fn, 0, PAGE_SIZE); if (r < 0) goto out; data = TSS_BASE_SIZE + TSS_REDIRECTION_SIZE; r = kvm_write_guest_page(kvm, fn++, &data, TSS_IOPB_BASE_OFFSET, sizeof(u16)); if (r < 0) goto out; r = kvm_clear_guest_page(kvm, fn++, 0, PAGE_SIZE); if (r < 0) goto out; r = kvm_clear_guest_page(kvm, fn, 0, PAGE_SIZE); if (r < 0) goto out; data = ~0; r = kvm_write_guest_page(kvm, fn, &data, RMODE_TSS_SIZE - 2 * PAGE_SIZE - 1, sizeof(u8)); if (r < 0) goto out; ret = 1; out: srcu_read_unlock(&kvm->srcu, idx); return ret; } static int init_rmode_identity_map(struct kvm *kvm) { int i, idx, r, ret; pfn_t identity_map_pfn; u32 tmp; if (!enable_ept) return 1; if (unlikely(!kvm->arch.ept_identity_pagetable)) { printk(KERN_ERR "EPT: identity-mapping pagetable " "haven't been allocated!\n"); return 0; } if (likely(kvm->arch.ept_identity_pagetable_done)) return 1; ret = 0; identity_map_pfn = kvm->arch.ept_identity_map_addr >> PAGE_SHIFT; idx = srcu_read_lock(&kvm->srcu); r = kvm_clear_guest_page(kvm, identity_map_pfn, 0, PAGE_SIZE); if (r < 0) goto out; /* Set up identity-mapping pagetable for EPT in real mode */ for (i = 0; i < PT32_ENT_PER_PAGE; i++) { tmp = (i << 22) + (_PAGE_PRESENT | _PAGE_RW | _PAGE_USER | _PAGE_ACCESSED | _PAGE_DIRTY | _PAGE_PSE); r = kvm_write_guest_page(kvm, identity_map_pfn, &tmp, i * sizeof(tmp), sizeof(tmp)); if (r < 0) goto out; } kvm->arch.ept_identity_pagetable_done = true; ret = 1; out: srcu_read_unlock(&kvm->srcu, idx); return ret; } static void seg_setup(int seg) { const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg]; unsigned int ar; vmcs_write16(sf->selector, 0); vmcs_writel(sf->base, 0); vmcs_write32(sf->limit, 0xffff); ar = 0x93; if (seg == VCPU_SREG_CS) ar |= 0x08; /* code segment */ vmcs_write32(sf->ar_bytes, ar); } static int alloc_apic_access_page(struct kvm *kvm) { struct page *page; struct kvm_userspace_memory_region kvm_userspace_mem; int r = 0; mutex_lock(&kvm->slots_lock); if (kvm->arch.apic_access_page) goto out; kvm_userspace_mem.slot = APIC_ACCESS_PAGE_PRIVATE_MEMSLOT; kvm_userspace_mem.flags = 0; kvm_userspace_mem.guest_phys_addr = 0xfee00000ULL; kvm_userspace_mem.memory_size = PAGE_SIZE; r = __kvm_set_memory_region(kvm, &kvm_userspace_mem); if (r) goto out; page = gfn_to_page(kvm, 0xfee00); if (is_error_page(page)) { r = -EFAULT; goto out; } kvm->arch.apic_access_page = page; out: mutex_unlock(&kvm->slots_lock); return r; } static int alloc_identity_pagetable(struct kvm *kvm) { struct page *page; struct kvm_userspace_memory_region kvm_userspace_mem; int r = 0; mutex_lock(&kvm->slots_lock); if (kvm->arch.ept_identity_pagetable) goto out; kvm_userspace_mem.slot = IDENTITY_PAGETABLE_PRIVATE_MEMSLOT; kvm_userspace_mem.flags = 0; kvm_userspace_mem.guest_phys_addr = kvm->arch.ept_identity_map_addr; kvm_userspace_mem.memory_size = PAGE_SIZE; r = __kvm_set_memory_region(kvm, &kvm_userspace_mem); if (r) goto out; page = gfn_to_page(kvm, kvm->arch.ept_identity_map_addr >> PAGE_SHIFT); if (is_error_page(page)) { r = -EFAULT; goto out; } kvm->arch.ept_identity_pagetable = page; out: mutex_unlock(&kvm->slots_lock); return r; } static void allocate_vpid(struct vcpu_vmx *vmx) { int vpid; vmx->vpid = 0; if (!enable_vpid) return; spin_lock(&vmx_vpid_lock); vpid = find_first_zero_bit(vmx_vpid_bitmap, VMX_NR_VPIDS); if (vpid < VMX_NR_VPIDS) { vmx->vpid = vpid; __set_bit(vpid, vmx_vpid_bitmap); } spin_unlock(&vmx_vpid_lock); } static void free_vpid(struct vcpu_vmx *vmx) { if (!enable_vpid) return; spin_lock(&vmx_vpid_lock); if (vmx->vpid != 0) __clear_bit(vmx->vpid, vmx_vpid_bitmap); spin_unlock(&vmx_vpid_lock); } #define MSR_TYPE_R 1 #define MSR_TYPE_W 2 static void __vmx_disable_intercept_for_msr(unsigned long *msr_bitmap, u32 msr, int type) { int f = sizeof(unsigned long); if (!cpu_has_vmx_msr_bitmap()) return; /* * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals * have the write-low and read-high bitmap offsets the wrong way round. * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff. */ if (msr <= 0x1fff) { if (type & MSR_TYPE_R) /* read-low */ __clear_bit(msr, msr_bitmap + 0x000 / f); if (type & MSR_TYPE_W) /* write-low */ __clear_bit(msr, msr_bitmap + 0x800 / f); } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) { msr &= 0x1fff; if (type & MSR_TYPE_R) /* read-high */ __clear_bit(msr, msr_bitmap + 0x400 / f); if (type & MSR_TYPE_W) /* write-high */ __clear_bit(msr, msr_bitmap + 0xc00 / f); } } static void __vmx_enable_intercept_for_msr(unsigned long *msr_bitmap, u32 msr, int type) { int f = sizeof(unsigned long); if (!cpu_has_vmx_msr_bitmap()) return; /* * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals * have the write-low and read-high bitmap offsets the wrong way round. * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff. */ if (msr <= 0x1fff) { if (type & MSR_TYPE_R) /* read-low */ __set_bit(msr, msr_bitmap + 0x000 / f); if (type & MSR_TYPE_W) /* write-low */ __set_bit(msr, msr_bitmap + 0x800 / f); } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) { msr &= 0x1fff; if (type & MSR_TYPE_R) /* read-high */ __set_bit(msr, msr_bitmap + 0x400 / f); if (type & MSR_TYPE_W) /* write-high */ __set_bit(msr, msr_bitmap + 0xc00 / f); } } static void vmx_disable_intercept_for_msr(u32 msr, bool longmode_only) { if (!longmode_only) __vmx_disable_intercept_for_msr(vmx_msr_bitmap_legacy, msr, MSR_TYPE_R | MSR_TYPE_W); __vmx_disable_intercept_for_msr(vmx_msr_bitmap_longmode, msr, MSR_TYPE_R | MSR_TYPE_W); } static void vmx_enable_intercept_msr_read_x2apic(u32 msr) { __vmx_enable_intercept_for_msr(vmx_msr_bitmap_legacy_x2apic, msr, MSR_TYPE_R); __vmx_enable_intercept_for_msr(vmx_msr_bitmap_longmode_x2apic, msr, MSR_TYPE_R); } static void vmx_disable_intercept_msr_read_x2apic(u32 msr) { __vmx_disable_intercept_for_msr(vmx_msr_bitmap_legacy_x2apic, msr, MSR_TYPE_R); __vmx_disable_intercept_for_msr(vmx_msr_bitmap_longmode_x2apic, msr, MSR_TYPE_R); } static void vmx_disable_intercept_msr_write_x2apic(u32 msr) { __vmx_disable_intercept_for_msr(vmx_msr_bitmap_legacy_x2apic, msr, MSR_TYPE_W); __vmx_disable_intercept_for_msr(vmx_msr_bitmap_longmode_x2apic, msr, MSR_TYPE_W); } static int vmx_vm_has_apicv(struct kvm *kvm) { return enable_apicv && irqchip_in_kernel(kvm); } /* * Send interrupt to vcpu via posted interrupt way. * 1. If target vcpu is running(non-root mode), send posted interrupt * notification to vcpu and hardware will sync PIR to vIRR atomically. * 2. If target vcpu isn't running(root mode), kick it to pick up the * interrupt from PIR in next vmentry. */ static void vmx_deliver_posted_interrupt(struct kvm_vcpu *vcpu, int vector) { struct vcpu_vmx *vmx = to_vmx(vcpu); int r; if (pi_test_and_set_pir(vector, &vmx->pi_desc)) return; r = pi_test_and_set_on(&vmx->pi_desc); kvm_make_request(KVM_REQ_EVENT, vcpu); #ifdef CONFIG_SMP if (!r && (vcpu->mode == IN_GUEST_MODE)) apic->send_IPI_mask(get_cpu_mask(vcpu->cpu), POSTED_INTR_VECTOR); else #endif kvm_vcpu_kick(vcpu); } static void vmx_sync_pir_to_irr(struct kvm_vcpu *vcpu) { struct vcpu_vmx *vmx = to_vmx(vcpu); if (!pi_test_and_clear_on(&vmx->pi_desc)) return; kvm_apic_update_irr(vcpu, vmx->pi_desc.pir); } static void vmx_sync_pir_to_irr_dummy(struct kvm_vcpu *vcpu) { return; } /* * Set up the vmcs's constant host-state fields, i.e., host-state fields that * will not change in the lifetime of the guest. * Note that host-state that does change is set elsewhere. E.g., host-state * that is set differently for each CPU is set in vmx_vcpu_load(), not here. */ static void vmx_set_constant_host_state(struct vcpu_vmx *vmx) { u32 low32, high32; unsigned long tmpl; struct desc_ptr dt; vmcs_writel(HOST_CR0, read_cr0() & ~X86_CR0_TS); /* 22.2.3 */ vmcs_writel(HOST_CR4, read_cr4()); /* 22.2.3, 22.2.5 */ vmcs_writel(HOST_CR3, read_cr3()); /* 22.2.3 FIXME: shadow tables */ vmcs_write16(HOST_CS_SELECTOR, __KERNEL_CS); /* 22.2.4 */ #ifdef CONFIG_X86_64 /* * Load null selectors, so we can avoid reloading them in * __vmx_load_host_state(), in case userspace uses the null selectors * too (the expected case). */ vmcs_write16(HOST_DS_SELECTOR, 0); vmcs_write16(HOST_ES_SELECTOR, 0); #else vmcs_write16(HOST_DS_SELECTOR, __KERNEL_DS); /* 22.2.4 */ vmcs_write16(HOST_ES_SELECTOR, __KERNEL_DS); /* 22.2.4 */ #endif vmcs_write16(HOST_SS_SELECTOR, __KERNEL_DS); /* 22.2.4 */ vmcs_write16(HOST_TR_SELECTOR, GDT_ENTRY_TSS*8); /* 22.2.4 */ native_store_idt(&dt); vmcs_writel(HOST_IDTR_BASE, dt.address); /* 22.2.4 */ vmx->host_idt_base = dt.address; vmcs_writel(HOST_RIP, vmx_return); /* 22.2.5 */ rdmsr(MSR_IA32_SYSENTER_CS, low32, high32); vmcs_write32(HOST_IA32_SYSENTER_CS, low32); rdmsrl(MSR_IA32_SYSENTER_EIP, tmpl); vmcs_writel(HOST_IA32_SYSENTER_EIP, tmpl); /* 22.2.3 */ if (vmcs_config.vmexit_ctrl & VM_EXIT_LOAD_IA32_PAT) { rdmsr(MSR_IA32_CR_PAT, low32, high32); vmcs_write64(HOST_IA32_PAT, low32 | ((u64) high32 << 32)); } } static void set_cr4_guest_host_mask(struct vcpu_vmx *vmx) { vmx->vcpu.arch.cr4_guest_owned_bits = KVM_CR4_GUEST_OWNED_BITS; if (enable_ept) vmx->vcpu.arch.cr4_guest_owned_bits |= X86_CR4_PGE; if (is_guest_mode(&vmx->vcpu)) vmx->vcpu.arch.cr4_guest_owned_bits &= ~get_vmcs12(&vmx->vcpu)->cr4_guest_host_mask; vmcs_writel(CR4_GUEST_HOST_MASK, ~vmx->vcpu.arch.cr4_guest_owned_bits); } static u32 vmx_pin_based_exec_ctrl(struct vcpu_vmx *vmx) { u32 pin_based_exec_ctrl = vmcs_config.pin_based_exec_ctrl; if (!vmx_vm_has_apicv(vmx->vcpu.kvm)) pin_based_exec_ctrl &= ~PIN_BASED_POSTED_INTR; return pin_based_exec_ctrl; } static u32 vmx_exec_control(struct vcpu_vmx *vmx) { u32 exec_control = vmcs_config.cpu_based_exec_ctrl; if (!vm_need_tpr_shadow(vmx->vcpu.kvm)) { exec_control &= ~CPU_BASED_TPR_SHADOW; #ifdef CONFIG_X86_64 exec_control |= CPU_BASED_CR8_STORE_EXITING | CPU_BASED_CR8_LOAD_EXITING; #endif } if (!enable_ept) exec_control |= CPU_BASED_CR3_STORE_EXITING | CPU_BASED_CR3_LOAD_EXITING | CPU_BASED_INVLPG_EXITING; return exec_control; } static u32 vmx_secondary_exec_control(struct vcpu_vmx *vmx) { u32 exec_control = vmcs_config.cpu_based_2nd_exec_ctrl; if (!vm_need_virtualize_apic_accesses(vmx->vcpu.kvm)) exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES; if (vmx->vpid == 0) exec_control &= ~SECONDARY_EXEC_ENABLE_VPID; if (!enable_ept) { exec_control &= ~SECONDARY_EXEC_ENABLE_EPT; enable_unrestricted_guest = 0; /* Enable INVPCID for non-ept guests may cause performance regression. */ exec_control &= ~SECONDARY_EXEC_ENABLE_INVPCID; } if (!enable_unrestricted_guest) exec_control &= ~SECONDARY_EXEC_UNRESTRICTED_GUEST; if (!ple_gap) exec_control &= ~SECONDARY_EXEC_PAUSE_LOOP_EXITING; if (!vmx_vm_has_apicv(vmx->vcpu.kvm)) exec_control &= ~(SECONDARY_EXEC_APIC_REGISTER_VIRT | SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY); exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE; /* SECONDARY_EXEC_SHADOW_VMCS is enabled when L1 executes VMPTRLD (handle_vmptrld). We can NOT enable shadow_vmcs here because we don't have yet a current VMCS12 */ exec_control &= ~SECONDARY_EXEC_SHADOW_VMCS; return exec_control; } static void ept_set_mmio_spte_mask(void) { /* * EPT Misconfigurations can be generated if the value of bits 2:0 * of an EPT paging-structure entry is 110b (write/execute). * Also, magic bits (0x3ull << 62) is set to quickly identify mmio * spte. */ kvm_mmu_set_mmio_spte_mask((0x3ull << 62) | 0x6ull); } /* * Sets up the vmcs for emulated real mode. */ static int vmx_vcpu_setup(struct vcpu_vmx *vmx) { #ifdef CONFIG_X86_64 unsigned long a; #endif int i; /* I/O */ vmcs_write64(IO_BITMAP_A, __pa(vmx_io_bitmap_a)); vmcs_write64(IO_BITMAP_B, __pa(vmx_io_bitmap_b)); if (enable_shadow_vmcs) { vmcs_write64(VMREAD_BITMAP, __pa(vmx_vmread_bitmap)); vmcs_write64(VMWRITE_BITMAP, __pa(vmx_vmwrite_bitmap)); } if (cpu_has_vmx_msr_bitmap()) vmcs_write64(MSR_BITMAP, __pa(vmx_msr_bitmap_legacy)); vmcs_write64(VMCS_LINK_POINTER, -1ull); /* 22.3.1.5 */ /* Control */ vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, vmx_pin_based_exec_ctrl(vmx)); vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, vmx_exec_control(vmx)); if (cpu_has_secondary_exec_ctrls()) { vmcs_write32(SECONDARY_VM_EXEC_CONTROL, vmx_secondary_exec_control(vmx)); } if (vmx_vm_has_apicv(vmx->vcpu.kvm)) { vmcs_write64(EOI_EXIT_BITMAP0, 0); vmcs_write64(EOI_EXIT_BITMAP1, 0); vmcs_write64(EOI_EXIT_BITMAP2, 0); vmcs_write64(EOI_EXIT_BITMAP3, 0); vmcs_write16(GUEST_INTR_STATUS, 0); vmcs_write64(POSTED_INTR_NV, POSTED_INTR_VECTOR); vmcs_write64(POSTED_INTR_DESC_ADDR, __pa((&vmx->pi_desc))); } if (ple_gap) { vmcs_write32(PLE_GAP, ple_gap); vmcs_write32(PLE_WINDOW, ple_window); } vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, 0); vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, 0); vmcs_write32(CR3_TARGET_COUNT, 0); /* 22.2.1 */ vmcs_write16(HOST_FS_SELECTOR, 0); /* 22.2.4 */ vmcs_write16(HOST_GS_SELECTOR, 0); /* 22.2.4 */ vmx_set_constant_host_state(vmx); #ifdef CONFIG_X86_64 rdmsrl(MSR_FS_BASE, a); vmcs_writel(HOST_FS_BASE, a); /* 22.2.4 */ rdmsrl(MSR_GS_BASE, a); vmcs_writel(HOST_GS_BASE, a); /* 22.2.4 */ #else vmcs_writel(HOST_FS_BASE, 0); /* 22.2.4 */ vmcs_writel(HOST_GS_BASE, 0); /* 22.2.4 */ #endif vmcs_write32(VM_EXIT_MSR_STORE_COUNT, 0); vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, 0); vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host)); vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, 0); vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest)); if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) { u32 msr_low, msr_high; u64 host_pat; rdmsr(MSR_IA32_CR_PAT, msr_low, msr_high); host_pat = msr_low | ((u64) msr_high << 32); /* Write the default value follow host pat */ vmcs_write64(GUEST_IA32_PAT, host_pat); /* Keep arch.pat sync with GUEST_IA32_PAT */ vmx->vcpu.arch.pat = host_pat; } for (i = 0; i < NR_VMX_MSR; ++i) { u32 index = vmx_msr_index[i]; u32 data_low, data_high; int j = vmx->nmsrs; if (rdmsr_safe(index, &data_low, &data_high) < 0) continue; if (wrmsr_safe(index, data_low, data_high) < 0) continue; vmx->guest_msrs[j].index = i; vmx->guest_msrs[j].data = 0; vmx->guest_msrs[j].mask = -1ull; ++vmx->nmsrs; } vmcs_write32(VM_EXIT_CONTROLS, vmcs_config.vmexit_ctrl); /* 22.2.1, 20.8.1 */ vmcs_write32(VM_ENTRY_CONTROLS, vmcs_config.vmentry_ctrl); vmcs_writel(CR0_GUEST_HOST_MASK, ~0UL); set_cr4_guest_host_mask(vmx); return 0; } static void vmx_vcpu_reset(struct kvm_vcpu *vcpu) { struct vcpu_vmx *vmx = to_vmx(vcpu); u64 msr; vmx->rmode.vm86_active = 0; vmx->soft_vnmi_blocked = 0; vmx->vcpu.arch.regs[VCPU_REGS_RDX] = get_rdx_init_val(); kvm_set_cr8(&vmx->vcpu, 0); msr = 0xfee00000 | MSR_IA32_APICBASE_ENABLE; if (kvm_vcpu_is_bsp(&vmx->vcpu)) msr |= MSR_IA32_APICBASE_BSP; kvm_set_apic_base(&vmx->vcpu, msr); vmx_segment_cache_clear(vmx); seg_setup(VCPU_SREG_CS); vmcs_write16(GUEST_CS_SELECTOR, 0xf000); vmcs_write32(GUEST_CS_BASE, 0xffff0000); seg_setup(VCPU_SREG_DS); seg_setup(VCPU_SREG_ES); seg_setup(VCPU_SREG_FS); seg_setup(VCPU_SREG_GS); seg_setup(VCPU_SREG_SS); vmcs_write16(GUEST_TR_SELECTOR, 0); vmcs_writel(GUEST_TR_BASE, 0); vmcs_write32(GUEST_TR_LIMIT, 0xffff); vmcs_write32(GUEST_TR_AR_BYTES, 0x008b); vmcs_write16(GUEST_LDTR_SELECTOR, 0); vmcs_writel(GUEST_LDTR_BASE, 0); vmcs_write32(GUEST_LDTR_LIMIT, 0xffff); vmcs_write32(GUEST_LDTR_AR_BYTES, 0x00082); vmcs_write32(GUEST_SYSENTER_CS, 0); vmcs_writel(GUEST_SYSENTER_ESP, 0); vmcs_writel(GUEST_SYSENTER_EIP, 0); vmcs_writel(GUEST_RFLAGS, 0x02); kvm_rip_write(vcpu, 0xfff0); vmcs_writel(GUEST_GDTR_BASE, 0); vmcs_write32(GUEST_GDTR_LIMIT, 0xffff); vmcs_writel(GUEST_IDTR_BASE, 0); vmcs_write32(GUEST_IDTR_LIMIT, 0xffff); vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE); vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, 0); vmcs_write32(GUEST_PENDING_DBG_EXCEPTIONS, 0); /* Special registers */ vmcs_write64(GUEST_IA32_DEBUGCTL, 0); setup_msrs(vmx); vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0); /* 22.2.1 */ if (cpu_has_vmx_tpr_shadow()) { vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, 0); if (vm_need_tpr_shadow(vmx->vcpu.kvm)) vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, __pa(vmx->vcpu.arch.apic->regs)); vmcs_write32(TPR_THRESHOLD, 0); } if (vm_need_virtualize_apic_accesses(vmx->vcpu.kvm)) vmcs_write64(APIC_ACCESS_ADDR, page_to_phys(vmx->vcpu.kvm->arch.apic_access_page)); if (vmx_vm_has_apicv(vcpu->kvm)) memset(&vmx->pi_desc, 0, sizeof(struct pi_desc)); if (vmx->vpid != 0) vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid); vmx->vcpu.arch.cr0 = X86_CR0_NW | X86_CR0_CD | X86_CR0_ET; vmx_set_cr0(&vmx->vcpu, kvm_read_cr0(vcpu)); /* enter rmode */ vmx_set_cr4(&vmx->vcpu, 0); vmx_set_efer(&vmx->vcpu, 0); vmx_fpu_activate(&vmx->vcpu); update_exception_bitmap(&vmx->vcpu); vpid_sync_context(vmx); } /* * In nested virtualization, check if L1 asked to exit on external interrupts. * For most existing hypervisors, this will always return true. */ static bool nested_exit_on_intr(struct kvm_vcpu *vcpu) { return get_vmcs12(vcpu)->pin_based_vm_exec_control & PIN_BASED_EXT_INTR_MASK; } static bool nested_exit_on_nmi(struct kvm_vcpu *vcpu) { return get_vmcs12(vcpu)->pin_based_vm_exec_control & PIN_BASED_NMI_EXITING; } static int enable_irq_window(struct kvm_vcpu *vcpu) { u32 cpu_based_vm_exec_control; if (is_guest_mode(vcpu) && nested_exit_on_intr(vcpu)) /* * We get here if vmx_interrupt_allowed() said we can't * inject to L1 now because L2 must run. The caller will have * to make L2 exit right after entry, so we can inject to L1 * more promptly. */ return -EBUSY; cpu_based_vm_exec_control = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL); cpu_based_vm_exec_control |= CPU_BASED_VIRTUAL_INTR_PENDING; vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control); return 0; } static int enable_nmi_window(struct kvm_vcpu *vcpu) { u32 cpu_based_vm_exec_control; if (!cpu_has_virtual_nmis()) return enable_irq_window(vcpu); if (vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_STI) return enable_irq_window(vcpu); cpu_based_vm_exec_control = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL); cpu_based_vm_exec_control |= CPU_BASED_VIRTUAL_NMI_PENDING; vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control); return 0; } static void vmx_inject_irq(struct kvm_vcpu *vcpu) { struct vcpu_vmx *vmx = to_vmx(vcpu); uint32_t intr; int irq = vcpu->arch.interrupt.nr; trace_kvm_inj_virq(irq); ++vcpu->stat.irq_injections; if (vmx->rmode.vm86_active) { int inc_eip = 0; if (vcpu->arch.interrupt.soft) inc_eip = vcpu->arch.event_exit_inst_len; if (kvm_inject_realmode_interrupt(vcpu, irq, inc_eip) != EMULATE_DONE) kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu); return; } intr = irq | INTR_INFO_VALID_MASK; if (vcpu->arch.interrupt.soft) { intr |= INTR_TYPE_SOFT_INTR; vmcs_write32(VM_ENTRY_INSTRUCTION_LEN, vmx->vcpu.arch.event_exit_inst_len); } else intr |= INTR_TYPE_EXT_INTR; vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr); } static void vmx_inject_nmi(struct kvm_vcpu *vcpu) { struct vcpu_vmx *vmx = to_vmx(vcpu); if (is_guest_mode(vcpu)) return; if (!cpu_has_virtual_nmis()) { /* * Tracking the NMI-blocked state in software is built upon * finding the next open IRQ window. This, in turn, depends on * well-behaving guests: They have to keep IRQs disabled at * least as long as the NMI handler runs. Otherwise we may * cause NMI nesting, maybe breaking the guest. But as this is * highly unlikely, we can live with the residual risk. */ vmx->soft_vnmi_blocked = 1; vmx->vnmi_blocked_time = 0; } ++vcpu->stat.nmi_injections; vmx->nmi_known_unmasked = false; if (vmx->rmode.vm86_active) { if (kvm_inject_realmode_interrupt(vcpu, NMI_VECTOR, 0) != EMULATE_DONE) kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu); return; } vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR); } static bool vmx_get_nmi_mask(struct kvm_vcpu *vcpu) { if (!cpu_has_virtual_nmis()) return to_vmx(vcpu)->soft_vnmi_blocked; if (to_vmx(vcpu)->nmi_known_unmasked) return false; return vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_NMI; } static void vmx_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked) { struct vcpu_vmx *vmx = to_vmx(vcpu); if (!cpu_has_virtual_nmis()) { if (vmx->soft_vnmi_blocked != masked) { vmx->soft_vnmi_blocked = masked; vmx->vnmi_blocked_time = 0; } } else { vmx->nmi_known_unmasked = !masked; if (masked) vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO, GUEST_INTR_STATE_NMI); else vmcs_clear_bits(GUEST_INTERRUPTIBILITY_INFO, GUEST_INTR_STATE_NMI); } } static int vmx_nmi_allowed(struct kvm_vcpu *vcpu) { if (is_guest_mode(vcpu)) { struct vmcs12 *vmcs12 = get_vmcs12(vcpu); if (to_vmx(vcpu)->nested.nested_run_pending) return 0; if (nested_exit_on_nmi(vcpu)) { nested_vmx_vmexit(vcpu); vmcs12->vm_exit_reason = EXIT_REASON_EXCEPTION_NMI; vmcs12->vm_exit_intr_info = NMI_VECTOR | INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK; /* * The NMI-triggered VM exit counts as injection: * clear this one and block further NMIs. */ vcpu->arch.nmi_pending = 0; vmx_set_nmi_mask(vcpu, true); return 0; } } if (!cpu_has_virtual_nmis() && to_vmx(vcpu)->soft_vnmi_blocked) return 0; return !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & (GUEST_INTR_STATE_MOV_SS | GUEST_INTR_STATE_STI | GUEST_INTR_STATE_NMI)); } static int vmx_interrupt_allowed(struct kvm_vcpu *vcpu) { if (is_guest_mode(vcpu)) { struct vmcs12 *vmcs12 = get_vmcs12(vcpu); if (to_vmx(vcpu)->nested.nested_run_pending) return 0; if (nested_exit_on_intr(vcpu)) { nested_vmx_vmexit(vcpu); vmcs12->vm_exit_reason = EXIT_REASON_EXTERNAL_INTERRUPT; vmcs12->vm_exit_intr_info = 0; /* * fall through to normal code, but now in L1, not L2 */ } } return (vmcs_readl(GUEST_RFLAGS) & X86_EFLAGS_IF) && !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & (GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS)); } static int vmx_set_tss_addr(struct kvm *kvm, unsigned int addr) { int ret; struct kvm_userspace_memory_region tss_mem = { .slot = TSS_PRIVATE_MEMSLOT, .guest_phys_addr = addr, .memory_size = PAGE_SIZE * 3, .flags = 0, }; ret = kvm_set_memory_region(kvm, &tss_mem); if (ret) return ret; kvm->arch.tss_addr = addr; if (!init_rmode_tss(kvm)) return -ENOMEM; return 0; } static bool rmode_exception(struct kvm_vcpu *vcpu, int vec) { switch (vec) { case BP_VECTOR: /* * Update instruction length as we may reinject the exception * from user space while in guest debugging mode. */ to_vmx(vcpu)->vcpu.arch.event_exit_inst_len = vmcs_read32(VM_EXIT_INSTRUCTION_LEN); if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP) return false; /* fall through */ case DB_VECTOR: if (vcpu->guest_debug & (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP)) return false; /* fall through */ case DE_VECTOR: case OF_VECTOR: case BR_VECTOR: case UD_VECTOR: case DF_VECTOR: case SS_VECTOR: case GP_VECTOR: case MF_VECTOR: return true; break; } return false; } static int handle_rmode_exception(struct kvm_vcpu *vcpu, int vec, u32 err_code) { /* * Instruction with address size override prefix opcode 0x67 * Cause the #SS fault with 0 error code in VM86 mode. */ if (((vec == GP_VECTOR) || (vec == SS_VECTOR)) && err_code == 0) { if (emulate_instruction(vcpu, 0) == EMULATE_DONE) { if (vcpu->arch.halt_request) { vcpu->arch.halt_request = 0; return kvm_emulate_halt(vcpu); } return 1; } return 0; } /* * Forward all other exceptions that are valid in real mode. * FIXME: Breaks guest debugging in real mode, needs to be fixed with * the required debugging infrastructure rework. */ kvm_queue_exception(vcpu, vec); return 1; } /* * Trigger machine check on the host. We assume all the MSRs are already set up * by the CPU and that we still run on the same CPU as the MCE occurred on. * We pass a fake environment to the machine check handler because we want * the guest to be always treated like user space, no matter what context * it used internally. */ static void kvm_machine_check(void) { #if defined(CONFIG_X86_MCE) && defined(CONFIG_X86_64) struct pt_regs regs = { .cs = 3, /* Fake ring 3 no matter what the guest ran on */ .flags = X86_EFLAGS_IF, }; do_machine_check(&regs, 0); #endif } static int handle_machine_check(struct kvm_vcpu *vcpu) { /* already handled by vcpu_run */ return 1; } static int handle_exception(struct kvm_vcpu *vcpu) { struct vcpu_vmx *vmx = to_vmx(vcpu); struct kvm_run *kvm_run = vcpu->run; u32 intr_info, ex_no, error_code; unsigned long cr2, rip, dr6; u32 vect_info; enum emulation_result er; vect_info = vmx->idt_vectoring_info; intr_info = vmx->exit_intr_info; if (is_machine_check(intr_info)) return handle_machine_check(vcpu); if ((intr_info & INTR_INFO_INTR_TYPE_MASK) == INTR_TYPE_NMI_INTR) return 1; /* already handled by vmx_vcpu_run() */ if (is_no_device(intr_info)) { vmx_fpu_activate(vcpu); return 1; } if (is_invalid_opcode(intr_info)) { er = emulate_instruction(vcpu, EMULTYPE_TRAP_UD); if (er != EMULATE_DONE) kvm_queue_exception(vcpu, UD_VECTOR); return 1; } error_code = 0; if (intr_info & INTR_INFO_DELIVER_CODE_MASK) error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE); /* * The #PF with PFEC.RSVD = 1 indicates the guest is accessing * MMIO, it is better to report an internal error. * See the comments in vmx_handle_exit. */ if ((vect_info & VECTORING_INFO_VALID_MASK) && !(is_page_fault(intr_info) && !(error_code & PFERR_RSVD_MASK))) { vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR; vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_SIMUL_EX; vcpu->run->internal.ndata = 2; vcpu->run->internal.data[0] = vect_info; vcpu->run->internal.data[1] = intr_info; return 0; } if (is_page_fault(intr_info)) { /* EPT won't cause page fault directly */ BUG_ON(enable_ept); cr2 = vmcs_readl(EXIT_QUALIFICATION); trace_kvm_page_fault(cr2, error_code); if (kvm_event_needs_reinjection(vcpu)) kvm_mmu_unprotect_page_virt(vcpu, cr2); return kvm_mmu_page_fault(vcpu, cr2, error_code, NULL, 0); } ex_no = intr_info & INTR_INFO_VECTOR_MASK; if (vmx->rmode.vm86_active && rmode_exception(vcpu, ex_no)) return handle_rmode_exception(vcpu, ex_no, error_code); switch (ex_no) { case DB_VECTOR: dr6 = vmcs_readl(EXIT_QUALIFICATION); if (!(vcpu->guest_debug & (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))) { vcpu->arch.dr6 = dr6 | DR6_FIXED_1; kvm_queue_exception(vcpu, DB_VECTOR); return 1; } kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1; kvm_run->debug.arch.dr7 = vmcs_readl(GUEST_DR7); /* fall through */ case BP_VECTOR: /* * Update instruction length as we may reinject #BP from * user space while in guest debugging mode. Reading it for * #DB as well causes no harm, it is not used in that case. */ vmx->vcpu.arch.event_exit_inst_len = vmcs_read32(VM_EXIT_INSTRUCTION_LEN); kvm_run->exit_reason = KVM_EXIT_DEBUG; rip = kvm_rip_read(vcpu); kvm_run->debug.arch.pc = vmcs_readl(GUEST_CS_BASE) + rip; kvm_run->debug.arch.exception = ex_no; break; default: kvm_run->exit_reason = KVM_EXIT_EXCEPTION; kvm_run->ex.exception = ex_no; kvm_run->ex.error_code = error_code; break; } return 0; } static int handle_external_interrupt(struct kvm_vcpu *vcpu) { ++vcpu->stat.irq_exits; return 1; } static int handle_triple_fault(struct kvm_vcpu *vcpu) { vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN; return 0; } static int handle_io(struct kvm_vcpu *vcpu) { unsigned long exit_qualification; int size, in, string; unsigned port; exit_qualification = vmcs_readl(EXIT_QUALIFICATION); string = (exit_qualification & 16) != 0; in = (exit_qualification & 8) != 0; ++vcpu->stat.io_exits; if (string || in) return emulate_instruction(vcpu, 0) == EMULATE_DONE; port = exit_qualification >> 16; size = (exit_qualification & 7) + 1; skip_emulated_instruction(vcpu); return kvm_fast_pio_out(vcpu, size, port); } static void vmx_patch_hypercall(struct kvm_vcpu *vcpu, unsigned char *hypercall) { /* * Patch in the VMCALL instruction: */ hypercall[0] = 0x0f; hypercall[1] = 0x01; hypercall[2] = 0xc1; } /* called to set cr0 as appropriate for a mov-to-cr0 exit. */ static int handle_set_cr0(struct kvm_vcpu *vcpu, unsigned long val) { if (is_guest_mode(vcpu)) { struct vmcs12 *vmcs12 = get_vmcs12(vcpu); unsigned long orig_val = val; /* * We get here when L2 changed cr0 in a way that did not change * any of L1's shadowed bits (see nested_vmx_exit_handled_cr), * but did change L0 shadowed bits. So we first calculate the * effective cr0 value that L1 would like to write into the * hardware. It consists of the L2-owned bits from the new * value combined with the L1-owned bits from L1's guest_cr0. */ val = (val & ~vmcs12->cr0_guest_host_mask) | (vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask); /* TODO: will have to take unrestricted guest mode into * account */ if ((val & VMXON_CR0_ALWAYSON) != VMXON_CR0_ALWAYSON) return 1; if (kvm_set_cr0(vcpu, val)) return 1; vmcs_writel(CR0_READ_SHADOW, orig_val); return 0; } else { if (to_vmx(vcpu)->nested.vmxon && ((val & VMXON_CR0_ALWAYSON) != VMXON_CR0_ALWAYSON)) return 1; return kvm_set_cr0(vcpu, val); } } static int handle_set_cr4(struct kvm_vcpu *vcpu, unsigned long val) { if (is_guest_mode(vcpu)) { struct vmcs12 *vmcs12 = get_vmcs12(vcpu); unsigned long orig_val = val; /* analogously to handle_set_cr0 */ val = (val & ~vmcs12->cr4_guest_host_mask) | (vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask); if (kvm_set_cr4(vcpu, val)) return 1; vmcs_writel(CR4_READ_SHADOW, orig_val); return 0; } else return kvm_set_cr4(vcpu, val); } /* called to set cr0 as approriate for clts instruction exit. */ static void handle_clts(struct kvm_vcpu *vcpu) { if (is_guest_mode(vcpu)) { /* * We get here when L2 did CLTS, and L1 didn't shadow CR0.TS * but we did (!fpu_active). We need to keep GUEST_CR0.TS on, * just pretend it's off (also in arch.cr0 for fpu_activate). */ vmcs_writel(CR0_READ_SHADOW, vmcs_readl(CR0_READ_SHADOW) & ~X86_CR0_TS); vcpu->arch.cr0 &= ~X86_CR0_TS; } else vmx_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~X86_CR0_TS)); } static int handle_cr(struct kvm_vcpu *vcpu) { unsigned long exit_qualification, val; int cr; int reg; int err; exit_qualification = vmcs_readl(EXIT_QUALIFICATION); cr = exit_qualification & 15; reg = (exit_qualification >> 8) & 15; switch ((exit_qualification >> 4) & 3) { case 0: /* mov to cr */ val = kvm_register_read(vcpu, reg); trace_kvm_cr_write(cr, val); switch (cr) { case 0: err = handle_set_cr0(vcpu, val); kvm_complete_insn_gp(vcpu, err); return 1; case 3: err = kvm_set_cr3(vcpu, val); kvm_complete_insn_gp(vcpu, err); return 1; case 4: err = handle_set_cr4(vcpu, val); kvm_complete_insn_gp(vcpu, err); return 1; case 8: { u8 cr8_prev = kvm_get_cr8(vcpu); u8 cr8 = kvm_register_read(vcpu, reg); err = kvm_set_cr8(vcpu, cr8); kvm_complete_insn_gp(vcpu, err); if (irqchip_in_kernel(vcpu->kvm)) return 1; if (cr8_prev <= cr8) return 1; vcpu->run->exit_reason = KVM_EXIT_SET_TPR; return 0; } } break; case 2: /* clts */ handle_clts(vcpu); trace_kvm_cr_write(0, kvm_read_cr0(vcpu)); skip_emulated_instruction(vcpu); vmx_fpu_activate(vcpu); return 1; case 1: /*mov from cr*/ switch (cr) { case 3: val = kvm_read_cr3(vcpu); kvm_register_write(vcpu, reg, val); trace_kvm_cr_read(cr, val); skip_emulated_instruction(vcpu); return 1; case 8: val = kvm_get_cr8(vcpu); kvm_register_write(vcpu, reg, val); trace_kvm_cr_read(cr, val); skip_emulated_instruction(vcpu); return 1; } break; case 3: /* lmsw */ val = (exit_qualification >> LMSW_SOURCE_DATA_SHIFT) & 0x0f; trace_kvm_cr_write(0, (kvm_read_cr0(vcpu) & ~0xful) | val); kvm_lmsw(vcpu, val); skip_emulated_instruction(vcpu); return 1; default: break; } vcpu->run->exit_reason = 0; vcpu_unimpl(vcpu, "unhandled control register: op %d cr %d\n", (int)(exit_qualification >> 4) & 3, cr); return 0; } static int handle_dr(struct kvm_vcpu *vcpu) { unsigned long exit_qualification; int dr, reg; /* Do not handle if the CPL > 0, will trigger GP on re-entry */ if (!kvm_require_cpl(vcpu, 0)) return 1; dr = vmcs_readl(GUEST_DR7); if (dr & DR7_GD) { /* * As the vm-exit takes precedence over the debug trap, we * need to emulate the latter, either for the host or the * guest debugging itself. */ if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) { vcpu->run->debug.arch.dr6 = vcpu->arch.dr6; vcpu->run->debug.arch.dr7 = dr; vcpu->run->debug.arch.pc = vmcs_readl(GUEST_CS_BASE) + vmcs_readl(GUEST_RIP); vcpu->run->debug.arch.exception = DB_VECTOR; vcpu->run->exit_reason = KVM_EXIT_DEBUG; return 0; } else { vcpu->arch.dr7 &= ~DR7_GD; vcpu->arch.dr6 |= DR6_BD; vmcs_writel(GUEST_DR7, vcpu->arch.dr7); kvm_queue_exception(vcpu, DB_VECTOR); return 1; } } exit_qualification = vmcs_readl(EXIT_QUALIFICATION); dr = exit_qualification & DEBUG_REG_ACCESS_NUM; reg = DEBUG_REG_ACCESS_REG(exit_qualification); if (exit_qualification & TYPE_MOV_FROM_DR) { unsigned long val; if (!kvm_get_dr(vcpu, dr, &val)) kvm_register_write(vcpu, reg, val); } else kvm_set_dr(vcpu, dr, vcpu->arch.regs[reg]); skip_emulated_instruction(vcpu); return 1; } static void vmx_set_dr7(struct kvm_vcpu *vcpu, unsigned long val) { vmcs_writel(GUEST_DR7, val); } static int handle_cpuid(struct kvm_vcpu *vcpu) { kvm_emulate_cpuid(vcpu); return 1; } static int handle_rdmsr(struct kvm_vcpu *vcpu) { u32 ecx = vcpu->arch.regs[VCPU_REGS_RCX]; u64 data; if (vmx_get_msr(vcpu, ecx, &data)) { trace_kvm_msr_read_ex(ecx); kvm_inject_gp(vcpu, 0); return 1; } trace_kvm_msr_read(ecx, data); /* FIXME: handling of bits 32:63 of rax, rdx */ vcpu->arch.regs[VCPU_REGS_RAX] = data & -1u; vcpu->arch.regs[VCPU_REGS_RDX] = (data >> 32) & -1u; skip_emulated_instruction(vcpu); return 1; } static int handle_wrmsr(struct kvm_vcpu *vcpu) { struct msr_data msr; u32 ecx = vcpu->arch.regs[VCPU_REGS_RCX]; u64 data = (vcpu->arch.regs[VCPU_REGS_RAX] & -1u) | ((u64)(vcpu->arch.regs[VCPU_REGS_RDX] & -1u) << 32); msr.data = data; msr.index = ecx; msr.host_initiated = false; if (vmx_set_msr(vcpu, &msr) != 0) { trace_kvm_msr_write_ex(ecx, data); kvm_inject_gp(vcpu, 0); return 1; } trace_kvm_msr_write(ecx, data); skip_emulated_instruction(vcpu); return 1; } static int handle_tpr_below_threshold(struct kvm_vcpu *vcpu) { kvm_make_request(KVM_REQ_EVENT, vcpu); return 1; } static int handle_interrupt_window(struct kvm_vcpu *vcpu) { u32 cpu_based_vm_exec_control; /* clear pending irq */ cpu_based_vm_exec_control = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL); cpu_based_vm_exec_control &= ~CPU_BASED_VIRTUAL_INTR_PENDING; vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control); kvm_make_request(KVM_REQ_EVENT, vcpu); ++vcpu->stat.irq_window_exits; /* * If the user space waits to inject interrupts, exit as soon as * possible */ if (!irqchip_in_kernel(vcpu->kvm) && vcpu->run->request_interrupt_window && !kvm_cpu_has_interrupt(vcpu)) { vcpu->run->exit_reason = KVM_EXIT_IRQ_WINDOW_OPEN; return 0; } return 1; } static int handle_halt(struct kvm_vcpu *vcpu) { skip_emulated_instruction(vcpu); return kvm_emulate_halt(vcpu); } static int handle_vmcall(struct kvm_vcpu *vcpu) { skip_emulated_instruction(vcpu); kvm_emulate_hypercall(vcpu); return 1; } static int handle_invd(struct kvm_vcpu *vcpu) { return emulate_instruction(vcpu, 0) == EMULATE_DONE; } static int handle_invlpg(struct kvm_vcpu *vcpu) { unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION); kvm_mmu_invlpg(vcpu, exit_qualification); skip_emulated_instruction(vcpu); return 1; } static int handle_rdpmc(struct kvm_vcpu *vcpu) { int err; err = kvm_rdpmc(vcpu); kvm_complete_insn_gp(vcpu, err); return 1; } static int handle_wbinvd(struct kvm_vcpu *vcpu) { skip_emulated_instruction(vcpu); kvm_emulate_wbinvd(vcpu); return 1; } static int handle_xsetbv(struct kvm_vcpu *vcpu) { u64 new_bv = kvm_read_edx_eax(vcpu); u32 index = kvm_register_read(vcpu, VCPU_REGS_RCX); if (kvm_set_xcr(vcpu, index, new_bv) == 0) skip_emulated_instruction(vcpu); return 1; } static int handle_apic_access(struct kvm_vcpu *vcpu) { if (likely(fasteoi)) { unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION); int access_type, offset; access_type = exit_qualification & APIC_ACCESS_TYPE; offset = exit_qualification & APIC_ACCESS_OFFSET; /* * Sane guest uses MOV to write EOI, with written value * not cared. So make a short-circuit here by avoiding * heavy instruction emulation. */ if ((access_type == TYPE_LINEAR_APIC_INST_WRITE) && (offset == APIC_EOI)) { kvm_lapic_set_eoi(vcpu); skip_emulated_instruction(vcpu); return 1; } } return emulate_instruction(vcpu, 0) == EMULATE_DONE; } static int handle_apic_eoi_induced(struct kvm_vcpu *vcpu) { unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION); int vector = exit_qualification & 0xff; /* EOI-induced VM exit is trap-like and thus no need to adjust IP */ kvm_apic_set_eoi_accelerated(vcpu, vector); return 1; } static int handle_apic_write(struct kvm_vcpu *vcpu) { unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION); u32 offset = exit_qualification & 0xfff; /* APIC-write VM exit is trap-like and thus no need to adjust IP */ kvm_apic_write_nodecode(vcpu, offset); return 1; } static int handle_task_switch(struct kvm_vcpu *vcpu) { struct vcpu_vmx *vmx = to_vmx(vcpu); unsigned long exit_qualification; bool has_error_code = false; u32 error_code = 0; u16 tss_selector; int reason, type, idt_v, idt_index; idt_v = (vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK); idt_index = (vmx->idt_vectoring_info & VECTORING_INFO_VECTOR_MASK); type = (vmx->idt_vectoring_info & VECTORING_INFO_TYPE_MASK); exit_qualification = vmcs_readl(EXIT_QUALIFICATION); reason = (u32)exit_qualification >> 30; if (reason == TASK_SWITCH_GATE && idt_v) { switch (type) { case INTR_TYPE_NMI_INTR: vcpu->arch.nmi_injected = false; vmx_set_nmi_mask(vcpu, true); break; case INTR_TYPE_EXT_INTR: case INTR_TYPE_SOFT_INTR: kvm_clear_interrupt_queue(vcpu); break; case INTR_TYPE_HARD_EXCEPTION: if (vmx->idt_vectoring_info & VECTORING_INFO_DELIVER_CODE_MASK) { has_error_code = true; error_code = vmcs_read32(IDT_VECTORING_ERROR_CODE); } /* fall through */ case INTR_TYPE_SOFT_EXCEPTION: kvm_clear_exception_queue(vcpu); break; default: break; } } tss_selector = exit_qualification; if (!idt_v || (type != INTR_TYPE_HARD_EXCEPTION && type != INTR_TYPE_EXT_INTR && type != INTR_TYPE_NMI_INTR)) skip_emulated_instruction(vcpu); if (kvm_task_switch(vcpu, tss_selector, type == INTR_TYPE_SOFT_INTR ? idt_index : -1, reason, has_error_code, error_code) == EMULATE_FAIL) { vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR; vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION; vcpu->run->internal.ndata = 0; return 0; } /* clear all local breakpoint enable flags */ vmcs_writel(GUEST_DR7, vmcs_readl(GUEST_DR7) & ~55); /* * TODO: What about debug traps on tss switch? * Are we supposed to inject them and update dr6? */ return 1; } static int handle_ept_violation(struct kvm_vcpu *vcpu) { unsigned long exit_qualification; gpa_t gpa; u32 error_code; int gla_validity; exit_qualification = vmcs_readl(EXIT_QUALIFICATION); gla_validity = (exit_qualification >> 7) & 0x3; if (gla_validity != 0x3 && gla_validity != 0x1 && gla_validity != 0) { printk(KERN_ERR "EPT: Handling EPT violation failed!\n"); printk(KERN_ERR "EPT: GPA: 0x%lx, GVA: 0x%lx\n", (long unsigned int)vmcs_read64(GUEST_PHYSICAL_ADDRESS), vmcs_readl(GUEST_LINEAR_ADDRESS)); printk(KERN_ERR "EPT: Exit qualification is 0x%lx\n", (long unsigned int)exit_qualification); vcpu->run->exit_reason = KVM_EXIT_UNKNOWN; vcpu->run->hw.hardware_exit_reason = EXIT_REASON_EPT_VIOLATION; return 0; } gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS); trace_kvm_page_fault(gpa, exit_qualification); /* It is a write fault? */ error_code = exit_qualification & (1U << 1); /* It is a fetch fault? */ error_code |= (exit_qualification & (1U << 2)) << 2; /* ept page table is present? */ error_code |= (exit_qualification >> 3) & 0x1; vcpu->arch.exit_qualification = exit_qualification; return kvm_mmu_page_fault(vcpu, gpa, error_code, NULL, 0); } static u64 ept_rsvd_mask(u64 spte, int level) { int i; u64 mask = 0; for (i = 51; i > boot_cpu_data.x86_phys_bits; i--) mask |= (1ULL << i); if (level > 2) /* bits 7:3 reserved */ mask |= 0xf8; else if (level == 2) { if (spte & (1ULL << 7)) /* 2MB ref, bits 20:12 reserved */ mask |= 0x1ff000; else /* bits 6:3 reserved */ mask |= 0x78; } return mask; } static void ept_misconfig_inspect_spte(struct kvm_vcpu *vcpu, u64 spte, int level) { printk(KERN_ERR "%s: spte 0x%llx level %d\n", __func__, spte, level); /* 010b (write-only) */ WARN_ON((spte & 0x7) == 0x2); /* 110b (write/execute) */ WARN_ON((spte & 0x7) == 0x6); /* 100b (execute-only) and value not supported by logical processor */ if (!cpu_has_vmx_ept_execute_only()) WARN_ON((spte & 0x7) == 0x4); /* not 000b */ if ((spte & 0x7)) { u64 rsvd_bits = spte & ept_rsvd_mask(spte, level); if (rsvd_bits != 0) { printk(KERN_ERR "%s: rsvd_bits = 0x%llx\n", __func__, rsvd_bits); WARN_ON(1); } if (level == 1 || (level == 2 && (spte & (1ULL << 7)))) { u64 ept_mem_type = (spte & 0x38) >> 3; if (ept_mem_type == 2 || ept_mem_type == 3 || ept_mem_type == 7) { printk(KERN_ERR "%s: ept_mem_type=0x%llx\n", __func__, ept_mem_type); WARN_ON(1); } } } } static int handle_ept_misconfig(struct kvm_vcpu *vcpu) { u64 sptes[4]; int nr_sptes, i, ret; gpa_t gpa; gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS); ret = handle_mmio_page_fault_common(vcpu, gpa, true); if (likely(ret == RET_MMIO_PF_EMULATE)) return x86_emulate_instruction(vcpu, gpa, 0, NULL, 0) == EMULATE_DONE; if (unlikely(ret == RET_MMIO_PF_INVALID)) return kvm_mmu_page_fault(vcpu, gpa, 0, NULL, 0); if (unlikely(ret == RET_MMIO_PF_RETRY)) return 1; /* It is the real ept misconfig */ printk(KERN_ERR "EPT: Misconfiguration.\n"); printk(KERN_ERR "EPT: GPA: 0x%llx\n", gpa); nr_sptes = kvm_mmu_get_spte_hierarchy(vcpu, gpa, sptes); for (i = PT64_ROOT_LEVEL; i > PT64_ROOT_LEVEL - nr_sptes; --i) ept_misconfig_inspect_spte(vcpu, sptes[i-1], i); vcpu->run->exit_reason = KVM_EXIT_UNKNOWN; vcpu->run->hw.hardware_exit_reason = EXIT_REASON_EPT_MISCONFIG; return 0; } static int handle_nmi_window(struct kvm_vcpu *vcpu) { u32 cpu_based_vm_exec_control; /* clear pending NMI */ cpu_based_vm_exec_control = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL); cpu_based_vm_exec_control &= ~CPU_BASED_VIRTUAL_NMI_PENDING; vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control); ++vcpu->stat.nmi_window_exits; kvm_make_request(KVM_REQ_EVENT, vcpu); return 1; } static int handle_invalid_guest_state(struct kvm_vcpu *vcpu) { struct vcpu_vmx *vmx = to_vmx(vcpu); enum emulation_result err = EMULATE_DONE; int ret = 1; u32 cpu_exec_ctrl; bool intr_window_requested; unsigned count = 130; cpu_exec_ctrl = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL); intr_window_requested = cpu_exec_ctrl & CPU_BASED_VIRTUAL_INTR_PENDING; while (!guest_state_valid(vcpu) && count-- != 0) { if (intr_window_requested && vmx_interrupt_allowed(vcpu)) return handle_interrupt_window(&vmx->vcpu); if (test_bit(KVM_REQ_EVENT, &vcpu->requests)) return 1; err = emulate_instruction(vcpu, EMULTYPE_NO_REEXECUTE); if (err == EMULATE_USER_EXIT) { ret = 0; goto out; } if (err != EMULATE_DONE) { vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR; vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION; vcpu->run->internal.ndata = 0; return 0; } if (vcpu->arch.halt_request) { vcpu->arch.halt_request = 0; ret = kvm_emulate_halt(vcpu); goto out; } if (signal_pending(current)) goto out; if (need_resched()) schedule(); } vmx->emulation_required = emulation_required(vcpu); out: return ret; } /* * Indicate a busy-waiting vcpu in spinlock. We do not enable the PAUSE * exiting, so only get here on cpu with PAUSE-Loop-Exiting. */ static int handle_pause(struct kvm_vcpu *vcpu) { skip_emulated_instruction(vcpu); kvm_vcpu_on_spin(vcpu); return 1; } static int handle_invalid_op(struct kvm_vcpu *vcpu) { kvm_queue_exception(vcpu, UD_VECTOR); return 1; } /* * To run an L2 guest, we need a vmcs02 based on the L1-specified vmcs12. * We could reuse a single VMCS for all the L2 guests, but we also want the * option to allocate a separate vmcs02 for each separate loaded vmcs12 - this * allows keeping them loaded on the processor, and in the future will allow * optimizations where prepare_vmcs02 doesn't need to set all the fields on * every entry if they never change. * So we keep, in vmx->nested.vmcs02_pool, a cache of size VMCS02_POOL_SIZE * (>=0) with a vmcs02 for each recently loaded vmcs12s, most recent first. * * The following functions allocate and free a vmcs02 in this pool. */ /* Get a VMCS from the pool to use as vmcs02 for the current vmcs12. */ static struct loaded_vmcs *nested_get_current_vmcs02(struct vcpu_vmx *vmx) { struct vmcs02_list *item; list_for_each_entry(item, &vmx->nested.vmcs02_pool, list) if (item->vmptr == vmx->nested.current_vmptr) { list_move(&item->list, &vmx->nested.vmcs02_pool); return &item->vmcs02; } if (vmx->nested.vmcs02_num >= max(VMCS02_POOL_SIZE, 1)) { /* Recycle the least recently used VMCS. */ item = list_entry(vmx->nested.vmcs02_pool.prev, struct vmcs02_list, list); item->vmptr = vmx->nested.current_vmptr; list_move(&item->list, &vmx->nested.vmcs02_pool); return &item->vmcs02; } /* Create a new VMCS */ item = kmalloc(sizeof(struct vmcs02_list), GFP_KERNEL); if (!item) return NULL; item->vmcs02.vmcs = alloc_vmcs(); if (!item->vmcs02.vmcs) { kfree(item); return NULL; } loaded_vmcs_init(&item->vmcs02); item->vmptr = vmx->nested.current_vmptr; list_add(&(item->list), &(vmx->nested.vmcs02_pool)); vmx->nested.vmcs02_num++; return &item->vmcs02; } /* Free and remove from pool a vmcs02 saved for a vmcs12 (if there is one) */ static void nested_free_vmcs02(struct vcpu_vmx *vmx, gpa_t vmptr) { struct vmcs02_list *item; list_for_each_entry(item, &vmx->nested.vmcs02_pool, list) if (item->vmptr == vmptr) { free_loaded_vmcs(&item->vmcs02); list_del(&item->list); kfree(item); vmx->nested.vmcs02_num--; return; } } /* * Free all VMCSs saved for this vcpu, except the one pointed by * vmx->loaded_vmcs. These include the VMCSs in vmcs02_pool (except the one * currently used, if running L2), and vmcs01 when running L2. */ static void nested_free_all_saved_vmcss(struct vcpu_vmx *vmx) { struct vmcs02_list *item, *n; list_for_each_entry_safe(item, n, &vmx->nested.vmcs02_pool, list) { if (vmx->loaded_vmcs != &item->vmcs02) free_loaded_vmcs(&item->vmcs02); list_del(&item->list); kfree(item); } vmx->nested.vmcs02_num = 0; if (vmx->loaded_vmcs != &vmx->vmcs01) free_loaded_vmcs(&vmx->vmcs01); } /* * The following 3 functions, nested_vmx_succeed()/failValid()/failInvalid(), * set the success or error code of an emulated VMX instruction, as specified * by Vol 2B, VMX Instruction Reference, "Conventions". */ static void nested_vmx_succeed(struct kvm_vcpu *vcpu) { vmx_set_rflags(vcpu, vmx_get_rflags(vcpu) & ~(X86_EFLAGS_CF | X86_EFLAGS_PF | X86_EFLAGS_AF | X86_EFLAGS_ZF | X86_EFLAGS_SF | X86_EFLAGS_OF)); } static void nested_vmx_failInvalid(struct kvm_vcpu *vcpu) { vmx_set_rflags(vcpu, (vmx_get_rflags(vcpu) & ~(X86_EFLAGS_PF | X86_EFLAGS_AF | X86_EFLAGS_ZF | X86_EFLAGS_SF | X86_EFLAGS_OF)) | X86_EFLAGS_CF); } static void nested_vmx_failValid(struct kvm_vcpu *vcpu, u32 vm_instruction_error) { if (to_vmx(vcpu)->nested.current_vmptr == -1ull) { /* * failValid writes the error number to the current VMCS, which * can't be done there isn't a current VMCS. */ nested_vmx_failInvalid(vcpu); return; } vmx_set_rflags(vcpu, (vmx_get_rflags(vcpu) & ~(X86_EFLAGS_CF | X86_EFLAGS_PF | X86_EFLAGS_AF | X86_EFLAGS_SF | X86_EFLAGS_OF)) | X86_EFLAGS_ZF); get_vmcs12(vcpu)->vm_instruction_error = vm_instruction_error; /* * We don't need to force a shadow sync because * VM_INSTRUCTION_ERROR is not shadowed */ } /* * Emulate the VMXON instruction. * Currently, we just remember that VMX is active, and do not save or even * inspect the argument to VMXON (the so-called "VMXON pointer") because we * do not currently need to store anything in that guest-allocated memory * region. Consequently, VMCLEAR and VMPTRLD also do not verify that the their * argument is different from the VMXON pointer (which the spec says they do). */ static int handle_vmon(struct kvm_vcpu *vcpu) { struct kvm_segment cs; struct vcpu_vmx *vmx = to_vmx(vcpu); struct vmcs *shadow_vmcs; const u64 VMXON_NEEDED_FEATURES = FEATURE_CONTROL_LOCKED | FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX; /* The Intel VMX Instruction Reference lists a bunch of bits that * are prerequisite to running VMXON, most notably cr4.VMXE must be * set to 1 (see vmx_set_cr4() for when we allow the guest to set this). * Otherwise, we should fail with #UD. We test these now: */ if (!kvm_read_cr4_bits(vcpu, X86_CR4_VMXE) || !kvm_read_cr0_bits(vcpu, X86_CR0_PE) || (vmx_get_rflags(vcpu) & X86_EFLAGS_VM)) { kvm_queue_exception(vcpu, UD_VECTOR); return 1; } vmx_get_segment(vcpu, &cs, VCPU_SREG_CS); if (is_long_mode(vcpu) && !cs.l) { kvm_queue_exception(vcpu, UD_VECTOR); return 1; } if (vmx_get_cpl(vcpu)) { kvm_inject_gp(vcpu, 0); return 1; } if (vmx->nested.vmxon) { nested_vmx_failValid(vcpu, VMXERR_VMXON_IN_VMX_ROOT_OPERATION); skip_emulated_instruction(vcpu); return 1; } if ((vmx->nested.msr_ia32_feature_control & VMXON_NEEDED_FEATURES) != VMXON_NEEDED_FEATURES) { kvm_inject_gp(vcpu, 0); return 1; } if (enable_shadow_vmcs) { shadow_vmcs = alloc_vmcs(); if (!shadow_vmcs) return -ENOMEM; /* mark vmcs as shadow */ shadow_vmcs->revision_id |= (1u << 31); /* init shadow vmcs */ vmcs_clear(shadow_vmcs); vmx->nested.current_shadow_vmcs = shadow_vmcs; } INIT_LIST_HEAD(&(vmx->nested.vmcs02_pool)); vmx->nested.vmcs02_num = 0; vmx->nested.vmxon = true; skip_emulated_instruction(vcpu); nested_vmx_succeed(vcpu); return 1; } /* * Intel's VMX Instruction Reference specifies a common set of prerequisites * for running VMX instructions (except VMXON, whose prerequisites are * slightly different). It also specifies what exception to inject otherwise. */ static int nested_vmx_check_permission(struct kvm_vcpu *vcpu) { struct kvm_segment cs; struct vcpu_vmx *vmx = to_vmx(vcpu); if (!vmx->nested.vmxon) { kvm_queue_exception(vcpu, UD_VECTOR); return 0; } vmx_get_segment(vcpu, &cs, VCPU_SREG_CS); if ((vmx_get_rflags(vcpu) & X86_EFLAGS_VM) || (is_long_mode(vcpu) && !cs.l)) { kvm_queue_exception(vcpu, UD_VECTOR); return 0; } if (vmx_get_cpl(vcpu)) { kvm_inject_gp(vcpu, 0); return 0; } return 1; } static inline void nested_release_vmcs12(struct vcpu_vmx *vmx) { u32 exec_control; if (enable_shadow_vmcs) { if (vmx->nested.current_vmcs12 != NULL) { /* copy to memory all shadowed fields in case they were modified */ copy_shadow_to_vmcs12(vmx); vmx->nested.sync_shadow_vmcs = false; exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL); exec_control &= ~SECONDARY_EXEC_SHADOW_VMCS; vmcs_write32(SECONDARY_VM_EXEC_CONTROL, exec_control); vmcs_write64(VMCS_LINK_POINTER, -1ull); } } kunmap(vmx->nested.current_vmcs12_page); nested_release_page(vmx->nested.current_vmcs12_page); } /* * Free whatever needs to be freed from vmx->nested when L1 goes down, or * just stops using VMX. */ static void free_nested(struct vcpu_vmx *vmx) { if (!vmx->nested.vmxon) return; vmx->nested.vmxon = false; if (vmx->nested.current_vmptr != -1ull) { nested_release_vmcs12(vmx); vmx->nested.current_vmptr = -1ull; vmx->nested.current_vmcs12 = NULL; } if (enable_shadow_vmcs) free_vmcs(vmx->nested.current_shadow_vmcs); /* Unpin physical memory we referred to in current vmcs02 */ if (vmx->nested.apic_access_page) { nested_release_page(vmx->nested.apic_access_page); vmx->nested.apic_access_page = 0; } nested_free_all_saved_vmcss(vmx); } /* Emulate the VMXOFF instruction */ static int handle_vmoff(struct kvm_vcpu *vcpu) { if (!nested_vmx_check_permission(vcpu)) return 1; free_nested(to_vmx(vcpu)); skip_emulated_instruction(vcpu); nested_vmx_succeed(vcpu); return 1; } /* * Decode the memory-address operand of a vmx instruction, as recorded on an * exit caused by such an instruction (run by a guest hypervisor). * On success, returns 0. When the operand is invalid, returns 1 and throws * #UD or #GP. */ static int get_vmx_mem_address(struct kvm_vcpu *vcpu, unsigned long exit_qualification, u32 vmx_instruction_info, gva_t *ret) { /* * According to Vol. 3B, "Information for VM Exits Due to Instruction * Execution", on an exit, vmx_instruction_info holds most of the * addressing components of the operand. Only the displacement part * is put in exit_qualification (see 3B, "Basic VM-Exit Information"). * For how an actual address is calculated from all these components, * refer to Vol. 1, "Operand Addressing". */ int scaling = vmx_instruction_info & 3; int addr_size = (vmx_instruction_info >> 7) & 7; bool is_reg = vmx_instruction_info & (1u << 10); int seg_reg = (vmx_instruction_info >> 15) & 7; int index_reg = (vmx_instruction_info >> 18) & 0xf; bool index_is_valid = !(vmx_instruction_info & (1u << 22)); int base_reg = (vmx_instruction_info >> 23) & 0xf; bool base_is_valid = !(vmx_instruction_info & (1u << 27)); if (is_reg) { kvm_queue_exception(vcpu, UD_VECTOR); return 1; } /* Addr = segment_base + offset */ /* offset = base + [index * scale] + displacement */ *ret = vmx_get_segment_base(vcpu, seg_reg); if (base_is_valid) *ret += kvm_register_read(vcpu, base_reg); if (index_is_valid) *ret += kvm_register_read(vcpu, index_reg)<<scaling; *ret += exit_qualification; /* holds the displacement */ if (addr_size == 1) /* 32 bit */ *ret &= 0xffffffff; /* * TODO: throw #GP (and return 1) in various cases that the VM* * instructions require it - e.g., offset beyond segment limit, * unusable or unreadable/unwritable segment, non-canonical 64-bit * address, and so on. Currently these are not checked. */ return 0; } /* Emulate the VMCLEAR instruction */ static int handle_vmclear(struct kvm_vcpu *vcpu) { struct vcpu_vmx *vmx = to_vmx(vcpu); gva_t gva; gpa_t vmptr; struct vmcs12 *vmcs12; struct page *page; struct x86_exception e; if (!nested_vmx_check_permission(vcpu)) return 1; if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION), vmcs_read32(VMX_INSTRUCTION_INFO), &gva)) return 1; if (kvm_read_guest_virt(&vcpu->arch.emulate_ctxt, gva, &vmptr, sizeof(vmptr), &e)) { kvm_inject_page_fault(vcpu, &e); return 1; } if (!IS_ALIGNED(vmptr, PAGE_SIZE)) { nested_vmx_failValid(vcpu, VMXERR_VMCLEAR_INVALID_ADDRESS); skip_emulated_instruction(vcpu); return 1; } if (vmptr == vmx->nested.current_vmptr) { nested_release_vmcs12(vmx); vmx->nested.current_vmptr = -1ull; vmx->nested.current_vmcs12 = NULL; } page = nested_get_page(vcpu, vmptr); if (page == NULL) { /* * For accurate processor emulation, VMCLEAR beyond available * physical memory should do nothing at all. However, it is * possible that a nested vmx bug, not a guest hypervisor bug, * resulted in this case, so let's shut down before doing any * more damage: */ kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu); return 1; } vmcs12 = kmap(page); vmcs12->launch_state = 0; kunmap(page); nested_release_page(page); nested_free_vmcs02(vmx, vmptr); skip_emulated_instruction(vcpu); nested_vmx_succeed(vcpu); return 1; } static int nested_vmx_run(struct kvm_vcpu *vcpu, bool launch); /* Emulate the VMLAUNCH instruction */ static int handle_vmlaunch(struct kvm_vcpu *vcpu) { return nested_vmx_run(vcpu, true); } /* Emulate the VMRESUME instruction */ static int handle_vmresume(struct kvm_vcpu *vcpu) { return nested_vmx_run(vcpu, false); } enum vmcs_field_type { VMCS_FIELD_TYPE_U16 = 0, VMCS_FIELD_TYPE_U64 = 1, VMCS_FIELD_TYPE_U32 = 2, VMCS_FIELD_TYPE_NATURAL_WIDTH = 3 }; static inline int vmcs_field_type(unsigned long field) { if (0x1 & field) /* the *_HIGH fields are all 32 bit */ return VMCS_FIELD_TYPE_U32; return (field >> 13) & 0x3 ; } static inline int vmcs_field_readonly(unsigned long field) { return (((field >> 10) & 0x3) == 1); } /* * Read a vmcs12 field. Since these can have varying lengths and we return * one type, we chose the biggest type (u64) and zero-extend the return value * to that size. Note that the caller, handle_vmread, might need to use only * some of the bits we return here (e.g., on 32-bit guests, only 32 bits of * 64-bit fields are to be returned). */ static inline bool vmcs12_read_any(struct kvm_vcpu *vcpu, unsigned long field, u64 *ret) { short offset = vmcs_field_to_offset(field); char *p; if (offset < 0) return 0; p = ((char *)(get_vmcs12(vcpu))) + offset; switch (vmcs_field_type(field)) { case VMCS_FIELD_TYPE_NATURAL_WIDTH: *ret = *((natural_width *)p); return 1; case VMCS_FIELD_TYPE_U16: *ret = *((u16 *)p); return 1; case VMCS_FIELD_TYPE_U32: *ret = *((u32 *)p); return 1; case VMCS_FIELD_TYPE_U64: *ret = *((u64 *)p); return 1; default: return 0; /* can never happen. */ } } static inline bool vmcs12_write_any(struct kvm_vcpu *vcpu, unsigned long field, u64 field_value){ short offset = vmcs_field_to_offset(field); char *p = ((char *) get_vmcs12(vcpu)) + offset; if (offset < 0) return false; switch (vmcs_field_type(field)) { case VMCS_FIELD_TYPE_U16: *(u16 *)p = field_value; return true; case VMCS_FIELD_TYPE_U32: *(u32 *)p = field_value; return true; case VMCS_FIELD_TYPE_U64: *(u64 *)p = field_value; return true; case VMCS_FIELD_TYPE_NATURAL_WIDTH: *(natural_width *)p = field_value; return true; default: return false; /* can never happen. */ } } static void copy_shadow_to_vmcs12(struct vcpu_vmx *vmx) { int i; unsigned long field; u64 field_value; struct vmcs *shadow_vmcs = vmx->nested.current_shadow_vmcs; const unsigned long *fields = shadow_read_write_fields; const int num_fields = max_shadow_read_write_fields; vmcs_load(shadow_vmcs); for (i = 0; i < num_fields; i++) { field = fields[i]; switch (vmcs_field_type(field)) { case VMCS_FIELD_TYPE_U16: field_value = vmcs_read16(field); break; case VMCS_FIELD_TYPE_U32: field_value = vmcs_read32(field); break; case VMCS_FIELD_TYPE_U64: field_value = vmcs_read64(field); break; case VMCS_FIELD_TYPE_NATURAL_WIDTH: field_value = vmcs_readl(field); break; } vmcs12_write_any(&vmx->vcpu, field, field_value); } vmcs_clear(shadow_vmcs); vmcs_load(vmx->loaded_vmcs->vmcs); } static void copy_vmcs12_to_shadow(struct vcpu_vmx *vmx) { const unsigned long *fields[] = { shadow_read_write_fields, shadow_read_only_fields }; const int max_fields[] = { max_shadow_read_write_fields, max_shadow_read_only_fields }; int i, q; unsigned long field; u64 field_value = 0; struct vmcs *shadow_vmcs = vmx->nested.current_shadow_vmcs; vmcs_load(shadow_vmcs); for (q = 0; q < ARRAY_SIZE(fields); q++) { for (i = 0; i < max_fields[q]; i++) { field = fields[q][i]; vmcs12_read_any(&vmx->vcpu, field, &field_value); switch (vmcs_field_type(field)) { case VMCS_FIELD_TYPE_U16: vmcs_write16(field, (u16)field_value); break; case VMCS_FIELD_TYPE_U32: vmcs_write32(field, (u32)field_value); break; case VMCS_FIELD_TYPE_U64: vmcs_write64(field, (u64)field_value); break; case VMCS_FIELD_TYPE_NATURAL_WIDTH: vmcs_writel(field, (long)field_value); break; } } } vmcs_clear(shadow_vmcs); vmcs_load(vmx->loaded_vmcs->vmcs); } /* * VMX instructions which assume a current vmcs12 (i.e., that VMPTRLD was * used before) all generate the same failure when it is missing. */ static int nested_vmx_check_vmcs12(struct kvm_vcpu *vcpu) { struct vcpu_vmx *vmx = to_vmx(vcpu); if (vmx->nested.current_vmptr == -1ull) { nested_vmx_failInvalid(vcpu); skip_emulated_instruction(vcpu); return 0; } return 1; } static int handle_vmread(struct kvm_vcpu *vcpu) { unsigned long field; u64 field_value; unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION); u32 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO); gva_t gva = 0; if (!nested_vmx_check_permission(vcpu) || !nested_vmx_check_vmcs12(vcpu)) return 1; /* Decode instruction info and find the field to read */ field = kvm_register_read(vcpu, (((vmx_instruction_info) >> 28) & 0xf)); /* Read the field, zero-extended to a u64 field_value */ if (!vmcs12_read_any(vcpu, field, &field_value)) { nested_vmx_failValid(vcpu, VMXERR_UNSUPPORTED_VMCS_COMPONENT); skip_emulated_instruction(vcpu); return 1; } /* * Now copy part of this value to register or memory, as requested. * Note that the number of bits actually copied is 32 or 64 depending * on the guest's mode (32 or 64 bit), not on the given field's length. */ if (vmx_instruction_info & (1u << 10)) { kvm_register_write(vcpu, (((vmx_instruction_info) >> 3) & 0xf), field_value); } else { if (get_vmx_mem_address(vcpu, exit_qualification, vmx_instruction_info, &gva)) return 1; /* _system ok, as nested_vmx_check_permission verified cpl=0 */ kvm_write_guest_virt_system(&vcpu->arch.emulate_ctxt, gva, &field_value, (is_long_mode(vcpu) ? 8 : 4), NULL); } nested_vmx_succeed(vcpu); skip_emulated_instruction(vcpu); return 1; } static int handle_vmwrite(struct kvm_vcpu *vcpu) { unsigned long field; gva_t gva; unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION); u32 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO); /* The value to write might be 32 or 64 bits, depending on L1's long * mode, and eventually we need to write that into a field of several * possible lengths. The code below first zero-extends the value to 64 * bit (field_value), and then copies only the approriate number of * bits into the vmcs12 field. */ u64 field_value = 0; struct x86_exception e; if (!nested_vmx_check_permission(vcpu) || !nested_vmx_check_vmcs12(vcpu)) return 1; if (vmx_instruction_info & (1u << 10)) field_value = kvm_register_read(vcpu, (((vmx_instruction_info) >> 3) & 0xf)); else { if (get_vmx_mem_address(vcpu, exit_qualification, vmx_instruction_info, &gva)) return 1; if (kvm_read_guest_virt(&vcpu->arch.emulate_ctxt, gva, &field_value, (is_long_mode(vcpu) ? 8 : 4), &e)) { kvm_inject_page_fault(vcpu, &e); return 1; } } field = kvm_register_read(vcpu, (((vmx_instruction_info) >> 28) & 0xf)); if (vmcs_field_readonly(field)) { nested_vmx_failValid(vcpu, VMXERR_VMWRITE_READ_ONLY_VMCS_COMPONENT); skip_emulated_instruction(vcpu); return 1; } if (!vmcs12_write_any(vcpu, field, field_value)) { nested_vmx_failValid(vcpu, VMXERR_UNSUPPORTED_VMCS_COMPONENT); skip_emulated_instruction(vcpu); return 1; } nested_vmx_succeed(vcpu); skip_emulated_instruction(vcpu); return 1; } /* Emulate the VMPTRLD instruction */ static int handle_vmptrld(struct kvm_vcpu *vcpu) { struct vcpu_vmx *vmx = to_vmx(vcpu); gva_t gva; gpa_t vmptr; struct x86_exception e; u32 exec_control; if (!nested_vmx_check_permission(vcpu)) return 1; if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION), vmcs_read32(VMX_INSTRUCTION_INFO), &gva)) return 1; if (kvm_read_guest_virt(&vcpu->arch.emulate_ctxt, gva, &vmptr, sizeof(vmptr), &e)) { kvm_inject_page_fault(vcpu, &e); return 1; } if (!IS_ALIGNED(vmptr, PAGE_SIZE)) { nested_vmx_failValid(vcpu, VMXERR_VMPTRLD_INVALID_ADDRESS); skip_emulated_instruction(vcpu); return 1; } if (vmx->nested.current_vmptr != vmptr) { struct vmcs12 *new_vmcs12; struct page *page; page = nested_get_page(vcpu, vmptr); if (page == NULL) { nested_vmx_failInvalid(vcpu); skip_emulated_instruction(vcpu); return 1; } new_vmcs12 = kmap(page); if (new_vmcs12->revision_id != VMCS12_REVISION) { kunmap(page); nested_release_page_clean(page); nested_vmx_failValid(vcpu, VMXERR_VMPTRLD_INCORRECT_VMCS_REVISION_ID); skip_emulated_instruction(vcpu); return 1; } if (vmx->nested.current_vmptr != -1ull) nested_release_vmcs12(vmx); vmx->nested.current_vmptr = vmptr; vmx->nested.current_vmcs12 = new_vmcs12; vmx->nested.current_vmcs12_page = page; if (enable_shadow_vmcs) { exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL); exec_control |= SECONDARY_EXEC_SHADOW_VMCS; vmcs_write32(SECONDARY_VM_EXEC_CONTROL, exec_control); vmcs_write64(VMCS_LINK_POINTER, __pa(vmx->nested.current_shadow_vmcs)); vmx->nested.sync_shadow_vmcs = true; } } nested_vmx_succeed(vcpu); skip_emulated_instruction(vcpu); return 1; } /* Emulate the VMPTRST instruction */ static int handle_vmptrst(struct kvm_vcpu *vcpu) { unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION); u32 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO); gva_t vmcs_gva; struct x86_exception e; if (!nested_vmx_check_permission(vcpu)) return 1; if (get_vmx_mem_address(vcpu, exit_qualification, vmx_instruction_info, &vmcs_gva)) return 1; /* ok to use *_system, as nested_vmx_check_permission verified cpl=0 */ if (kvm_write_guest_virt_system(&vcpu->arch.emulate_ctxt, vmcs_gva, (void *)&to_vmx(vcpu)->nested.current_vmptr, sizeof(u64), &e)) { kvm_inject_page_fault(vcpu, &e); return 1; } nested_vmx_succeed(vcpu); skip_emulated_instruction(vcpu); return 1; } /* * The exit handlers return 1 if the exit was handled fully and guest execution * may resume. Otherwise they set the kvm_run parameter to indicate what needs * to be done to userspace and return 0. */ static int (*const kvm_vmx_exit_handlers[])(struct kvm_vcpu *vcpu) = { [EXIT_REASON_EXCEPTION_NMI] = handle_exception, [EXIT_REASON_EXTERNAL_INTERRUPT] = handle_external_interrupt, [EXIT_REASON_TRIPLE_FAULT] = handle_triple_fault, [EXIT_REASON_NMI_WINDOW] = handle_nmi_window, [EXIT_REASON_IO_INSTRUCTION] = handle_io, [EXIT_REASON_CR_ACCESS] = handle_cr, [EXIT_REASON_DR_ACCESS] = handle_dr, [EXIT_REASON_CPUID] = handle_cpuid, [EXIT_REASON_MSR_READ] = handle_rdmsr, [EXIT_REASON_MSR_WRITE] = handle_wrmsr, [EXIT_REASON_PENDING_INTERRUPT] = handle_interrupt_window, [EXIT_REASON_HLT] = handle_halt, [EXIT_REASON_INVD] = handle_invd, [EXIT_REASON_INVLPG] = handle_invlpg, [EXIT_REASON_RDPMC] = handle_rdpmc, [EXIT_REASON_VMCALL] = handle_vmcall, [EXIT_REASON_VMCLEAR] = handle_vmclear, [EXIT_REASON_VMLAUNCH] = handle_vmlaunch, [EXIT_REASON_VMPTRLD] = handle_vmptrld, [EXIT_REASON_VMPTRST] = handle_vmptrst, [EXIT_REASON_VMREAD] = handle_vmread, [EXIT_REASON_VMRESUME] = handle_vmresume, [EXIT_REASON_VMWRITE] = handle_vmwrite, [EXIT_REASON_VMOFF] = handle_vmoff, [EXIT_REASON_VMON] = handle_vmon, [EXIT_REASON_TPR_BELOW_THRESHOLD] = handle_tpr_below_threshold, [EXIT_REASON_APIC_ACCESS] = handle_apic_access, [EXIT_REASON_APIC_WRITE] = handle_apic_write, [EXIT_REASON_EOI_INDUCED] = handle_apic_eoi_induced, [EXIT_REASON_WBINVD] = handle_wbinvd, [EXIT_REASON_XSETBV] = handle_xsetbv, [EXIT_REASON_TASK_SWITCH] = handle_task_switch, [EXIT_REASON_MCE_DURING_VMENTRY] = handle_machine_check, [EXIT_REASON_EPT_VIOLATION] = handle_ept_violation, [EXIT_REASON_EPT_MISCONFIG] = handle_ept_misconfig, [EXIT_REASON_PAUSE_INSTRUCTION] = handle_pause, [EXIT_REASON_MWAIT_INSTRUCTION] = handle_invalid_op, [EXIT_REASON_MONITOR_INSTRUCTION] = handle_invalid_op, }; static const int kvm_vmx_max_exit_handlers = ARRAY_SIZE(kvm_vmx_exit_handlers); static bool nested_vmx_exit_handled_io(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12) { unsigned long exit_qualification; gpa_t bitmap, last_bitmap; unsigned int port; int size; u8 b; if (nested_cpu_has(vmcs12, CPU_BASED_UNCOND_IO_EXITING)) return 1; if (!nested_cpu_has(vmcs12, CPU_BASED_USE_IO_BITMAPS)) return 0; exit_qualification = vmcs_readl(EXIT_QUALIFICATION); port = exit_qualification >> 16; size = (exit_qualification & 7) + 1; last_bitmap = (gpa_t)-1; b = -1; while (size > 0) { if (port < 0x8000) bitmap = vmcs12->io_bitmap_a; else if (port < 0x10000) bitmap = vmcs12->io_bitmap_b; else return 1; bitmap += (port & 0x7fff) / 8; if (last_bitmap != bitmap) if (kvm_read_guest(vcpu->kvm, bitmap, &b, 1)) return 1; if (b & (1 << (port & 7))) return 1; port++; size--; last_bitmap = bitmap; } return 0; } /* * Return 1 if we should exit from L2 to L1 to handle an MSR access access, * rather than handle it ourselves in L0. I.e., check whether L1 expressed * disinterest in the current event (read or write a specific MSR) by using an * MSR bitmap. This may be the case even when L0 doesn't use MSR bitmaps. */ static bool nested_vmx_exit_handled_msr(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12, u32 exit_reason) { u32 msr_index = vcpu->arch.regs[VCPU_REGS_RCX]; gpa_t bitmap; if (!nested_cpu_has(vmcs12, CPU_BASED_USE_MSR_BITMAPS)) return 1; /* * The MSR_BITMAP page is divided into four 1024-byte bitmaps, * for the four combinations of read/write and low/high MSR numbers. * First we need to figure out which of the four to use: */ bitmap = vmcs12->msr_bitmap; if (exit_reason == EXIT_REASON_MSR_WRITE) bitmap += 2048; if (msr_index >= 0xc0000000) { msr_index -= 0xc0000000; bitmap += 1024; } /* Then read the msr_index'th bit from this bitmap: */ if (msr_index < 1024*8) { unsigned char b; if (kvm_read_guest(vcpu->kvm, bitmap + msr_index/8, &b, 1)) return 1; return 1 & (b >> (msr_index & 7)); } else return 1; /* let L1 handle the wrong parameter */ } /* * Return 1 if we should exit from L2 to L1 to handle a CR access exit, * rather than handle it ourselves in L0. I.e., check if L1 wanted to * intercept (via guest_host_mask etc.) the current event. */ static bool nested_vmx_exit_handled_cr(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12) { unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION); int cr = exit_qualification & 15; int reg = (exit_qualification >> 8) & 15; unsigned long val = kvm_register_read(vcpu, reg); switch ((exit_qualification >> 4) & 3) { case 0: /* mov to cr */ switch (cr) { case 0: if (vmcs12->cr0_guest_host_mask & (val ^ vmcs12->cr0_read_shadow)) return 1; break; case 3: if ((vmcs12->cr3_target_count >= 1 && vmcs12->cr3_target_value0 == val) || (vmcs12->cr3_target_count >= 2 && vmcs12->cr3_target_value1 == val) || (vmcs12->cr3_target_count >= 3 && vmcs12->cr3_target_value2 == val) || (vmcs12->cr3_target_count >= 4 && vmcs12->cr3_target_value3 == val)) return 0; if (nested_cpu_has(vmcs12, CPU_BASED_CR3_LOAD_EXITING)) return 1; break; case 4: if (vmcs12->cr4_guest_host_mask & (vmcs12->cr4_read_shadow ^ val)) return 1; break; case 8: if (nested_cpu_has(vmcs12, CPU_BASED_CR8_LOAD_EXITING)) return 1; break; } break; case 2: /* clts */ if ((vmcs12->cr0_guest_host_mask & X86_CR0_TS) && (vmcs12->cr0_read_shadow & X86_CR0_TS)) return 1; break; case 1: /* mov from cr */ switch (cr) { case 3: if (vmcs12->cpu_based_vm_exec_control & CPU_BASED_CR3_STORE_EXITING) return 1; break; case 8: if (vmcs12->cpu_based_vm_exec_control & CPU_BASED_CR8_STORE_EXITING) return 1; break; } break; case 3: /* lmsw */ /* * lmsw can change bits 1..3 of cr0, and only set bit 0 of * cr0. Other attempted changes are ignored, with no exit. */ if (vmcs12->cr0_guest_host_mask & 0xe & (val ^ vmcs12->cr0_read_shadow)) return 1; if ((vmcs12->cr0_guest_host_mask & 0x1) && !(vmcs12->cr0_read_shadow & 0x1) && (val & 0x1)) return 1; break; } return 0; } /* * Return 1 if we should exit from L2 to L1 to handle an exit, or 0 if we * should handle it ourselves in L0 (and then continue L2). Only call this * when in is_guest_mode (L2). */ static bool nested_vmx_exit_handled(struct kvm_vcpu *vcpu) { u32 intr_info = vmcs_read32(VM_EXIT_INTR_INFO); struct vcpu_vmx *vmx = to_vmx(vcpu); struct vmcs12 *vmcs12 = get_vmcs12(vcpu); u32 exit_reason = vmx->exit_reason; if (vmx->nested.nested_run_pending) return 0; if (unlikely(vmx->fail)) { pr_info_ratelimited("%s failed vm entry %x\n", __func__, vmcs_read32(VM_INSTRUCTION_ERROR)); return 1; } switch (exit_reason) { case EXIT_REASON_EXCEPTION_NMI: if (!is_exception(intr_info)) return 0; else if (is_page_fault(intr_info)) return enable_ept; return vmcs12->exception_bitmap & (1u << (intr_info & INTR_INFO_VECTOR_MASK)); case EXIT_REASON_EXTERNAL_INTERRUPT: return 0; case EXIT_REASON_TRIPLE_FAULT: return 1; case EXIT_REASON_PENDING_INTERRUPT: return nested_cpu_has(vmcs12, CPU_BASED_VIRTUAL_INTR_PENDING); case EXIT_REASON_NMI_WINDOW: return nested_cpu_has(vmcs12, CPU_BASED_VIRTUAL_NMI_PENDING); case EXIT_REASON_TASK_SWITCH: return 1; case EXIT_REASON_CPUID: return 1; case EXIT_REASON_HLT: return nested_cpu_has(vmcs12, CPU_BASED_HLT_EXITING); case EXIT_REASON_INVD: return 1; case EXIT_REASON_INVLPG: return nested_cpu_has(vmcs12, CPU_BASED_INVLPG_EXITING); case EXIT_REASON_RDPMC: return nested_cpu_has(vmcs12, CPU_BASED_RDPMC_EXITING); case EXIT_REASON_RDTSC: return nested_cpu_has(vmcs12, CPU_BASED_RDTSC_EXITING); case EXIT_REASON_VMCALL: case EXIT_REASON_VMCLEAR: case EXIT_REASON_VMLAUNCH: case EXIT_REASON_VMPTRLD: case EXIT_REASON_VMPTRST: case EXIT_REASON_VMREAD: case EXIT_REASON_VMRESUME: case EXIT_REASON_VMWRITE: case EXIT_REASON_VMOFF: case EXIT_REASON_VMON: /* * VMX instructions trap unconditionally. This allows L1 to * emulate them for its L2 guest, i.e., allows 3-level nesting! */ return 1; case EXIT_REASON_CR_ACCESS: return nested_vmx_exit_handled_cr(vcpu, vmcs12); case EXIT_REASON_DR_ACCESS: return nested_cpu_has(vmcs12, CPU_BASED_MOV_DR_EXITING); case EXIT_REASON_IO_INSTRUCTION: return nested_vmx_exit_handled_io(vcpu, vmcs12); case EXIT_REASON_MSR_READ: case EXIT_REASON_MSR_WRITE: return nested_vmx_exit_handled_msr(vcpu, vmcs12, exit_reason); case EXIT_REASON_INVALID_STATE: return 1; case EXIT_REASON_MWAIT_INSTRUCTION: return nested_cpu_has(vmcs12, CPU_BASED_MWAIT_EXITING); case EXIT_REASON_MONITOR_INSTRUCTION: return nested_cpu_has(vmcs12, CPU_BASED_MONITOR_EXITING); case EXIT_REASON_PAUSE_INSTRUCTION: return nested_cpu_has(vmcs12, CPU_BASED_PAUSE_EXITING) || nested_cpu_has2(vmcs12, SECONDARY_EXEC_PAUSE_LOOP_EXITING); case EXIT_REASON_MCE_DURING_VMENTRY: return 0; case EXIT_REASON_TPR_BELOW_THRESHOLD: return 1; case EXIT_REASON_APIC_ACCESS: return nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES); case EXIT_REASON_EPT_VIOLATION: case EXIT_REASON_EPT_MISCONFIG: return 0; case EXIT_REASON_PREEMPTION_TIMER: return vmcs12->pin_based_vm_exec_control & PIN_BASED_VMX_PREEMPTION_TIMER; case EXIT_REASON_WBINVD: return nested_cpu_has2(vmcs12, SECONDARY_EXEC_WBINVD_EXITING); case EXIT_REASON_XSETBV: return 1; default: return 1; } } static void vmx_get_exit_info(struct kvm_vcpu *vcpu, u64 *info1, u64 *info2) { *info1 = vmcs_readl(EXIT_QUALIFICATION); *info2 = vmcs_read32(VM_EXIT_INTR_INFO); } /* * The guest has exited. See if we can fix it or if we need userspace * assistance. */ static int vmx_handle_exit(struct kvm_vcpu *vcpu) { struct vcpu_vmx *vmx = to_vmx(vcpu); u32 exit_reason = vmx->exit_reason; u32 vectoring_info = vmx->idt_vectoring_info; /* If guest state is invalid, start emulating */ if (vmx->emulation_required) return handle_invalid_guest_state(vcpu); /* * the KVM_REQ_EVENT optimization bit is only on for one entry, and if * we did not inject a still-pending event to L1 now because of * nested_run_pending, we need to re-enable this bit. */ if (vmx->nested.nested_run_pending) kvm_make_request(KVM_REQ_EVENT, vcpu); if (!is_guest_mode(vcpu) && (exit_reason == EXIT_REASON_VMLAUNCH || exit_reason == EXIT_REASON_VMRESUME)) vmx->nested.nested_run_pending = 1; else vmx->nested.nested_run_pending = 0; if (is_guest_mode(vcpu) && nested_vmx_exit_handled(vcpu)) { nested_vmx_vmexit(vcpu); return 1; } if (exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY) { vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY; vcpu->run->fail_entry.hardware_entry_failure_reason = exit_reason; return 0; } if (unlikely(vmx->fail)) { vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY; vcpu->run->fail_entry.hardware_entry_failure_reason = vmcs_read32(VM_INSTRUCTION_ERROR); return 0; } /* * Note: * Do not try to fix EXIT_REASON_EPT_MISCONFIG if it caused by * delivery event since it indicates guest is accessing MMIO. * The vm-exit can be triggered again after return to guest that * will cause infinite loop. */ if ((vectoring_info & VECTORING_INFO_VALID_MASK) && (exit_reason != EXIT_REASON_EXCEPTION_NMI && exit_reason != EXIT_REASON_EPT_VIOLATION && exit_reason != EXIT_REASON_TASK_SWITCH)) { vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR; vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_DELIVERY_EV; vcpu->run->internal.ndata = 2; vcpu->run->internal.data[0] = vectoring_info; vcpu->run->internal.data[1] = exit_reason; return 0; } if (unlikely(!cpu_has_virtual_nmis() && vmx->soft_vnmi_blocked && !(is_guest_mode(vcpu) && nested_cpu_has_virtual_nmis( get_vmcs12(vcpu), vcpu)))) { if (vmx_interrupt_allowed(vcpu)) { vmx->soft_vnmi_blocked = 0; } else if (vmx->vnmi_blocked_time > 1000000000LL && vcpu->arch.nmi_pending) { /* * This CPU don't support us in finding the end of an * NMI-blocked window if the guest runs with IRQs * disabled. So we pull the trigger after 1 s of * futile waiting, but inform the user about this. */ printk(KERN_WARNING "%s: Breaking out of NMI-blocked " "state on VCPU %d after 1 s timeout\n", __func__, vcpu->vcpu_id); vmx->soft_vnmi_blocked = 0; } } if (exit_reason < kvm_vmx_max_exit_handlers && kvm_vmx_exit_handlers[exit_reason]) return kvm_vmx_exit_handlers[exit_reason](vcpu); else { vcpu->run->exit_reason = KVM_EXIT_UNKNOWN; vcpu->run->hw.hardware_exit_reason = exit_reason; } return 0; } static void update_cr8_intercept(struct kvm_vcpu *vcpu, int tpr, int irr) { if (irr == -1 || tpr < irr) { vmcs_write32(TPR_THRESHOLD, 0); return; } vmcs_write32(TPR_THRESHOLD, irr); } static void vmx_set_virtual_x2apic_mode(struct kvm_vcpu *vcpu, bool set) { u32 sec_exec_control; /* * There is not point to enable virtualize x2apic without enable * apicv */ if (!cpu_has_vmx_virtualize_x2apic_mode() || !vmx_vm_has_apicv(vcpu->kvm)) return; if (!vm_need_tpr_shadow(vcpu->kvm)) return; sec_exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL); if (set) { sec_exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES; sec_exec_control |= SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE; } else { sec_exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE; sec_exec_control |= SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES; } vmcs_write32(SECONDARY_VM_EXEC_CONTROL, sec_exec_control); vmx_set_msr_bitmap(vcpu); } static void vmx_hwapic_isr_update(struct kvm *kvm, int isr) { u16 status; u8 old; if (!vmx_vm_has_apicv(kvm)) return; if (isr == -1) isr = 0; status = vmcs_read16(GUEST_INTR_STATUS); old = status >> 8; if (isr != old) { status &= 0xff; status |= isr << 8; vmcs_write16(GUEST_INTR_STATUS, status); } } static void vmx_set_rvi(int vector) { u16 status; u8 old; status = vmcs_read16(GUEST_INTR_STATUS); old = (u8)status & 0xff; if ((u8)vector != old) { status &= ~0xff; status |= (u8)vector; vmcs_write16(GUEST_INTR_STATUS, status); } } static void vmx_hwapic_irr_update(struct kvm_vcpu *vcpu, int max_irr) { if (max_irr == -1) return; vmx_set_rvi(max_irr); } static void vmx_load_eoi_exitmap(struct kvm_vcpu *vcpu, u64 *eoi_exit_bitmap) { if (!vmx_vm_has_apicv(vcpu->kvm)) return; vmcs_write64(EOI_EXIT_BITMAP0, eoi_exit_bitmap[0]); vmcs_write64(EOI_EXIT_BITMAP1, eoi_exit_bitmap[1]); vmcs_write64(EOI_EXIT_BITMAP2, eoi_exit_bitmap[2]); vmcs_write64(EOI_EXIT_BITMAP3, eoi_exit_bitmap[3]); } static void vmx_complete_atomic_exit(struct vcpu_vmx *vmx) { u32 exit_intr_info; if (!(vmx->exit_reason == EXIT_REASON_MCE_DURING_VMENTRY || vmx->exit_reason == EXIT_REASON_EXCEPTION_NMI)) return; vmx->exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO); exit_intr_info = vmx->exit_intr_info; /* Handle machine checks before interrupts are enabled */ if (is_machine_check(exit_intr_info)) kvm_machine_check(); /* We need to handle NMIs before interrupts are enabled */ if ((exit_intr_info & INTR_INFO_INTR_TYPE_MASK) == INTR_TYPE_NMI_INTR && (exit_intr_info & INTR_INFO_VALID_MASK)) { kvm_before_handle_nmi(&vmx->vcpu); asm("int $2"); kvm_after_handle_nmi(&vmx->vcpu); } } static void vmx_handle_external_intr(struct kvm_vcpu *vcpu) { u32 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO); /* * If external interrupt exists, IF bit is set in rflags/eflags on the * interrupt stack frame, and interrupt will be enabled on a return * from interrupt handler. */ if ((exit_intr_info & (INTR_INFO_VALID_MASK | INTR_INFO_INTR_TYPE_MASK)) == (INTR_INFO_VALID_MASK | INTR_TYPE_EXT_INTR)) { unsigned int vector; unsigned long entry; gate_desc *desc; struct vcpu_vmx *vmx = to_vmx(vcpu); #ifdef CONFIG_X86_64 unsigned long tmp; #endif vector = exit_intr_info & INTR_INFO_VECTOR_MASK; desc = (gate_desc *)vmx->host_idt_base + vector; entry = gate_offset(*desc); asm volatile( #ifdef CONFIG_X86_64 "mov %%" _ASM_SP ", %[sp]\n\t" "and $0xfffffffffffffff0, %%" _ASM_SP "\n\t" "push $%c[ss]\n\t" "push %[sp]\n\t" #endif "pushf\n\t" "orl $0x200, (%%" _ASM_SP ")\n\t" __ASM_SIZE(push) " $%c[cs]\n\t" "call *%[entry]\n\t" : #ifdef CONFIG_X86_64 [sp]"=&r"(tmp) #endif : [entry]"r"(entry), [ss]"i"(__KERNEL_DS), [cs]"i"(__KERNEL_CS) ); } else local_irq_enable(); } static void vmx_recover_nmi_blocking(struct vcpu_vmx *vmx) { u32 exit_intr_info; bool unblock_nmi; u8 vector; bool idtv_info_valid; idtv_info_valid = vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK; if (cpu_has_virtual_nmis()) { if (vmx->nmi_known_unmasked) return; /* * Can't use vmx->exit_intr_info since we're not sure what * the exit reason is. */ exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO); unblock_nmi = (exit_intr_info & INTR_INFO_UNBLOCK_NMI) != 0; vector = exit_intr_info & INTR_INFO_VECTOR_MASK; /* * SDM 3: 27.7.1.2 (September 2008) * Re-set bit "block by NMI" before VM entry if vmexit caused by * a guest IRET fault. * SDM 3: 23.2.2 (September 2008) * Bit 12 is undefined in any of the following cases: * If the VM exit sets the valid bit in the IDT-vectoring * information field. * If the VM exit is due to a double fault. */ if ((exit_intr_info & INTR_INFO_VALID_MASK) && unblock_nmi && vector != DF_VECTOR && !idtv_info_valid) vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO, GUEST_INTR_STATE_NMI); else vmx->nmi_known_unmasked = !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_NMI); } else if (unlikely(vmx->soft_vnmi_blocked)) vmx->vnmi_blocked_time += ktime_to_ns(ktime_sub(ktime_get(), vmx->entry_time)); } static void __vmx_complete_interrupts(struct kvm_vcpu *vcpu, u32 idt_vectoring_info, int instr_len_field, int error_code_field) { u8 vector; int type; bool idtv_info_valid; idtv_info_valid = idt_vectoring_info & VECTORING_INFO_VALID_MASK; vcpu->arch.nmi_injected = false; kvm_clear_exception_queue(vcpu); kvm_clear_interrupt_queue(vcpu); if (!idtv_info_valid) return; kvm_make_request(KVM_REQ_EVENT, vcpu); vector = idt_vectoring_info & VECTORING_INFO_VECTOR_MASK; type = idt_vectoring_info & VECTORING_INFO_TYPE_MASK; switch (type) { case INTR_TYPE_NMI_INTR: vcpu->arch.nmi_injected = true; /* * SDM 3: 27.7.1.2 (September 2008) * Clear bit "block by NMI" before VM entry if a NMI * delivery faulted. */ vmx_set_nmi_mask(vcpu, false); break; case INTR_TYPE_SOFT_EXCEPTION: vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field); /* fall through */ case INTR_TYPE_HARD_EXCEPTION: if (idt_vectoring_info & VECTORING_INFO_DELIVER_CODE_MASK) { u32 err = vmcs_read32(error_code_field); kvm_queue_exception_e(vcpu, vector, err); } else kvm_queue_exception(vcpu, vector); break; case INTR_TYPE_SOFT_INTR: vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field); /* fall through */ case INTR_TYPE_EXT_INTR: kvm_queue_interrupt(vcpu, vector, type == INTR_TYPE_SOFT_INTR); break; default: break; } } static void vmx_complete_interrupts(struct vcpu_vmx *vmx) { __vmx_complete_interrupts(&vmx->vcpu, vmx->idt_vectoring_info, VM_EXIT_INSTRUCTION_LEN, IDT_VECTORING_ERROR_CODE); } static void vmx_cancel_injection(struct kvm_vcpu *vcpu) { __vmx_complete_interrupts(vcpu, vmcs_read32(VM_ENTRY_INTR_INFO_FIELD), VM_ENTRY_INSTRUCTION_LEN, VM_ENTRY_EXCEPTION_ERROR_CODE); vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0); } static void atomic_switch_perf_msrs(struct vcpu_vmx *vmx) { int i, nr_msrs; struct perf_guest_switch_msr *msrs; msrs = perf_guest_get_msrs(&nr_msrs); if (!msrs) return; for (i = 0; i < nr_msrs; i++) if (msrs[i].host == msrs[i].guest) clear_atomic_switch_msr(vmx, msrs[i].msr); else add_atomic_switch_msr(vmx, msrs[i].msr, msrs[i].guest, msrs[i].host); } static void __noclone vmx_vcpu_run(struct kvm_vcpu *vcpu) { struct vcpu_vmx *vmx = to_vmx(vcpu); unsigned long debugctlmsr; /* Record the guest's net vcpu time for enforced NMI injections. */ if (unlikely(!cpu_has_virtual_nmis() && vmx->soft_vnmi_blocked)) vmx->entry_time = ktime_get(); /* Don't enter VMX if guest state is invalid, let the exit handler start emulation until we arrive back to a valid state */ if (vmx->emulation_required) return; if (vmx->nested.sync_shadow_vmcs) { copy_vmcs12_to_shadow(vmx); vmx->nested.sync_shadow_vmcs = false; } if (test_bit(VCPU_REGS_RSP, (unsigned long *)&vcpu->arch.regs_dirty)) vmcs_writel(GUEST_RSP, vcpu->arch.regs[VCPU_REGS_RSP]); if (test_bit(VCPU_REGS_RIP, (unsigned long *)&vcpu->arch.regs_dirty)) vmcs_writel(GUEST_RIP, vcpu->arch.regs[VCPU_REGS_RIP]); /* When single-stepping over STI and MOV SS, we must clear the * corresponding interruptibility bits in the guest state. Otherwise * vmentry fails as it then expects bit 14 (BS) in pending debug * exceptions being set, but that's not correct for the guest debugging * case. */ if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP) vmx_set_interrupt_shadow(vcpu, 0); atomic_switch_perf_msrs(vmx); debugctlmsr = get_debugctlmsr(); vmx->__launched = vmx->loaded_vmcs->launched; asm( /* Store host registers */ "push %%" _ASM_DX "; push %%" _ASM_BP ";" "push %%" _ASM_CX " \n\t" /* placeholder for guest rcx */ "push %%" _ASM_CX " \n\t" "cmp %%" _ASM_SP ", %c[host_rsp](%0) \n\t" "je 1f \n\t" "mov %%" _ASM_SP ", %c[host_rsp](%0) \n\t" __ex(ASM_VMX_VMWRITE_RSP_RDX) "\n\t" "1: \n\t" /* Reload cr2 if changed */ "mov %c[cr2](%0), %%" _ASM_AX " \n\t" "mov %%cr2, %%" _ASM_DX " \n\t" "cmp %%" _ASM_AX ", %%" _ASM_DX " \n\t" "je 2f \n\t" "mov %%" _ASM_AX", %%cr2 \n\t" "2: \n\t" /* Check if vmlaunch of vmresume is needed */ "cmpl $0, %c[launched](%0) \n\t" /* Load guest registers. Don't clobber flags. */ "mov %c[rax](%0), %%" _ASM_AX " \n\t" "mov %c[rbx](%0), %%" _ASM_BX " \n\t" "mov %c[rdx](%0), %%" _ASM_DX " \n\t" "mov %c[rsi](%0), %%" _ASM_SI " \n\t" "mov %c[rdi](%0), %%" _ASM_DI " \n\t" "mov %c[rbp](%0), %%" _ASM_BP " \n\t" #ifdef CONFIG_X86_64 "mov %c[r8](%0), %%r8 \n\t" "mov %c[r9](%0), %%r9 \n\t" "mov %c[r10](%0), %%r10 \n\t" "mov %c[r11](%0), %%r11 \n\t" "mov %c[r12](%0), %%r12 \n\t" "mov %c[r13](%0), %%r13 \n\t" "mov %c[r14](%0), %%r14 \n\t" "mov %c[r15](%0), %%r15 \n\t" #endif "mov %c[rcx](%0), %%" _ASM_CX " \n\t" /* kills %0 (ecx) */ /* Enter guest mode */ "jne 1f \n\t" __ex(ASM_VMX_VMLAUNCH) "\n\t" "jmp 2f \n\t" "1: " __ex(ASM_VMX_VMRESUME) "\n\t" "2: " /* Save guest registers, load host registers, keep flags */ "mov %0, %c[wordsize](%%" _ASM_SP ") \n\t" "pop %0 \n\t" "mov %%" _ASM_AX ", %c[rax](%0) \n\t" "mov %%" _ASM_BX ", %c[rbx](%0) \n\t" __ASM_SIZE(pop) " %c[rcx](%0) \n\t" "mov %%" _ASM_DX ", %c[rdx](%0) \n\t" "mov %%" _ASM_SI ", %c[rsi](%0) \n\t" "mov %%" _ASM_DI ", %c[rdi](%0) \n\t" "mov %%" _ASM_BP ", %c[rbp](%0) \n\t" #ifdef CONFIG_X86_64 "mov %%r8, %c[r8](%0) \n\t" "mov %%r9, %c[r9](%0) \n\t" "mov %%r10, %c[r10](%0) \n\t" "mov %%r11, %c[r11](%0) \n\t" "mov %%r12, %c[r12](%0) \n\t" "mov %%r13, %c[r13](%0) \n\t" "mov %%r14, %c[r14](%0) \n\t" "mov %%r15, %c[r15](%0) \n\t" #endif "mov %%cr2, %%" _ASM_AX " \n\t" "mov %%" _ASM_AX ", %c[cr2](%0) \n\t" "pop %%" _ASM_BP "; pop %%" _ASM_DX " \n\t" "setbe %c[fail](%0) \n\t" ".pushsection .rodata \n\t" ".global vmx_return \n\t" "vmx_return: " _ASM_PTR " 2b \n\t" ".popsection" : : "c"(vmx), "d"((unsigned long)HOST_RSP), [launched]"i"(offsetof(struct vcpu_vmx, __launched)), [fail]"i"(offsetof(struct vcpu_vmx, fail)), [host_rsp]"i"(offsetof(struct vcpu_vmx, host_rsp)), [rax]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RAX])), [rbx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RBX])), [rcx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RCX])), [rdx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RDX])), [rsi]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RSI])), [rdi]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RDI])), [rbp]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RBP])), #ifdef CONFIG_X86_64 [r8]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R8])), [r9]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R9])), [r10]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R10])), [r11]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R11])), [r12]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R12])), [r13]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R13])), [r14]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R14])), [r15]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R15])), #endif [cr2]"i"(offsetof(struct vcpu_vmx, vcpu.arch.cr2)), [wordsize]"i"(sizeof(ulong)) : "cc", "memory" #ifdef CONFIG_X86_64 , "rax", "rbx", "rdi", "rsi" , "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15" #else , "eax", "ebx", "edi", "esi" #endif ); /* MSR_IA32_DEBUGCTLMSR is zeroed on vmexit. Restore it if needed */ if (debugctlmsr) update_debugctlmsr(debugctlmsr); #ifndef CONFIG_X86_64 /* * The sysexit path does not restore ds/es, so we must set them to * a reasonable value ourselves. * * We can't defer this to vmx_load_host_state() since that function * may be executed in interrupt context, which saves and restore segments * around it, nullifying its effect. */ loadsegment(ds, __USER_DS); loadsegment(es, __USER_DS); #endif vcpu->arch.regs_avail = ~((1 << VCPU_REGS_RIP) | (1 << VCPU_REGS_RSP) | (1 << VCPU_EXREG_RFLAGS) | (1 << VCPU_EXREG_CPL) | (1 << VCPU_EXREG_PDPTR) | (1 << VCPU_EXREG_SEGMENTS) | (1 << VCPU_EXREG_CR3)); vcpu->arch.regs_dirty = 0; vmx->idt_vectoring_info = vmcs_read32(IDT_VECTORING_INFO_FIELD); vmx->loaded_vmcs->launched = 1; vmx->exit_reason = vmcs_read32(VM_EXIT_REASON); trace_kvm_exit(vmx->exit_reason, vcpu, KVM_ISA_VMX); vmx_complete_atomic_exit(vmx); vmx_recover_nmi_blocking(vmx); vmx_complete_interrupts(vmx); } static void vmx_free_vcpu(struct kvm_vcpu *vcpu) { struct vcpu_vmx *vmx = to_vmx(vcpu); free_vpid(vmx); free_nested(vmx); free_loaded_vmcs(vmx->loaded_vmcs); kfree(vmx->guest_msrs); kvm_vcpu_uninit(vcpu); kmem_cache_free(kvm_vcpu_cache, vmx); } static struct kvm_vcpu *vmx_create_vcpu(struct kvm *kvm, unsigned int id) { int err; struct vcpu_vmx *vmx = kmem_cache_zalloc(kvm_vcpu_cache, GFP_KERNEL); int cpu; if (!vmx) return ERR_PTR(-ENOMEM); allocate_vpid(vmx); err = kvm_vcpu_init(&vmx->vcpu, kvm, id); if (err) goto free_vcpu; vmx->guest_msrs = kmalloc(PAGE_SIZE, GFP_KERNEL); err = -ENOMEM; if (!vmx->guest_msrs) { goto uninit_vcpu; } vmx->loaded_vmcs = &vmx->vmcs01; vmx->loaded_vmcs->vmcs = alloc_vmcs(); if (!vmx->loaded_vmcs->vmcs) goto free_msrs; if (!vmm_exclusive) kvm_cpu_vmxon(__pa(per_cpu(vmxarea, raw_smp_processor_id()))); loaded_vmcs_init(vmx->loaded_vmcs); if (!vmm_exclusive) kvm_cpu_vmxoff(); cpu = get_cpu(); vmx_vcpu_load(&vmx->vcpu, cpu); vmx->vcpu.cpu = cpu; err = vmx_vcpu_setup(vmx); vmx_vcpu_put(&vmx->vcpu); put_cpu(); if (err) goto free_vmcs; if (vm_need_virtualize_apic_accesses(kvm)) { err = alloc_apic_access_page(kvm); if (err) goto free_vmcs; } if (enable_ept) { if (!kvm->arch.ept_identity_map_addr) kvm->arch.ept_identity_map_addr = VMX_EPT_IDENTITY_PAGETABLE_ADDR; err = -ENOMEM; if (alloc_identity_pagetable(kvm) != 0) goto free_vmcs; if (!init_rmode_identity_map(kvm)) goto free_vmcs; } vmx->nested.current_vmptr = -1ull; vmx->nested.current_vmcs12 = NULL; return &vmx->vcpu; free_vmcs: free_loaded_vmcs(vmx->loaded_vmcs); free_msrs: kfree(vmx->guest_msrs); uninit_vcpu: kvm_vcpu_uninit(&vmx->vcpu); free_vcpu: free_vpid(vmx); kmem_cache_free(kvm_vcpu_cache, vmx); return ERR_PTR(err); } static void __init vmx_check_processor_compat(void *rtn) { struct vmcs_config vmcs_conf; *(int *)rtn = 0; if (setup_vmcs_config(&vmcs_conf) < 0) *(int *)rtn = -EIO; if (memcmp(&vmcs_config, &vmcs_conf, sizeof(struct vmcs_config)) != 0) { printk(KERN_ERR "kvm: CPU %d feature inconsistency!\n", smp_processor_id()); *(int *)rtn = -EIO; } } static int get_ept_level(void) { return VMX_EPT_DEFAULT_GAW + 1; } static u64 vmx_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio) { u64 ret; /* For VT-d and EPT combination * 1. MMIO: always map as UC * 2. EPT with VT-d: * a. VT-d without snooping control feature: can't guarantee the * result, try to trust guest. * b. VT-d with snooping control feature: snooping control feature of * VT-d engine can guarantee the cache correctness. Just set it * to WB to keep consistent with host. So the same as item 3. * 3. EPT without VT-d: always map as WB and set IPAT=1 to keep * consistent with host MTRR */ if (is_mmio) ret = MTRR_TYPE_UNCACHABLE << VMX_EPT_MT_EPTE_SHIFT; else if (vcpu->kvm->arch.iommu_domain && !(vcpu->kvm->arch.iommu_flags & KVM_IOMMU_CACHE_COHERENCY)) ret = kvm_get_guest_memory_type(vcpu, gfn) << VMX_EPT_MT_EPTE_SHIFT; else ret = (MTRR_TYPE_WRBACK << VMX_EPT_MT_EPTE_SHIFT) | VMX_EPT_IPAT_BIT; return ret; } static int vmx_get_lpage_level(void) { if (enable_ept && !cpu_has_vmx_ept_1g_page()) return PT_DIRECTORY_LEVEL; else /* For shadow and EPT supported 1GB page */ return PT_PDPE_LEVEL; } static void vmx_cpuid_update(struct kvm_vcpu *vcpu) { struct kvm_cpuid_entry2 *best; struct vcpu_vmx *vmx = to_vmx(vcpu); u32 exec_control; vmx->rdtscp_enabled = false; if (vmx_rdtscp_supported()) { exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL); if (exec_control & SECONDARY_EXEC_RDTSCP) { best = kvm_find_cpuid_entry(vcpu, 0x80000001, 0); if (best && (best->edx & bit(X86_FEATURE_RDTSCP))) vmx->rdtscp_enabled = true; else { exec_control &= ~SECONDARY_EXEC_RDTSCP; vmcs_write32(SECONDARY_VM_EXEC_CONTROL, exec_control); } } } /* Exposing INVPCID only when PCID is exposed */ best = kvm_find_cpuid_entry(vcpu, 0x7, 0); if (vmx_invpcid_supported() && best && (best->ebx & bit(X86_FEATURE_INVPCID)) && guest_cpuid_has_pcid(vcpu)) { exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL); exec_control |= SECONDARY_EXEC_ENABLE_INVPCID; vmcs_write32(SECONDARY_VM_EXEC_CONTROL, exec_control); } else { if (cpu_has_secondary_exec_ctrls()) { exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL); exec_control &= ~SECONDARY_EXEC_ENABLE_INVPCID; vmcs_write32(SECONDARY_VM_EXEC_CONTROL, exec_control); } if (best) best->ebx &= ~bit(X86_FEATURE_INVPCID); } } static void vmx_set_supported_cpuid(u32 func, struct kvm_cpuid_entry2 *entry) { if (func == 1 && nested) entry->ecx |= bit(X86_FEATURE_VMX); } static void nested_ept_inject_page_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault) { struct vmcs12 *vmcs12; nested_vmx_vmexit(vcpu); vmcs12 = get_vmcs12(vcpu); if (fault->error_code & PFERR_RSVD_MASK) vmcs12->vm_exit_reason = EXIT_REASON_EPT_MISCONFIG; else vmcs12->vm_exit_reason = EXIT_REASON_EPT_VIOLATION; vmcs12->exit_qualification = vcpu->arch.exit_qualification; vmcs12->guest_physical_address = fault->address; } /* Callbacks for nested_ept_init_mmu_context: */ static unsigned long nested_ept_get_cr3(struct kvm_vcpu *vcpu) { /* return the page table to be shadowed - in our case, EPT12 */ return get_vmcs12(vcpu)->ept_pointer; } static int nested_ept_init_mmu_context(struct kvm_vcpu *vcpu) { int r = kvm_init_shadow_ept_mmu(vcpu, &vcpu->arch.mmu, nested_vmx_ept_caps & VMX_EPT_EXECUTE_ONLY_BIT); vcpu->arch.mmu.set_cr3 = vmx_set_cr3; vcpu->arch.mmu.get_cr3 = nested_ept_get_cr3; vcpu->arch.mmu.inject_page_fault = nested_ept_inject_page_fault; vcpu->arch.walk_mmu = &vcpu->arch.nested_mmu; return r; } static void nested_ept_uninit_mmu_context(struct kvm_vcpu *vcpu) { vcpu->arch.walk_mmu = &vcpu->arch.mmu; } /* * prepare_vmcs02 is called when the L1 guest hypervisor runs its nested * L2 guest. L1 has a vmcs for L2 (vmcs12), and this function "merges" it * with L0's requirements for its guest (a.k.a. vmsc01), so we can run the L2 * guest in a way that will both be appropriate to L1's requests, and our * needs. In addition to modifying the active vmcs (which is vmcs02), this * function also has additional necessary side-effects, like setting various * vcpu->arch fields. */ static void prepare_vmcs02(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12) { struct vcpu_vmx *vmx = to_vmx(vcpu); u32 exec_control; vmcs_write16(GUEST_ES_SELECTOR, vmcs12->guest_es_selector); vmcs_write16(GUEST_CS_SELECTOR, vmcs12->guest_cs_selector); vmcs_write16(GUEST_SS_SELECTOR, vmcs12->guest_ss_selector); vmcs_write16(GUEST_DS_SELECTOR, vmcs12->guest_ds_selector); vmcs_write16(GUEST_FS_SELECTOR, vmcs12->guest_fs_selector); vmcs_write16(GUEST_GS_SELECTOR, vmcs12->guest_gs_selector); vmcs_write16(GUEST_LDTR_SELECTOR, vmcs12->guest_ldtr_selector); vmcs_write16(GUEST_TR_SELECTOR, vmcs12->guest_tr_selector); vmcs_write32(GUEST_ES_LIMIT, vmcs12->guest_es_limit); vmcs_write32(GUEST_CS_LIMIT, vmcs12->guest_cs_limit); vmcs_write32(GUEST_SS_LIMIT, vmcs12->guest_ss_limit); vmcs_write32(GUEST_DS_LIMIT, vmcs12->guest_ds_limit); vmcs_write32(GUEST_FS_LIMIT, vmcs12->guest_fs_limit); vmcs_write32(GUEST_GS_LIMIT, vmcs12->guest_gs_limit); vmcs_write32(GUEST_LDTR_LIMIT, vmcs12->guest_ldtr_limit); vmcs_write32(GUEST_TR_LIMIT, vmcs12->guest_tr_limit); vmcs_write32(GUEST_GDTR_LIMIT, vmcs12->guest_gdtr_limit); vmcs_write32(GUEST_IDTR_LIMIT, vmcs12->guest_idtr_limit); vmcs_write32(GUEST_ES_AR_BYTES, vmcs12->guest_es_ar_bytes); vmcs_write32(GUEST_CS_AR_BYTES, vmcs12->guest_cs_ar_bytes); vmcs_write32(GUEST_SS_AR_BYTES, vmcs12->guest_ss_ar_bytes); vmcs_write32(GUEST_DS_AR_BYTES, vmcs12->guest_ds_ar_bytes); vmcs_write32(GUEST_FS_AR_BYTES, vmcs12->guest_fs_ar_bytes); vmcs_write32(GUEST_GS_AR_BYTES, vmcs12->guest_gs_ar_bytes); vmcs_write32(GUEST_LDTR_AR_BYTES, vmcs12->guest_ldtr_ar_bytes); vmcs_write32(GUEST_TR_AR_BYTES, vmcs12->guest_tr_ar_bytes); vmcs_writel(GUEST_ES_BASE, vmcs12->guest_es_base); vmcs_writel(GUEST_CS_BASE, vmcs12->guest_cs_base); vmcs_writel(GUEST_SS_BASE, vmcs12->guest_ss_base); vmcs_writel(GUEST_DS_BASE, vmcs12->guest_ds_base); vmcs_writel(GUEST_FS_BASE, vmcs12->guest_fs_base); vmcs_writel(GUEST_GS_BASE, vmcs12->guest_gs_base); vmcs_writel(GUEST_LDTR_BASE, vmcs12->guest_ldtr_base); vmcs_writel(GUEST_TR_BASE, vmcs12->guest_tr_base); vmcs_writel(GUEST_GDTR_BASE, vmcs12->guest_gdtr_base); vmcs_writel(GUEST_IDTR_BASE, vmcs12->guest_idtr_base); vmcs_write64(GUEST_IA32_DEBUGCTL, vmcs12->guest_ia32_debugctl); vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, vmcs12->vm_entry_intr_info_field); vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE, vmcs12->vm_entry_exception_error_code); vmcs_write32(VM_ENTRY_INSTRUCTION_LEN, vmcs12->vm_entry_instruction_len); vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, vmcs12->guest_interruptibility_info); vmcs_write32(GUEST_SYSENTER_CS, vmcs12->guest_sysenter_cs); kvm_set_dr(vcpu, 7, vmcs12->guest_dr7); vmx_set_rflags(vcpu, vmcs12->guest_rflags); vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS, vmcs12->guest_pending_dbg_exceptions); vmcs_writel(GUEST_SYSENTER_ESP, vmcs12->guest_sysenter_esp); vmcs_writel(GUEST_SYSENTER_EIP, vmcs12->guest_sysenter_eip); vmcs_write64(VMCS_LINK_POINTER, -1ull); vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, (vmcs_config.pin_based_exec_ctrl | vmcs12->pin_based_vm_exec_control)); if (vmcs12->pin_based_vm_exec_control & PIN_BASED_VMX_PREEMPTION_TIMER) vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, vmcs12->vmx_preemption_timer_value); /* * Whether page-faults are trapped is determined by a combination of * 3 settings: PFEC_MASK, PFEC_MATCH and EXCEPTION_BITMAP.PF. * If enable_ept, L0 doesn't care about page faults and we should * set all of these to L1's desires. However, if !enable_ept, L0 does * care about (at least some) page faults, and because it is not easy * (if at all possible?) to merge L0 and L1's desires, we simply ask * to exit on each and every L2 page fault. This is done by setting * MASK=MATCH=0 and (see below) EB.PF=1. * Note that below we don't need special code to set EB.PF beyond the * "or"ing of the EB of vmcs01 and vmcs12, because when enable_ept, * vmcs01's EB.PF is 0 so the "or" will take vmcs12's value, and when * !enable_ept, EB.PF is 1, so the "or" will always be 1. * * A problem with this approach (when !enable_ept) is that L1 may be * injected with more page faults than it asked for. This could have * caused problems, but in practice existing hypervisors don't care. * To fix this, we will need to emulate the PFEC checking (on the L1 * page tables), using walk_addr(), when injecting PFs to L1. */ vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, enable_ept ? vmcs12->page_fault_error_code_mask : 0); vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, enable_ept ? vmcs12->page_fault_error_code_match : 0); if (cpu_has_secondary_exec_ctrls()) { u32 exec_control = vmx_secondary_exec_control(vmx); if (!vmx->rdtscp_enabled) exec_control &= ~SECONDARY_EXEC_RDTSCP; /* Take the following fields only from vmcs12 */ exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES; if (nested_cpu_has(vmcs12, CPU_BASED_ACTIVATE_SECONDARY_CONTROLS)) exec_control |= vmcs12->secondary_vm_exec_control; if (exec_control & SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES) { /* * Translate L1 physical address to host physical * address for vmcs02. Keep the page pinned, so this * physical address remains valid. We keep a reference * to it so we can release it later. */ if (vmx->nested.apic_access_page) /* shouldn't happen */ nested_release_page(vmx->nested.apic_access_page); vmx->nested.apic_access_page = nested_get_page(vcpu, vmcs12->apic_access_addr); /* * If translation failed, no matter: This feature asks * to exit when accessing the given address, and if it * can never be accessed, this feature won't do * anything anyway. */ if (!vmx->nested.apic_access_page) exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES; else vmcs_write64(APIC_ACCESS_ADDR, page_to_phys(vmx->nested.apic_access_page)); } vmcs_write32(SECONDARY_VM_EXEC_CONTROL, exec_control); } /* * Set host-state according to L0's settings (vmcs12 is irrelevant here) * Some constant fields are set here by vmx_set_constant_host_state(). * Other fields are different per CPU, and will be set later when * vmx_vcpu_load() is called, and when vmx_save_host_state() is called. */ vmx_set_constant_host_state(vmx); /* * HOST_RSP is normally set correctly in vmx_vcpu_run() just before * entry, but only if the current (host) sp changed from the value * we wrote last (vmx->host_rsp). This cache is no longer relevant * if we switch vmcs, and rather than hold a separate cache per vmcs, * here we just force the write to happen on entry. */ vmx->host_rsp = 0; exec_control = vmx_exec_control(vmx); /* L0's desires */ exec_control &= ~CPU_BASED_VIRTUAL_INTR_PENDING; exec_control &= ~CPU_BASED_VIRTUAL_NMI_PENDING; exec_control &= ~CPU_BASED_TPR_SHADOW; exec_control |= vmcs12->cpu_based_vm_exec_control; /* * Merging of IO and MSR bitmaps not currently supported. * Rather, exit every time. */ exec_control &= ~CPU_BASED_USE_MSR_BITMAPS; exec_control &= ~CPU_BASED_USE_IO_BITMAPS; exec_control |= CPU_BASED_UNCOND_IO_EXITING; vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, exec_control); /* EXCEPTION_BITMAP and CR0_GUEST_HOST_MASK should basically be the * bitwise-or of what L1 wants to trap for L2, and what we want to * trap. Note that CR0.TS also needs updating - we do this later. */ update_exception_bitmap(vcpu); vcpu->arch.cr0_guest_owned_bits &= ~vmcs12->cr0_guest_host_mask; vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits); /* L2->L1 exit controls are emulated - the hardware exit is to L0 so * we should use its exit controls. Note that VM_EXIT_LOAD_IA32_EFER * bits are further modified by vmx_set_efer() below. */ vmcs_write32(VM_EXIT_CONTROLS, vmcs_config.vmexit_ctrl); /* vmcs12's VM_ENTRY_LOAD_IA32_EFER and VM_ENTRY_IA32E_MODE are * emulated by vmx_set_efer(), below. */ vmcs_write32(VM_ENTRY_CONTROLS, (vmcs12->vm_entry_controls & ~VM_ENTRY_LOAD_IA32_EFER & ~VM_ENTRY_IA32E_MODE) | (vmcs_config.vmentry_ctrl & ~VM_ENTRY_IA32E_MODE)); if (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_PAT) vmcs_write64(GUEST_IA32_PAT, vmcs12->guest_ia32_pat); else if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) vmcs_write64(GUEST_IA32_PAT, vmx->vcpu.arch.pat); set_cr4_guest_host_mask(vmx); if (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETING) vmcs_write64(TSC_OFFSET, vmx->nested.vmcs01_tsc_offset + vmcs12->tsc_offset); else vmcs_write64(TSC_OFFSET, vmx->nested.vmcs01_tsc_offset); if (enable_vpid) { /* * Trivially support vpid by letting L2s share their parent * L1's vpid. TODO: move to a more elaborate solution, giving * each L2 its own vpid and exposing the vpid feature to L1. */ vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid); vmx_flush_tlb(vcpu); } if (nested_cpu_has_ept(vmcs12)) { kvm_mmu_unload(vcpu); nested_ept_init_mmu_context(vcpu); } if (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_EFER) vcpu->arch.efer = vmcs12->guest_ia32_efer; else if (vmcs12->vm_entry_controls & VM_ENTRY_IA32E_MODE) vcpu->arch.efer |= (EFER_LMA | EFER_LME); else vcpu->arch.efer &= ~(EFER_LMA | EFER_LME); /* Note: modifies VM_ENTRY/EXIT_CONTROLS and GUEST/HOST_IA32_EFER */ vmx_set_efer(vcpu, vcpu->arch.efer); /* * This sets GUEST_CR0 to vmcs12->guest_cr0, with possibly a modified * TS bit (for lazy fpu) and bits which we consider mandatory enabled. * The CR0_READ_SHADOW is what L2 should have expected to read given * the specifications by L1; It's not enough to take * vmcs12->cr0_read_shadow because on our cr0_guest_host_mask we we * have more bits than L1 expected. */ vmx_set_cr0(vcpu, vmcs12->guest_cr0); vmcs_writel(CR0_READ_SHADOW, nested_read_cr0(vmcs12)); vmx_set_cr4(vcpu, vmcs12->guest_cr4); vmcs_writel(CR4_READ_SHADOW, nested_read_cr4(vmcs12)); /* shadow page tables on either EPT or shadow page tables */ kvm_set_cr3(vcpu, vmcs12->guest_cr3); kvm_mmu_reset_context(vcpu); /* * L1 may access the L2's PDPTR, so save them to construct vmcs12 */ if (enable_ept) { vmcs_write64(GUEST_PDPTR0, vmcs12->guest_pdptr0); vmcs_write64(GUEST_PDPTR1, vmcs12->guest_pdptr1); vmcs_write64(GUEST_PDPTR2, vmcs12->guest_pdptr2); vmcs_write64(GUEST_PDPTR3, vmcs12->guest_pdptr3); } kvm_register_write(vcpu, VCPU_REGS_RSP, vmcs12->guest_rsp); kvm_register_write(vcpu, VCPU_REGS_RIP, vmcs12->guest_rip); } /* * nested_vmx_run() handles a nested entry, i.e., a VMLAUNCH or VMRESUME on L1 * for running an L2 nested guest. */ static int nested_vmx_run(struct kvm_vcpu *vcpu, bool launch) { struct vmcs12 *vmcs12; struct vcpu_vmx *vmx = to_vmx(vcpu); int cpu; struct loaded_vmcs *vmcs02; bool ia32e; if (!nested_vmx_check_permission(vcpu) || !nested_vmx_check_vmcs12(vcpu)) return 1; skip_emulated_instruction(vcpu); vmcs12 = get_vmcs12(vcpu); if (enable_shadow_vmcs) copy_shadow_to_vmcs12(vmx); /* * The nested entry process starts with enforcing various prerequisites * on vmcs12 as required by the Intel SDM, and act appropriately when * they fail: As the SDM explains, some conditions should cause the * instruction to fail, while others will cause the instruction to seem * to succeed, but return an EXIT_REASON_INVALID_STATE. * To speed up the normal (success) code path, we should avoid checking * for misconfigurations which will anyway be caught by the processor * when using the merged vmcs02. */ if (vmcs12->launch_state == launch) { nested_vmx_failValid(vcpu, launch ? VMXERR_VMLAUNCH_NONCLEAR_VMCS : VMXERR_VMRESUME_NONLAUNCHED_VMCS); return 1; } if (vmcs12->guest_activity_state != GUEST_ACTIVITY_ACTIVE) { nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD); return 1; } if ((vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_MSR_BITMAPS) && !IS_ALIGNED(vmcs12->msr_bitmap, PAGE_SIZE)) { /*TODO: Also verify bits beyond physical address width are 0*/ nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD); return 1; } if (nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES) && !IS_ALIGNED(vmcs12->apic_access_addr, PAGE_SIZE)) { /*TODO: Also verify bits beyond physical address width are 0*/ nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD); return 1; } if (vmcs12->vm_entry_msr_load_count > 0 || vmcs12->vm_exit_msr_load_count > 0 || vmcs12->vm_exit_msr_store_count > 0) { pr_warn_ratelimited("%s: VMCS MSR_{LOAD,STORE} unsupported\n", __func__); nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD); return 1; } if (!vmx_control_verify(vmcs12->cpu_based_vm_exec_control, nested_vmx_procbased_ctls_low, nested_vmx_procbased_ctls_high) || !vmx_control_verify(vmcs12->secondary_vm_exec_control, nested_vmx_secondary_ctls_low, nested_vmx_secondary_ctls_high) || !vmx_control_verify(vmcs12->pin_based_vm_exec_control, nested_vmx_pinbased_ctls_low, nested_vmx_pinbased_ctls_high) || !vmx_control_verify(vmcs12->vm_exit_controls, nested_vmx_exit_ctls_low, nested_vmx_exit_ctls_high) || !vmx_control_verify(vmcs12->vm_entry_controls, nested_vmx_entry_ctls_low, nested_vmx_entry_ctls_high)) { nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD); return 1; } if (((vmcs12->host_cr0 & VMXON_CR0_ALWAYSON) != VMXON_CR0_ALWAYSON) || ((vmcs12->host_cr4 & VMXON_CR4_ALWAYSON) != VMXON_CR4_ALWAYSON)) { nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_HOST_STATE_FIELD); return 1; } if (((vmcs12->guest_cr0 & VMXON_CR0_ALWAYSON) != VMXON_CR0_ALWAYSON) || ((vmcs12->guest_cr4 & VMXON_CR4_ALWAYSON) != VMXON_CR4_ALWAYSON)) { nested_vmx_entry_failure(vcpu, vmcs12, EXIT_REASON_INVALID_STATE, ENTRY_FAIL_DEFAULT); return 1; } if (vmcs12->vmcs_link_pointer != -1ull) { nested_vmx_entry_failure(vcpu, vmcs12, EXIT_REASON_INVALID_STATE, ENTRY_FAIL_VMCS_LINK_PTR); return 1; } /* * If the load IA32_EFER VM-entry control is 1, the following checks * are performed on the field for the IA32_EFER MSR: * - Bits reserved in the IA32_EFER MSR must be 0. * - Bit 10 (corresponding to IA32_EFER.LMA) must equal the value of * the IA-32e mode guest VM-exit control. It must also be identical * to bit 8 (LME) if bit 31 in the CR0 field (corresponding to * CR0.PG) is 1. */ if (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_EFER) { ia32e = (vmcs12->vm_entry_controls & VM_ENTRY_IA32E_MODE) != 0; if (!kvm_valid_efer(vcpu, vmcs12->guest_ia32_efer) || ia32e != !!(vmcs12->guest_ia32_efer & EFER_LMA) || ((vmcs12->guest_cr0 & X86_CR0_PG) && ia32e != !!(vmcs12->guest_ia32_efer & EFER_LME))) { nested_vmx_entry_failure(vcpu, vmcs12, EXIT_REASON_INVALID_STATE, ENTRY_FAIL_DEFAULT); return 1; } } /* * If the load IA32_EFER VM-exit control is 1, bits reserved in the * IA32_EFER MSR must be 0 in the field for that register. In addition, * the values of the LMA and LME bits in the field must each be that of * the host address-space size VM-exit control. */ if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_EFER) { ia32e = (vmcs12->vm_exit_controls & VM_EXIT_HOST_ADDR_SPACE_SIZE) != 0; if (!kvm_valid_efer(vcpu, vmcs12->host_ia32_efer) || ia32e != !!(vmcs12->host_ia32_efer & EFER_LMA) || ia32e != !!(vmcs12->host_ia32_efer & EFER_LME)) { nested_vmx_entry_failure(vcpu, vmcs12, EXIT_REASON_INVALID_STATE, ENTRY_FAIL_DEFAULT); return 1; } } /* * We're finally done with prerequisite checking, and can start with * the nested entry. */ vmcs02 = nested_get_current_vmcs02(vmx); if (!vmcs02) return -ENOMEM; enter_guest_mode(vcpu); vmx->nested.vmcs01_tsc_offset = vmcs_read64(TSC_OFFSET); cpu = get_cpu(); vmx->loaded_vmcs = vmcs02; vmx_vcpu_put(vcpu); vmx_vcpu_load(vcpu, cpu); vcpu->cpu = cpu; put_cpu(); vmx_segment_cache_clear(vmx); vmcs12->launch_state = 1; prepare_vmcs02(vcpu, vmcs12); /* * Note no nested_vmx_succeed or nested_vmx_fail here. At this point * we are no longer running L1, and VMLAUNCH/VMRESUME has not yet * returned as far as L1 is concerned. It will only return (and set * the success flag) when L2 exits (see nested_vmx_vmexit()). */ return 1; } /* * On a nested exit from L2 to L1, vmcs12.guest_cr0 might not be up-to-date * because L2 may have changed some cr0 bits directly (CRO_GUEST_HOST_MASK). * This function returns the new value we should put in vmcs12.guest_cr0. * It's not enough to just return the vmcs02 GUEST_CR0. Rather, * 1. Bits that neither L0 nor L1 trapped, were set directly by L2 and are now * available in vmcs02 GUEST_CR0. (Note: It's enough to check that L0 * didn't trap the bit, because if L1 did, so would L0). * 2. Bits that L1 asked to trap (and therefore L0 also did) could not have * been modified by L2, and L1 knows it. So just leave the old value of * the bit from vmcs12.guest_cr0. Note that the bit from vmcs02 GUEST_CR0 * isn't relevant, because if L0 traps this bit it can set it to anything. * 3. Bits that L1 didn't trap, but L0 did. L1 believes the guest could have * changed these bits, and therefore they need to be updated, but L0 * didn't necessarily allow them to be changed in GUEST_CR0 - and rather * put them in vmcs02 CR0_READ_SHADOW. So take these bits from there. */ static inline unsigned long vmcs12_guest_cr0(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12) { return /*1*/ (vmcs_readl(GUEST_CR0) & vcpu->arch.cr0_guest_owned_bits) | /*2*/ (vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask) | /*3*/ (vmcs_readl(CR0_READ_SHADOW) & ~(vmcs12->cr0_guest_host_mask | vcpu->arch.cr0_guest_owned_bits)); } static inline unsigned long vmcs12_guest_cr4(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12) { return /*1*/ (vmcs_readl(GUEST_CR4) & vcpu->arch.cr4_guest_owned_bits) | /*2*/ (vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask) | /*3*/ (vmcs_readl(CR4_READ_SHADOW) & ~(vmcs12->cr4_guest_host_mask | vcpu->arch.cr4_guest_owned_bits)); } static void vmcs12_save_pending_event(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12) { u32 idt_vectoring; unsigned int nr; if (vcpu->arch.exception.pending) { nr = vcpu->arch.exception.nr; idt_vectoring = nr | VECTORING_INFO_VALID_MASK; if (kvm_exception_is_soft(nr)) { vmcs12->vm_exit_instruction_len = vcpu->arch.event_exit_inst_len; idt_vectoring |= INTR_TYPE_SOFT_EXCEPTION; } else idt_vectoring |= INTR_TYPE_HARD_EXCEPTION; if (vcpu->arch.exception.has_error_code) { idt_vectoring |= VECTORING_INFO_DELIVER_CODE_MASK; vmcs12->idt_vectoring_error_code = vcpu->arch.exception.error_code; } vmcs12->idt_vectoring_info_field = idt_vectoring; } else if (vcpu->arch.nmi_pending) { vmcs12->idt_vectoring_info_field = INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR; } else if (vcpu->arch.interrupt.pending) { nr = vcpu->arch.interrupt.nr; idt_vectoring = nr | VECTORING_INFO_VALID_MASK; if (vcpu->arch.interrupt.soft) { idt_vectoring |= INTR_TYPE_SOFT_INTR; vmcs12->vm_entry_instruction_len = vcpu->arch.event_exit_inst_len; } else idt_vectoring |= INTR_TYPE_EXT_INTR; vmcs12->idt_vectoring_info_field = idt_vectoring; } } /* * prepare_vmcs12 is part of what we need to do when the nested L2 guest exits * and we want to prepare to run its L1 parent. L1 keeps a vmcs for L2 (vmcs12), * and this function updates it to reflect the changes to the guest state while * L2 was running (and perhaps made some exits which were handled directly by L0 * without going back to L1), and to reflect the exit reason. * Note that we do not have to copy here all VMCS fields, just those that * could have changed by the L2 guest or the exit - i.e., the guest-state and * exit-information fields only. Other fields are modified by L1 with VMWRITE, * which already writes to vmcs12 directly. */ static void prepare_vmcs12(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12) { /* update guest state fields: */ vmcs12->guest_cr0 = vmcs12_guest_cr0(vcpu, vmcs12); vmcs12->guest_cr4 = vmcs12_guest_cr4(vcpu, vmcs12); kvm_get_dr(vcpu, 7, (unsigned long *)&vmcs12->guest_dr7); vmcs12->guest_rsp = kvm_register_read(vcpu, VCPU_REGS_RSP); vmcs12->guest_rip = kvm_register_read(vcpu, VCPU_REGS_RIP); vmcs12->guest_rflags = vmcs_readl(GUEST_RFLAGS); vmcs12->guest_es_selector = vmcs_read16(GUEST_ES_SELECTOR); vmcs12->guest_cs_selector = vmcs_read16(GUEST_CS_SELECTOR); vmcs12->guest_ss_selector = vmcs_read16(GUEST_SS_SELECTOR); vmcs12->guest_ds_selector = vmcs_read16(GUEST_DS_SELECTOR); vmcs12->guest_fs_selector = vmcs_read16(GUEST_FS_SELECTOR); vmcs12->guest_gs_selector = vmcs_read16(GUEST_GS_SELECTOR); vmcs12->guest_ldtr_selector = vmcs_read16(GUEST_LDTR_SELECTOR); vmcs12->guest_tr_selector = vmcs_read16(GUEST_TR_SELECTOR); vmcs12->guest_es_limit = vmcs_read32(GUEST_ES_LIMIT); vmcs12->guest_cs_limit = vmcs_read32(GUEST_CS_LIMIT); vmcs12->guest_ss_limit = vmcs_read32(GUEST_SS_LIMIT); vmcs12->guest_ds_limit = vmcs_read32(GUEST_DS_LIMIT); vmcs12->guest_fs_limit = vmcs_read32(GUEST_FS_LIMIT); vmcs12->guest_gs_limit = vmcs_read32(GUEST_GS_LIMIT); vmcs12->guest_ldtr_limit = vmcs_read32(GUEST_LDTR_LIMIT); vmcs12->guest_tr_limit = vmcs_read32(GUEST_TR_LIMIT); vmcs12->guest_gdtr_limit = vmcs_read32(GUEST_GDTR_LIMIT); vmcs12->guest_idtr_limit = vmcs_read32(GUEST_IDTR_LIMIT); vmcs12->guest_es_ar_bytes = vmcs_read32(GUEST_ES_AR_BYTES); vmcs12->guest_cs_ar_bytes = vmcs_read32(GUEST_CS_AR_BYTES); vmcs12->guest_ss_ar_bytes = vmcs_read32(GUEST_SS_AR_BYTES); vmcs12->guest_ds_ar_bytes = vmcs_read32(GUEST_DS_AR_BYTES); vmcs12->guest_fs_ar_bytes = vmcs_read32(GUEST_FS_AR_BYTES); vmcs12->guest_gs_ar_bytes = vmcs_read32(GUEST_GS_AR_BYTES); vmcs12->guest_ldtr_ar_bytes = vmcs_read32(GUEST_LDTR_AR_BYTES); vmcs12->guest_tr_ar_bytes = vmcs_read32(GUEST_TR_AR_BYTES); vmcs12->guest_es_base = vmcs_readl(GUEST_ES_BASE); vmcs12->guest_cs_base = vmcs_readl(GUEST_CS_BASE); vmcs12->guest_ss_base = vmcs_readl(GUEST_SS_BASE); vmcs12->guest_ds_base = vmcs_readl(GUEST_DS_BASE); vmcs12->guest_fs_base = vmcs_readl(GUEST_FS_BASE); vmcs12->guest_gs_base = vmcs_readl(GUEST_GS_BASE); vmcs12->guest_ldtr_base = vmcs_readl(GUEST_LDTR_BASE); vmcs12->guest_tr_base = vmcs_readl(GUEST_TR_BASE); vmcs12->guest_gdtr_base = vmcs_readl(GUEST_GDTR_BASE); vmcs12->guest_idtr_base = vmcs_readl(GUEST_IDTR_BASE); vmcs12->guest_interruptibility_info = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO); vmcs12->guest_pending_dbg_exceptions = vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS); /* * In some cases (usually, nested EPT), L2 is allowed to change its * own CR3 without exiting. If it has changed it, we must keep it. * Of course, if L0 is using shadow page tables, GUEST_CR3 was defined * by L0, not L1 or L2, so we mustn't unconditionally copy it to vmcs12. * * Additionally, restore L2's PDPTR to vmcs12. */ if (enable_ept) { vmcs12->guest_cr3 = vmcs_read64(GUEST_CR3); vmcs12->guest_pdptr0 = vmcs_read64(GUEST_PDPTR0); vmcs12->guest_pdptr1 = vmcs_read64(GUEST_PDPTR1); vmcs12->guest_pdptr2 = vmcs_read64(GUEST_PDPTR2); vmcs12->guest_pdptr3 = vmcs_read64(GUEST_PDPTR3); } vmcs12->vm_entry_controls = (vmcs12->vm_entry_controls & ~VM_ENTRY_IA32E_MODE) | (vmcs_read32(VM_ENTRY_CONTROLS) & VM_ENTRY_IA32E_MODE); /* TODO: These cannot have changed unless we have MSR bitmaps and * the relevant bit asks not to trap the change */ vmcs12->guest_ia32_debugctl = vmcs_read64(GUEST_IA32_DEBUGCTL); if (vmcs12->vm_exit_controls & VM_EXIT_SAVE_IA32_PAT) vmcs12->guest_ia32_pat = vmcs_read64(GUEST_IA32_PAT); vmcs12->guest_sysenter_cs = vmcs_read32(GUEST_SYSENTER_CS); vmcs12->guest_sysenter_esp = vmcs_readl(GUEST_SYSENTER_ESP); vmcs12->guest_sysenter_eip = vmcs_readl(GUEST_SYSENTER_EIP); /* update exit information fields: */ vmcs12->vm_exit_reason = to_vmx(vcpu)->exit_reason; vmcs12->exit_qualification = vmcs_readl(EXIT_QUALIFICATION); vmcs12->vm_exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO); if ((vmcs12->vm_exit_intr_info & (INTR_INFO_VALID_MASK | INTR_INFO_DELIVER_CODE_MASK)) == (INTR_INFO_VALID_MASK | INTR_INFO_DELIVER_CODE_MASK)) vmcs12->vm_exit_intr_error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE); vmcs12->idt_vectoring_info_field = 0; vmcs12->vm_exit_instruction_len = vmcs_read32(VM_EXIT_INSTRUCTION_LEN); vmcs12->vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO); if (!(vmcs12->vm_exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY)) { /* vm_entry_intr_info_field is cleared on exit. Emulate this * instead of reading the real value. */ vmcs12->vm_entry_intr_info_field &= ~INTR_INFO_VALID_MASK; /* * Transfer the event that L0 or L1 may wanted to inject into * L2 to IDT_VECTORING_INFO_FIELD. */ vmcs12_save_pending_event(vcpu, vmcs12); } /* * Drop what we picked up for L2 via vmx_complete_interrupts. It is * preserved above and would only end up incorrectly in L1. */ vcpu->arch.nmi_injected = false; kvm_clear_exception_queue(vcpu); kvm_clear_interrupt_queue(vcpu); } /* * A part of what we need to when the nested L2 guest exits and we want to * run its L1 parent, is to reset L1's guest state to the host state specified * in vmcs12. * This function is to be called not only on normal nested exit, but also on * a nested entry failure, as explained in Intel's spec, 3B.23.7 ("VM-Entry * Failures During or After Loading Guest State"). * This function should be called when the active VMCS is L1's (vmcs01). */ static void load_vmcs12_host_state(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12) { struct kvm_segment seg; if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_EFER) vcpu->arch.efer = vmcs12->host_ia32_efer; else if (vmcs12->vm_exit_controls & VM_EXIT_HOST_ADDR_SPACE_SIZE) vcpu->arch.efer |= (EFER_LMA | EFER_LME); else vcpu->arch.efer &= ~(EFER_LMA | EFER_LME); vmx_set_efer(vcpu, vcpu->arch.efer); kvm_register_write(vcpu, VCPU_REGS_RSP, vmcs12->host_rsp); kvm_register_write(vcpu, VCPU_REGS_RIP, vmcs12->host_rip); vmx_set_rflags(vcpu, X86_EFLAGS_FIXED); /* * Note that calling vmx_set_cr0 is important, even if cr0 hasn't * actually changed, because it depends on the current state of * fpu_active (which may have changed). * Note that vmx_set_cr0 refers to efer set above. */ kvm_set_cr0(vcpu, vmcs12->host_cr0); /* * If we did fpu_activate()/fpu_deactivate() during L2's run, we need * to apply the same changes to L1's vmcs. We just set cr0 correctly, * but we also need to update cr0_guest_host_mask and exception_bitmap. */ update_exception_bitmap(vcpu); vcpu->arch.cr0_guest_owned_bits = (vcpu->fpu_active ? X86_CR0_TS : 0); vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits); /* * Note that CR4_GUEST_HOST_MASK is already set in the original vmcs01 * (KVM doesn't change it)- no reason to call set_cr4_guest_host_mask(); */ vcpu->arch.cr4_guest_owned_bits = ~vmcs_readl(CR4_GUEST_HOST_MASK); kvm_set_cr4(vcpu, vmcs12->host_cr4); if (nested_cpu_has_ept(vmcs12)) nested_ept_uninit_mmu_context(vcpu); kvm_set_cr3(vcpu, vmcs12->host_cr3); kvm_mmu_reset_context(vcpu); if (enable_vpid) { /* * Trivially support vpid by letting L2s share their parent * L1's vpid. TODO: move to a more elaborate solution, giving * each L2 its own vpid and exposing the vpid feature to L1. */ vmx_flush_tlb(vcpu); } vmcs_write32(GUEST_SYSENTER_CS, vmcs12->host_ia32_sysenter_cs); vmcs_writel(GUEST_SYSENTER_ESP, vmcs12->host_ia32_sysenter_esp); vmcs_writel(GUEST_SYSENTER_EIP, vmcs12->host_ia32_sysenter_eip); vmcs_writel(GUEST_IDTR_BASE, vmcs12->host_idtr_base); vmcs_writel(GUEST_GDTR_BASE, vmcs12->host_gdtr_base); if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_PAT) vmcs_write64(GUEST_IA32_PAT, vmcs12->host_ia32_pat); if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL) vmcs_write64(GUEST_IA32_PERF_GLOBAL_CTRL, vmcs12->host_ia32_perf_global_ctrl); /* Set L1 segment info according to Intel SDM 27.5.2 Loading Host Segment and Descriptor-Table Registers */ seg = (struct kvm_segment) { .base = 0, .limit = 0xFFFFFFFF, .selector = vmcs12->host_cs_selector, .type = 11, .present = 1, .s = 1, .g = 1 }; if (vmcs12->vm_exit_controls & VM_EXIT_HOST_ADDR_SPACE_SIZE) seg.l = 1; else seg.db = 1; vmx_set_segment(vcpu, &seg, VCPU_SREG_CS); seg = (struct kvm_segment) { .base = 0, .limit = 0xFFFFFFFF, .type = 3, .present = 1, .s = 1, .db = 1, .g = 1 }; seg.selector = vmcs12->host_ds_selector; vmx_set_segment(vcpu, &seg, VCPU_SREG_DS); seg.selector = vmcs12->host_es_selector; vmx_set_segment(vcpu, &seg, VCPU_SREG_ES); seg.selector = vmcs12->host_ss_selector; vmx_set_segment(vcpu, &seg, VCPU_SREG_SS); seg.selector = vmcs12->host_fs_selector; seg.base = vmcs12->host_fs_base; vmx_set_segment(vcpu, &seg, VCPU_SREG_FS); seg.selector = vmcs12->host_gs_selector; seg.base = vmcs12->host_gs_base; vmx_set_segment(vcpu, &seg, VCPU_SREG_GS); seg = (struct kvm_segment) { .base = vmcs12->host_tr_base, .limit = 0x67, .selector = vmcs12->host_tr_selector, .type = 11, .present = 1 }; vmx_set_segment(vcpu, &seg, VCPU_SREG_TR); kvm_set_dr(vcpu, 7, 0x400); vmcs_write64(GUEST_IA32_DEBUGCTL, 0); } /* * Emulate an exit from nested guest (L2) to L1, i.e., prepare to run L1 * and modify vmcs12 to make it see what it would expect to see there if * L2 was its real guest. Must only be called when in L2 (is_guest_mode()) */ static void nested_vmx_vmexit(struct kvm_vcpu *vcpu) { struct vcpu_vmx *vmx = to_vmx(vcpu); int cpu; struct vmcs12 *vmcs12 = get_vmcs12(vcpu); /* trying to cancel vmlaunch/vmresume is a bug */ WARN_ON_ONCE(vmx->nested.nested_run_pending); leave_guest_mode(vcpu); prepare_vmcs12(vcpu, vmcs12); cpu = get_cpu(); vmx->loaded_vmcs = &vmx->vmcs01; vmx_vcpu_put(vcpu); vmx_vcpu_load(vcpu, cpu); vcpu->cpu = cpu; put_cpu(); vmx_segment_cache_clear(vmx); /* if no vmcs02 cache requested, remove the one we used */ if (VMCS02_POOL_SIZE == 0) nested_free_vmcs02(vmx, vmx->nested.current_vmptr); load_vmcs12_host_state(vcpu, vmcs12); /* Update TSC_OFFSET if TSC was changed while L2 ran */ vmcs_write64(TSC_OFFSET, vmx->nested.vmcs01_tsc_offset); /* This is needed for same reason as it was needed in prepare_vmcs02 */ vmx->host_rsp = 0; /* Unpin physical memory we referred to in vmcs02 */ if (vmx->nested.apic_access_page) { nested_release_page(vmx->nested.apic_access_page); vmx->nested.apic_access_page = 0; } /* * Exiting from L2 to L1, we're now back to L1 which thinks it just * finished a VMLAUNCH or VMRESUME instruction, so we need to set the * success or failure flag accordingly. */ if (unlikely(vmx->fail)) { vmx->fail = 0; nested_vmx_failValid(vcpu, vmcs_read32(VM_INSTRUCTION_ERROR)); } else nested_vmx_succeed(vcpu); if (enable_shadow_vmcs) vmx->nested.sync_shadow_vmcs = true; } /* * L1's failure to enter L2 is a subset of a normal exit, as explained in * 23.7 "VM-entry failures during or after loading guest state" (this also * lists the acceptable exit-reason and exit-qualification parameters). * It should only be called before L2 actually succeeded to run, and when * vmcs01 is current (it doesn't leave_guest_mode() or switch vmcss). */ static void nested_vmx_entry_failure(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12, u32 reason, unsigned long qualification) { load_vmcs12_host_state(vcpu, vmcs12); vmcs12->vm_exit_reason = reason | VMX_EXIT_REASONS_FAILED_VMENTRY; vmcs12->exit_qualification = qualification; nested_vmx_succeed(vcpu); if (enable_shadow_vmcs) to_vmx(vcpu)->nested.sync_shadow_vmcs = true; } static int vmx_check_intercept(struct kvm_vcpu *vcpu, struct x86_instruction_info *info, enum x86_intercept_stage stage) { return X86EMUL_CONTINUE; } static struct kvm_x86_ops vmx_x86_ops = { .cpu_has_kvm_support = cpu_has_kvm_support, .disabled_by_bios = vmx_disabled_by_bios, .hardware_setup = hardware_setup, .hardware_unsetup = hardware_unsetup, .check_processor_compatibility = vmx_check_processor_compat, .hardware_enable = hardware_enable, .hardware_disable = hardware_disable, .cpu_has_accelerated_tpr = report_flexpriority, .vcpu_create = vmx_create_vcpu, .vcpu_free = vmx_free_vcpu, .vcpu_reset = vmx_vcpu_reset, .prepare_guest_switch = vmx_save_host_state, .vcpu_load = vmx_vcpu_load, .vcpu_put = vmx_vcpu_put, .update_db_bp_intercept = update_exception_bitmap, .get_msr = vmx_get_msr, .set_msr = vmx_set_msr, .get_segment_base = vmx_get_segment_base, .get_segment = vmx_get_segment, .set_segment = vmx_set_segment, .get_cpl = vmx_get_cpl, .get_cs_db_l_bits = vmx_get_cs_db_l_bits, .decache_cr0_guest_bits = vmx_decache_cr0_guest_bits, .decache_cr3 = vmx_decache_cr3, .decache_cr4_guest_bits = vmx_decache_cr4_guest_bits, .set_cr0 = vmx_set_cr0, .set_cr3 = vmx_set_cr3, .set_cr4 = vmx_set_cr4, .set_efer = vmx_set_efer, .get_idt = vmx_get_idt, .set_idt = vmx_set_idt, .get_gdt = vmx_get_gdt, .set_gdt = vmx_set_gdt, .set_dr7 = vmx_set_dr7, .cache_reg = vmx_cache_reg, .get_rflags = vmx_get_rflags, .set_rflags = vmx_set_rflags, .fpu_activate = vmx_fpu_activate, .fpu_deactivate = vmx_fpu_deactivate, .tlb_flush = vmx_flush_tlb, .run = vmx_vcpu_run, .handle_exit = vmx_handle_exit, .skip_emulated_instruction = skip_emulated_instruction, .set_interrupt_shadow = vmx_set_interrupt_shadow, .get_interrupt_shadow = vmx_get_interrupt_shadow, .patch_hypercall = vmx_patch_hypercall, .set_irq = vmx_inject_irq, .set_nmi = vmx_inject_nmi, .queue_exception = vmx_queue_exception, .cancel_injection = vmx_cancel_injection, .interrupt_allowed = vmx_interrupt_allowed, .nmi_allowed = vmx_nmi_allowed, .get_nmi_mask = vmx_get_nmi_mask, .set_nmi_mask = vmx_set_nmi_mask, .enable_nmi_window = enable_nmi_window, .enable_irq_window = enable_irq_window, .update_cr8_intercept = update_cr8_intercept, .set_virtual_x2apic_mode = vmx_set_virtual_x2apic_mode, .vm_has_apicv = vmx_vm_has_apicv, .load_eoi_exitmap = vmx_load_eoi_exitmap, .hwapic_irr_update = vmx_hwapic_irr_update, .hwapic_isr_update = vmx_hwapic_isr_update, .sync_pir_to_irr = vmx_sync_pir_to_irr, .deliver_posted_interrupt = vmx_deliver_posted_interrupt, .set_tss_addr = vmx_set_tss_addr, .get_tdp_level = get_ept_level, .get_mt_mask = vmx_get_mt_mask, .get_exit_info = vmx_get_exit_info, .get_lpage_level = vmx_get_lpage_level, .cpuid_update = vmx_cpuid_update, .rdtscp_supported = vmx_rdtscp_supported, .invpcid_supported = vmx_invpcid_supported, .set_supported_cpuid = vmx_set_supported_cpuid, .has_wbinvd_exit = cpu_has_vmx_wbinvd_exit, .set_tsc_khz = vmx_set_tsc_khz, .read_tsc_offset = vmx_read_tsc_offset, .write_tsc_offset = vmx_write_tsc_offset, .adjust_tsc_offset = vmx_adjust_tsc_offset, .compute_tsc_offset = vmx_compute_tsc_offset, .read_l1_tsc = vmx_read_l1_tsc, .set_tdp_cr3 = vmx_set_cr3, .check_intercept = vmx_check_intercept, .handle_external_intr = vmx_handle_external_intr, }; static int __init vmx_init(void) { int r, i, msr; rdmsrl_safe(MSR_EFER, &host_efer); for (i = 0; i < NR_VMX_MSR; ++i) kvm_define_shared_msr(i, vmx_msr_index[i]); vmx_io_bitmap_a = (unsigned long *)__get_free_page(GFP_KERNEL); if (!vmx_io_bitmap_a) return -ENOMEM; r = -ENOMEM; vmx_io_bitmap_b = (unsigned long *)__get_free_page(GFP_KERNEL); if (!vmx_io_bitmap_b) goto out; vmx_msr_bitmap_legacy = (unsigned long *)__get_free_page(GFP_KERNEL); if (!vmx_msr_bitmap_legacy) goto out1; vmx_msr_bitmap_legacy_x2apic = (unsigned long *)__get_free_page(GFP_KERNEL); if (!vmx_msr_bitmap_legacy_x2apic) goto out2; vmx_msr_bitmap_longmode = (unsigned long *)__get_free_page(GFP_KERNEL); if (!vmx_msr_bitmap_longmode) goto out3; vmx_msr_bitmap_longmode_x2apic = (unsigned long *)__get_free_page(GFP_KERNEL); if (!vmx_msr_bitmap_longmode_x2apic) goto out4; vmx_vmread_bitmap = (unsigned long *)__get_free_page(GFP_KERNEL); if (!vmx_vmread_bitmap) goto out5; vmx_vmwrite_bitmap = (unsigned long *)__get_free_page(GFP_KERNEL); if (!vmx_vmwrite_bitmap) goto out6; memset(vmx_vmread_bitmap, 0xff, PAGE_SIZE); memset(vmx_vmwrite_bitmap, 0xff, PAGE_SIZE); /* shadowed read/write fields */ for (i = 0; i < max_shadow_read_write_fields; i++) { clear_bit(shadow_read_write_fields[i], vmx_vmwrite_bitmap); clear_bit(shadow_read_write_fields[i], vmx_vmread_bitmap); } /* shadowed read only fields */ for (i = 0; i < max_shadow_read_only_fields; i++) clear_bit(shadow_read_only_fields[i], vmx_vmread_bitmap); /* * Allow direct access to the PC debug port (it is often used for I/O * delays, but the vmexits simply slow things down). */ memset(vmx_io_bitmap_a, 0xff, PAGE_SIZE); clear_bit(0x80, vmx_io_bitmap_a); memset(vmx_io_bitmap_b, 0xff, PAGE_SIZE); memset(vmx_msr_bitmap_legacy, 0xff, PAGE_SIZE); memset(vmx_msr_bitmap_longmode, 0xff, PAGE_SIZE); set_bit(0, vmx_vpid_bitmap); /* 0 is reserved for host */ r = kvm_init(&vmx_x86_ops, sizeof(struct vcpu_vmx), __alignof__(struct vcpu_vmx), THIS_MODULE); if (r) goto out7; #ifdef CONFIG_KEXEC rcu_assign_pointer(crash_vmclear_loaded_vmcss, crash_vmclear_local_loaded_vmcss); #endif vmx_disable_intercept_for_msr(MSR_FS_BASE, false); vmx_disable_intercept_for_msr(MSR_GS_BASE, false); vmx_disable_intercept_for_msr(MSR_KERNEL_GS_BASE, true); vmx_disable_intercept_for_msr(MSR_IA32_SYSENTER_CS, false); vmx_disable_intercept_for_msr(MSR_IA32_SYSENTER_ESP, false); vmx_disable_intercept_for_msr(MSR_IA32_SYSENTER_EIP, false); memcpy(vmx_msr_bitmap_legacy_x2apic, vmx_msr_bitmap_legacy, PAGE_SIZE); memcpy(vmx_msr_bitmap_longmode_x2apic, vmx_msr_bitmap_longmode, PAGE_SIZE); if (enable_apicv) { for (msr = 0x800; msr <= 0x8ff; msr++) vmx_disable_intercept_msr_read_x2apic(msr); /* According SDM, in x2apic mode, the whole id reg is used. * But in KVM, it only use the highest eight bits. Need to * intercept it */ vmx_enable_intercept_msr_read_x2apic(0x802); /* TMCCT */ vmx_enable_intercept_msr_read_x2apic(0x839); /* TPR */ vmx_disable_intercept_msr_write_x2apic(0x808); /* EOI */ vmx_disable_intercept_msr_write_x2apic(0x80b); /* SELF-IPI */ vmx_disable_intercept_msr_write_x2apic(0x83f); } if (enable_ept) { kvm_mmu_set_mask_ptes(0ull, (enable_ept_ad_bits) ? VMX_EPT_ACCESS_BIT : 0ull, (enable_ept_ad_bits) ? VMX_EPT_DIRTY_BIT : 0ull, 0ull, VMX_EPT_EXECUTABLE_MASK); ept_set_mmio_spte_mask(); kvm_enable_tdp(); } else kvm_disable_tdp(); return 0; out7: free_page((unsigned long)vmx_vmwrite_bitmap); out6: free_page((unsigned long)vmx_vmread_bitmap); out5: free_page((unsigned long)vmx_msr_bitmap_longmode_x2apic); out4: free_page((unsigned long)vmx_msr_bitmap_longmode); out3: free_page((unsigned long)vmx_msr_bitmap_legacy_x2apic); out2: free_page((unsigned long)vmx_msr_bitmap_legacy); out1: free_page((unsigned long)vmx_io_bitmap_b); out: free_page((unsigned long)vmx_io_bitmap_a); return r; } static void __exit vmx_exit(void) { free_page((unsigned long)vmx_msr_bitmap_legacy_x2apic); free_page((unsigned long)vmx_msr_bitmap_longmode_x2apic); free_page((unsigned long)vmx_msr_bitmap_legacy); free_page((unsigned long)vmx_msr_bitmap_longmode); free_page((unsigned long)vmx_io_bitmap_b); free_page((unsigned long)vmx_io_bitmap_a); free_page((unsigned long)vmx_vmwrite_bitmap); free_page((unsigned long)vmx_vmread_bitmap); #ifdef CONFIG_KEXEC rcu_assign_pointer(crash_vmclear_loaded_vmcss, NULL); synchronize_rcu(); #endif kvm_exit(); } module_init(vmx_init) module_exit(vmx_exit)
./CrossVul/dataset_final_sorted/CWE-20/c/bad_2162_3
crossvul-cpp_data_bad_3088_0
/* bubblewrap * Copyright (C) 2016 Alexander Larsson * * This program 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, see <http://www.gnu.org/licenses/>. * */ #include "config.h" #include <poll.h> #include <sched.h> #include <pwd.h> #include <grp.h> #include <sys/mount.h> #include <sys/socket.h> #include <sys/wait.h> #include <sys/eventfd.h> #include <sys/fsuid.h> #include <sys/signalfd.h> #include <sys/capability.h> #include <sys/prctl.h> #include <linux/sched.h> #include <linux/seccomp.h> #include <linux/filter.h> #include "utils.h" #include "network.h" #include "bind-mount.h" #ifndef CLONE_NEWCGROUP #define CLONE_NEWCGROUP 0x02000000 /* New cgroup namespace */ #endif /* Globals to avoid having to use getuid(), since the uid/gid changes during runtime */ static uid_t real_uid; static gid_t real_gid; static uid_t overflow_uid; static gid_t overflow_gid; static bool is_privileged; static const char *argv0; static const char *host_tty_dev; static int proc_fd = -1; static char *opt_exec_label = NULL; static char *opt_file_label = NULL; char *opt_chdir_path = NULL; bool opt_unshare_user = FALSE; bool opt_unshare_user_try = FALSE; bool opt_unshare_pid = FALSE; bool opt_unshare_ipc = FALSE; bool opt_unshare_net = FALSE; bool opt_unshare_uts = FALSE; bool opt_unshare_cgroup = FALSE; bool opt_unshare_cgroup_try = FALSE; bool opt_needs_devpts = FALSE; uid_t opt_sandbox_uid = -1; gid_t opt_sandbox_gid = -1; int opt_sync_fd = -1; int opt_block_fd = -1; int opt_info_fd = -1; int opt_seccomp_fd = -1; char *opt_sandbox_hostname = NULL; typedef enum { SETUP_BIND_MOUNT, SETUP_RO_BIND_MOUNT, SETUP_DEV_BIND_MOUNT, SETUP_MOUNT_PROC, SETUP_MOUNT_DEV, SETUP_MOUNT_TMPFS, SETUP_MOUNT_MQUEUE, SETUP_MAKE_DIR, SETUP_MAKE_FILE, SETUP_MAKE_BIND_FILE, SETUP_MAKE_RO_BIND_FILE, SETUP_MAKE_SYMLINK, SETUP_REMOUNT_RO_NO_RECURSIVE, SETUP_SET_HOSTNAME, } SetupOpType; typedef enum { NO_CREATE_DEST = (1 << 0), } SetupOpFlag; typedef struct _SetupOp SetupOp; struct _SetupOp { SetupOpType type; const char *source; const char *dest; int fd; SetupOpFlag flags; SetupOp *next; }; typedef struct _LockFile LockFile; struct _LockFile { const char *path; LockFile *next; }; static SetupOp *ops = NULL; static SetupOp *last_op = NULL; static LockFile *lock_files = NULL; static LockFile *last_lock_file = NULL; enum { PRIV_SEP_OP_DONE, PRIV_SEP_OP_BIND_MOUNT, PRIV_SEP_OP_PROC_MOUNT, PRIV_SEP_OP_TMPFS_MOUNT, PRIV_SEP_OP_DEVPTS_MOUNT, PRIV_SEP_OP_MQUEUE_MOUNT, PRIV_SEP_OP_REMOUNT_RO_NO_RECURSIVE, PRIV_SEP_OP_SET_HOSTNAME, }; typedef struct { uint32_t op; uint32_t flags; uint32_t arg1_offset; uint32_t arg2_offset; } PrivSepOp; static SetupOp * setup_op_new (SetupOpType type) { SetupOp *op = xcalloc (sizeof (SetupOp)); op->type = type; op->fd = -1; op->flags = 0; if (last_op != NULL) last_op->next = op; else ops = op; last_op = op; return op; } static LockFile * lock_file_new (const char *path) { LockFile *lock = xcalloc (sizeof (LockFile)); lock->path = path; if (last_lock_file != NULL) last_lock_file->next = lock; else lock_files = lock; last_lock_file = lock; return lock; } static void usage (int ecode, FILE *out) { fprintf (out, "usage: %s [OPTIONS...] COMMAND [ARGS...]\n\n", argv0); fprintf (out, " --help Print this help\n" " --version Print version\n" " --args FD Parse nul-separated args from FD\n" " --unshare-user Create new user namespace (may be automatically implied if not setuid)\n" " --unshare-user-try Create new user namespace if possible else continue by skipping it\n" " --unshare-ipc Create new ipc namespace\n" " --unshare-pid Create new pid namespace\n" " --unshare-net Create new network namespace\n" " --unshare-uts Create new uts namespace\n" " --unshare-cgroup Create new cgroup namespace\n" " --unshare-cgroup-try Create new cgroup namespace if possible else continue by skipping it\n" " --uid UID Custom uid in the sandbox (requires --unshare-user)\n" " --gid GID Custon gid in the sandbox (requires --unshare-user)\n" " --hostname NAME Custom hostname in the sandbox (requires --unshare-uts)\n" " --chdir DIR Change directory to DIR\n" " --setenv VAR VALUE Set an environment variable\n" " --unsetenv VAR Unset an environment variable\n" " --lock-file DEST Take a lock on DEST while sandbox is running\n" " --sync-fd FD Keep this fd open while sandbox is running\n" " --bind SRC DEST Bind mount the host path SRC on DEST\n" " --dev-bind SRC DEST Bind mount the host path SRC on DEST, allowing device access\n" " --ro-bind SRC DEST Bind mount the host path SRC readonly on DEST\n" " --remount-ro DEST Remount DEST as readonly, it doesn't recursively remount\n" " --exec-label LABEL Exec Label for the sandbox\n" " --file-label LABEL File label for temporary sandbox content\n" " --proc DEST Mount procfs on DEST\n" " --dev DEST Mount new dev on DEST\n" " --tmpfs DEST Mount new tmpfs on DEST\n" " --mqueue DEST Mount new mqueue on DEST\n" " --dir DEST Create dir at DEST\n" " --file FD DEST Copy from FD to dest DEST\n" " --bind-data FD DEST Copy from FD to file which is bind-mounted on DEST\n" " --ro-bind-data FD DEST Copy from FD to file which is readonly bind-mounted on DEST\n" " --symlink SRC DEST Create symlink at DEST with target SRC\n" " --seccomp FD Load and use seccomp rules from FD\n" " --block-fd FD Block on FD until some data to read is available\n" " --info-fd FD Write information about the running container to FD\n" ); exit (ecode); } static void block_sigchild (void) { sigset_t mask; sigemptyset (&mask); sigaddset (&mask, SIGCHLD); if (sigprocmask (SIG_BLOCK, &mask, NULL) == -1) die_with_error ("sigprocmask"); } static void unblock_sigchild (void) { sigset_t mask; sigemptyset (&mask); sigaddset (&mask, SIGCHLD); if (sigprocmask (SIG_UNBLOCK, &mask, NULL) == -1) die_with_error ("sigprocmask"); } /* Closes all fd:s except 0,1,2 and the passed in array of extra fds */ static int close_extra_fds (void *data, int fd) { int *extra_fds = (int *) data; int i; for (i = 0; extra_fds[i] != -1; i++) if (fd == extra_fds[i]) return 0; if (fd <= 2) return 0; close (fd); return 0; } /* This stays around for as long as the initial process in the app does * and when that exits it exits, propagating the exit status. We do this * by having pid 1 in the sandbox detect this exit and tell the monitor * the exit status via a eventfd. We also track the exit of the sandbox * pid 1 via a signalfd for SIGCHLD, and exit with an error in this case. * This is to catch e.g. problems during setup. */ static void monitor_child (int event_fd) { int res; uint64_t val; ssize_t s; int signal_fd; sigset_t mask; struct pollfd fds[2]; int num_fds; struct signalfd_siginfo fdsi; int dont_close[] = { event_fd, -1 }; /* Close all extra fds in the monitoring process. Any passed in fds have been passed on to the child anyway. */ fdwalk (proc_fd, close_extra_fds, dont_close); sigemptyset (&mask); sigaddset (&mask, SIGCHLD); signal_fd = signalfd (-1, &mask, SFD_CLOEXEC | SFD_NONBLOCK); if (signal_fd == -1) die_with_error ("Can't create signalfd"); num_fds = 1; fds[0].fd = signal_fd; fds[0].events = POLLIN; if (event_fd != -1) { fds[1].fd = event_fd; fds[1].events = POLLIN; num_fds++; } while (1) { fds[0].revents = fds[1].revents = 0; res = poll (fds, num_fds, -1); if (res == -1 && errno != EINTR) die_with_error ("poll"); /* Always read from the eventfd first, if pid 2 died then pid 1 often * dies too, and we could race, reporting that first and we'd lose * the real exit status. */ if (event_fd != -1) { s = read (event_fd, &val, 8); if (s == -1 && errno != EINTR && errno != EAGAIN) die_with_error ("read eventfd"); else if (s == 8) exit ((int) val - 1); } s = read (signal_fd, &fdsi, sizeof (struct signalfd_siginfo)); if (s == -1 && errno != EINTR && errno != EAGAIN) { die_with_error ("read signalfd"); } else if (s == sizeof (struct signalfd_siginfo)) { if (fdsi.ssi_signo != SIGCHLD) die ("Read unexpected signal\n"); exit (fdsi.ssi_status); } } } /* This is pid 1 in the app sandbox. It is needed because we're using * pid namespaces, and someone has to reap zombies in it. We also detect * when the initial process (pid 2) dies and report its exit status to * the monitor so that it can return it to the original spawner. * * When there are no other processes in the sandbox the wait will return * ECHILD, and we then exit pid 1 to clean up the sandbox. */ static int do_init (int event_fd, pid_t initial_pid) { int initial_exit_status = 1; LockFile *lock; for (lock = lock_files; lock != NULL; lock = lock->next) { int fd = open (lock->path, O_RDONLY | O_CLOEXEC); if (fd == -1) die_with_error ("Unable to open lock file %s", lock->path); struct flock l = { .l_type = F_RDLCK, .l_whence = SEEK_SET, .l_start = 0, .l_len = 0 }; if (fcntl (fd, F_SETLK, &l) < 0) die_with_error ("Unable to lock file %s", lock->path); /* Keep fd open to hang on to lock */ } while (TRUE) { pid_t child; int status; child = wait (&status); if (child == initial_pid && event_fd != -1) { uint64_t val; int res UNUSED; if (WIFEXITED (status)) initial_exit_status = WEXITSTATUS (status); val = initial_exit_status + 1; res = write (event_fd, &val, 8); /* Ignore res, if e.g. the parent died and closed event_fd we don't want to error out here */ } if (child == -1 && errno != EINTR) { if (errno != ECHILD) die_with_error ("init wait()"); break; } } return initial_exit_status; } /* low 32bit caps needed */ #define REQUIRED_CAPS_0 (CAP_TO_MASK (CAP_SYS_ADMIN) | CAP_TO_MASK (CAP_SYS_CHROOT) | CAP_TO_MASK (CAP_NET_ADMIN) | CAP_TO_MASK (CAP_SETUID) | CAP_TO_MASK (CAP_SETGID)) /* high 32bit caps needed */ #define REQUIRED_CAPS_1 0 static void set_required_caps (void) { struct __user_cap_header_struct hdr = { _LINUX_CAPABILITY_VERSION_3, 0 }; struct __user_cap_data_struct data[2] = { { 0 } }; /* Drop all non-require capabilities */ data[0].effective = REQUIRED_CAPS_0; data[0].permitted = REQUIRED_CAPS_0; data[0].inheritable = 0; data[1].effective = REQUIRED_CAPS_1; data[1].permitted = REQUIRED_CAPS_1; data[1].inheritable = 0; if (capset (&hdr, data) < 0) die_with_error ("capset failed"); } static void drop_all_caps (void) { struct __user_cap_header_struct hdr = { _LINUX_CAPABILITY_VERSION_3, 0 }; struct __user_cap_data_struct data[2] = { { 0 } }; if (capset (&hdr, data) < 0) die_with_error ("capset failed"); } static bool has_caps (void) { struct __user_cap_header_struct hdr = { _LINUX_CAPABILITY_VERSION_3, 0 }; struct __user_cap_data_struct data[2] = { { 0 } }; if (capget (&hdr, data) < 0) die_with_error ("capget failed"); return data[0].permitted != 0 || data[1].permitted != 0; } /* This acquires the privileges that the bwrap will need it to work. * If bwrap is not setuid, then this does nothing, and it relies on * unprivileged user namespaces to be used. This case is * "is_privileged = FALSE". * * If bwrap is setuid, then we do things in phases. * The first part is run as euid 0, but with with fsuid as the real user. * The second part, inside the child, is run as the real user but with * capabilities. * And finally we drop all capabilities. * The reason for the above dance is to avoid having the setup phase * being able to read files the user can't, while at the same time * working around various kernel issues. See below for details. */ static void acquire_privs (void) { uid_t euid, new_fsuid; euid = geteuid (); /* Are we setuid ? */ if (real_uid != euid) { if (euid == 0) is_privileged = TRUE; else die ("Unexpected setuid user %d, should be 0", euid); /* We want to keep running as euid=0 until at the clone() * operation because doing so will make the user namespace be * owned by root, which makes it not ptrace:able by the user as * it otherwise would be. After that we will run fully as the * user, which is necessary e.g. to be able to read from a fuse * mount from the user. * * However, we don't want to accidentally mis-use euid=0 for * escalated filesystem access before the clone(), so we set * fsuid to the uid. */ if (setfsuid (real_uid) < 0) die_with_error ("Unable to set fsuid"); /* setfsuid can't properly report errors, check that it worked (as per manpage) */ new_fsuid = setfsuid (-1); if (new_fsuid != real_uid) die ("Unable to set fsuid (was %d)", (int)new_fsuid); /* Keep only the required capabilities for setup */ set_required_caps (); } else if (real_uid != 0 && has_caps ()) { /* We have some capabilities in the non-setuid case, which should not happen. Probably caused by the binary being setcap instead of setuid which we don't support anymore */ die ("Unexpected capabilities but not setuid, old file caps config?"); } /* Else, we try unprivileged user namespaces */ } /* This is called once we're inside the namespace */ static void switch_to_user_with_privs (void) { if (!is_privileged) return; /* Tell kernel not clear capabilities when later dropping root uid */ if (prctl (PR_SET_KEEPCAPS, 1, 0, 0, 0) < 0) die_with_error ("prctl(PR_SET_KEEPCAPS) failed"); if (setuid (opt_sandbox_uid) < 0) die_with_error ("unable to drop root uid"); /* Regain effective required capabilities from permitted */ set_required_caps (); } static void drop_privs (void) { if (!is_privileged) return; /* Drop root uid */ if (setuid (opt_sandbox_uid) < 0) die_with_error ("unable to drop root uid"); drop_all_caps (); } static char * get_newroot_path (const char *path) { while (*path == '/') path++; return strconcat ("/newroot/", path); } static char * get_oldroot_path (const char *path) { while (*path == '/') path++; return strconcat ("/oldroot/", path); } static void write_uid_gid_map (uid_t sandbox_uid, uid_t parent_uid, uid_t sandbox_gid, uid_t parent_gid, pid_t pid, bool deny_groups, bool map_root) { cleanup_free char *uid_map = NULL; cleanup_free char *gid_map = NULL; cleanup_free char *dir = NULL; cleanup_fd int dir_fd = -1; uid_t old_fsuid = -1; if (pid == -1) dir = xstrdup ("self"); else dir = xasprintf ("%d", pid); dir_fd = openat (proc_fd, dir, O_RDONLY | O_PATH); if (dir_fd < 0) die_with_error ("open /proc/%s failed", dir); if (map_root && parent_uid != 0 && sandbox_uid != 0) uid_map = xasprintf ("0 %d 1\n" "%d %d 1\n", overflow_uid, sandbox_uid, parent_uid); else uid_map = xasprintf ("%d %d 1\n", sandbox_uid, parent_uid); if (map_root && parent_gid != 0 && sandbox_gid != 0) gid_map = xasprintf ("0 %d 1\n" "%d %d 1\n", overflow_gid, sandbox_gid, parent_gid); else gid_map = xasprintf ("%d %d 1\n", sandbox_gid, parent_gid); /* We have to be root to be allowed to write to the uid map * for setuid apps, so temporary set fsuid to 0 */ if (is_privileged) old_fsuid = setfsuid (0); if (write_file_at (dir_fd, "uid_map", uid_map) != 0) die_with_error ("setting up uid map"); if (deny_groups && write_file_at (dir_fd, "setgroups", "deny\n") != 0) { /* If /proc/[pid]/setgroups does not exist, assume we are * running a linux kernel < 3.19, i.e. we live with the * vulnerability known as CVE-2014-8989 in older kernels * where setgroups does not exist. */ if (errno != ENOENT) die_with_error ("error writing to setgroups"); } if (write_file_at (dir_fd, "gid_map", gid_map) != 0) die_with_error ("setting up gid map"); if (is_privileged) { setfsuid (old_fsuid); if (setfsuid (-1) != real_uid) die ("Unable to re-set fsuid"); } } static void privileged_op (int privileged_op_socket, uint32_t op, uint32_t flags, const char *arg1, const char *arg2) { if (privileged_op_socket != -1) { uint32_t buffer[2048]; /* 8k, but is int32 to guarantee nice alignment */ PrivSepOp *op_buffer = (PrivSepOp *) buffer; size_t buffer_size = sizeof (PrivSepOp); uint32_t arg1_offset = 0, arg2_offset = 0; /* We're unprivileged, send this request to the privileged part */ if (arg1 != NULL) { arg1_offset = buffer_size; buffer_size += strlen (arg1) + 1; } if (arg2 != NULL) { arg2_offset = buffer_size; buffer_size += strlen (arg2) + 1; } if (buffer_size >= sizeof (buffer)) die ("privilege separation operation to large"); op_buffer->op = op; op_buffer->flags = flags; op_buffer->arg1_offset = arg1_offset; op_buffer->arg2_offset = arg2_offset; if (arg1 != NULL) strcpy ((char *) buffer + arg1_offset, arg1); if (arg2 != NULL) strcpy ((char *) buffer + arg2_offset, arg2); if (write (privileged_op_socket, buffer, buffer_size) != buffer_size) die ("Can't write to privileged_op_socket"); if (read (privileged_op_socket, buffer, 1) != 1) die ("Can't read from privileged_op_socket"); return; } /* * This runs a privileged request for the unprivileged setup * code. Note that since the setup code is unprivileged it is not as * trusted, so we need to verify that all requests only affect the * child namespace as set up by the privileged parts of the setup, * and that all the code is very careful about handling input. * * This means: * * Bind mounts are safe, since we always use filesystem namespace. They * must be recursive though, as otherwise you can use a non-recursive bind * mount to access an otherwise over-mounted mountpoint. * * Mounting proc, tmpfs, mqueue, devpts in the child namespace is assumed to * be safe. * * Remounting RO (even non-recursive) is safe because it decreases privileges. * * sethostname() is safe only if we set up a UTS namespace */ switch (op) { case PRIV_SEP_OP_DONE: break; case PRIV_SEP_OP_REMOUNT_RO_NO_RECURSIVE: if (bind_mount (proc_fd, NULL, arg2, BIND_READONLY) != 0) die_with_error ("Can't remount readonly on %s", arg2); break; case PRIV_SEP_OP_BIND_MOUNT: /* We always bind directories recursively, otherwise this would let us access files that are otherwise covered on the host */ if (bind_mount (proc_fd, arg1, arg2, BIND_RECURSIVE | flags) != 0) die_with_error ("Can't bind mount %s on %s", arg1, arg2); break; case PRIV_SEP_OP_PROC_MOUNT: if (mount ("proc", arg1, "proc", MS_MGC_VAL | MS_NOSUID | MS_NOEXEC | MS_NODEV, NULL) != 0) die_with_error ("Can't mount proc on %s", arg1); break; case PRIV_SEP_OP_TMPFS_MOUNT: { cleanup_free char *opt = label_mount ("mode=0755", opt_file_label); if (mount ("tmpfs", arg1, "tmpfs", MS_MGC_VAL | MS_NOSUID | MS_NODEV, opt) != 0) die_with_error ("Can't mount tmpfs on %s", arg1); break; } case PRIV_SEP_OP_DEVPTS_MOUNT: if (mount ("devpts", arg1, "devpts", MS_MGC_VAL | MS_NOSUID | MS_NOEXEC, "newinstance,ptmxmode=0666,mode=620") != 0) die_with_error ("Can't mount devpts on %s", arg1); break; case PRIV_SEP_OP_MQUEUE_MOUNT: if (mount ("mqueue", arg1, "mqueue", 0, NULL) != 0) die_with_error ("Can't mount mqueue on %s", arg1); break; case PRIV_SEP_OP_SET_HOSTNAME: /* This is checked at the start, but lets verify it here in case something manages to send hacked priv-sep operation requests. */ if (!opt_unshare_uts) die ("Refusing to set hostname in original namespace"); if (sethostname (arg1, strlen(arg1)) != 0) die_with_error ("Can't set hostname to %s", arg1); break; default: die ("Unexpected privileged op %d", op); } } /* This is run unprivileged in the child namespace but can request * some privileged operations (also in the child namespace) via the * privileged_op_socket. */ static void setup_newroot (bool unshare_pid, int privileged_op_socket) { SetupOp *op; for (op = ops; op != NULL; op = op->next) { cleanup_free char *source = NULL; cleanup_free char *dest = NULL; int source_mode = 0; int i; if (op->source && op->type != SETUP_MAKE_SYMLINK) { source = get_oldroot_path (op->source); source_mode = get_file_mode (source); if (source_mode < 0) die_with_error ("Can't get type of source %s", op->source); } if (op->dest && (op->flags & NO_CREATE_DEST) == 0) { dest = get_newroot_path (op->dest); if (mkdir_with_parents (dest, 0755, FALSE) != 0) die_with_error ("Can't mkdir parents for %s", op->dest); } switch (op->type) { case SETUP_RO_BIND_MOUNT: case SETUP_DEV_BIND_MOUNT: case SETUP_BIND_MOUNT: if (source_mode == S_IFDIR) { if (mkdir (dest, 0755) != 0 && errno != EEXIST) die_with_error ("Can't mkdir %s", op->dest); } else if (ensure_file (dest, 0666) != 0) die_with_error ("Can't create file at %s", op->dest); privileged_op (privileged_op_socket, PRIV_SEP_OP_BIND_MOUNT, (op->type == SETUP_RO_BIND_MOUNT ? BIND_READONLY : 0) | (op->type == SETUP_DEV_BIND_MOUNT ? BIND_DEVICES : 0), source, dest); break; case SETUP_REMOUNT_RO_NO_RECURSIVE: privileged_op (privileged_op_socket, PRIV_SEP_OP_REMOUNT_RO_NO_RECURSIVE, BIND_READONLY, NULL, dest); break; case SETUP_MOUNT_PROC: if (mkdir (dest, 0755) != 0 && errno != EEXIST) die_with_error ("Can't mkdir %s", op->dest); if (unshare_pid) { /* Our own procfs */ privileged_op (privileged_op_socket, PRIV_SEP_OP_PROC_MOUNT, 0, dest, NULL); } else { /* Use system procfs, as we share pid namespace anyway */ privileged_op (privileged_op_socket, PRIV_SEP_OP_BIND_MOUNT, 0, "oldroot/proc", dest); } /* There are a bunch of weird old subdirs of /proc that could potentially be problematic (for instance /proc/sysrq-trigger lets you shut down the machine if you have write access). We should not have access to these as a non-privileged user, but lets cover them anyway just to make sure */ const char *cover_proc_dirs[] = { "sys", "sysrq-trigger", "irq", "bus" }; for (i = 0; i < N_ELEMENTS (cover_proc_dirs); i++) { cleanup_free char *subdir = strconcat3 (dest, "/", cover_proc_dirs[i]); privileged_op (privileged_op_socket, PRIV_SEP_OP_BIND_MOUNT, BIND_READONLY, subdir, subdir); } break; case SETUP_MOUNT_DEV: if (mkdir (dest, 0755) != 0 && errno != EEXIST) die_with_error ("Can't mkdir %s", op->dest); privileged_op (privileged_op_socket, PRIV_SEP_OP_TMPFS_MOUNT, 0, dest, NULL); static const char *const devnodes[] = { "null", "zero", "full", "random", "urandom", "tty" }; for (i = 0; i < N_ELEMENTS (devnodes); i++) { cleanup_free char *node_dest = strconcat3 (dest, "/", devnodes[i]); cleanup_free char *node_src = strconcat ("/oldroot/dev/", devnodes[i]); if (create_file (node_dest, 0666, NULL) != 0) die_with_error ("Can't create file %s/%s", op->dest, devnodes[i]); privileged_op (privileged_op_socket, PRIV_SEP_OP_BIND_MOUNT, BIND_DEVICES, node_src, node_dest); } static const char *const stdionodes[] = { "stdin", "stdout", "stderr" }; for (i = 0; i < N_ELEMENTS (stdionodes); i++) { cleanup_free char *target = xasprintf ("/proc/self/fd/%d", i); cleanup_free char *node_dest = strconcat3 (dest, "/", stdionodes[i]); if (symlink (target, node_dest) < 0) die_with_error ("Can't create symlink %s/%s", op->dest, stdionodes[i]); } { cleanup_free char *pts = strconcat (dest, "/pts"); cleanup_free char *ptmx = strconcat (dest, "/ptmx"); cleanup_free char *shm = strconcat (dest, "/shm"); if (mkdir (shm, 0755) == -1) die_with_error ("Can't create %s/shm", op->dest); if (mkdir (pts, 0755) == -1) die_with_error ("Can't create %s/devpts", op->dest); privileged_op (privileged_op_socket, PRIV_SEP_OP_DEVPTS_MOUNT, BIND_DEVICES, pts, NULL); if (symlink ("pts/ptmx", ptmx) != 0) die_with_error ("Can't make symlink at %s/ptmx", op->dest); } /* If stdout is a tty, that means the sandbox can write to the outside-sandbox tty. In that case we also create a /dev/console that points to this tty device. This should not cause any more access than we already have, and it makes ttyname() work in the sandbox. */ if (host_tty_dev != NULL && *host_tty_dev != 0) { cleanup_free char *src_tty_dev = strconcat ("/oldroot", host_tty_dev); cleanup_free char *dest_console = strconcat (dest, "/console"); if (create_file (dest_console, 0666, NULL) != 0) die_with_error ("creating %s/console", op->dest); privileged_op (privileged_op_socket, PRIV_SEP_OP_BIND_MOUNT, BIND_DEVICES, src_tty_dev, dest_console); } break; case SETUP_MOUNT_TMPFS: if (mkdir (dest, 0755) != 0 && errno != EEXIST) die_with_error ("Can't mkdir %s", op->dest); privileged_op (privileged_op_socket, PRIV_SEP_OP_TMPFS_MOUNT, 0, dest, NULL); break; case SETUP_MOUNT_MQUEUE: if (mkdir (dest, 0755) != 0 && errno != EEXIST) die_with_error ("Can't mkdir %s", op->dest); privileged_op (privileged_op_socket, PRIV_SEP_OP_MQUEUE_MOUNT, 0, dest, NULL); break; case SETUP_MAKE_DIR: if (mkdir (dest, 0755) != 0 && errno != EEXIST) die_with_error ("Can't mkdir %s", op->dest); break; case SETUP_MAKE_FILE: { cleanup_fd int dest_fd = -1; dest_fd = creat (dest, 0666); if (dest_fd == -1) die_with_error ("Can't create file %s", op->dest); if (copy_file_data (op->fd, dest_fd) != 0) die_with_error ("Can't write data to file %s", op->dest); close (op->fd); } break; case SETUP_MAKE_BIND_FILE: case SETUP_MAKE_RO_BIND_FILE: { cleanup_fd int dest_fd = -1; char tempfile[] = "/bindfileXXXXXX"; dest_fd = mkstemp (tempfile); if (dest_fd == -1) die_with_error ("Can't create tmpfile for %s", op->dest); if (copy_file_data (op->fd, dest_fd) != 0) die_with_error ("Can't write data to file %s", op->dest); close (op->fd); if (ensure_file (dest, 0666) != 0) die_with_error ("Can't create file at %s", op->dest); privileged_op (privileged_op_socket, PRIV_SEP_OP_BIND_MOUNT, (op->type == SETUP_MAKE_RO_BIND_FILE ? BIND_READONLY : 0), tempfile, dest); /* Remove the file so we're sure the app can't get to it in any other way. Its outside the container chroot, so it shouldn't be possible, but lets make it really sure. */ unlink (tempfile); } break; case SETUP_MAKE_SYMLINK: if (symlink (op->source, dest) != 0) die_with_error ("Can't make symlink at %s", op->dest); break; case SETUP_SET_HOSTNAME: privileged_op (privileged_op_socket, PRIV_SEP_OP_SET_HOSTNAME, 0, op->dest, NULL); break; default: die ("Unexpected type %d", op->type); } } privileged_op (privileged_op_socket, PRIV_SEP_OP_DONE, 0, NULL, NULL); } /* We need to resolve relative symlinks in the sandbox before we chroot so that absolute symlinks are handled correctly. We also need to do this after we've switched to the real uid so that e.g. paths on fuse mounts work */ static void resolve_symlinks_in_ops (void) { SetupOp *op; for (op = ops; op != NULL; op = op->next) { const char *old_source; switch (op->type) { case SETUP_RO_BIND_MOUNT: case SETUP_DEV_BIND_MOUNT: case SETUP_BIND_MOUNT: old_source = op->source; op->source = realpath (old_source, NULL); if (op->source == NULL) die_with_error ("Can't find source path %s", old_source); break; default: break; } } } static const char * resolve_string_offset (void *buffer, size_t buffer_size, uint32_t offset) { if (offset == 0) return NULL; if (offset > buffer_size) die ("Invalid string offset %d (buffer size %zd)", offset, buffer_size); return (const char *) buffer + offset; } static uint32_t read_priv_sec_op (int read_socket, void *buffer, size_t buffer_size, uint32_t *flags, const char **arg1, const char **arg2) { const PrivSepOp *op = (const PrivSepOp *) buffer; ssize_t rec_len; do rec_len = read (read_socket, buffer, buffer_size - 1); while (rec_len == -1 && errno == EINTR); if (rec_len < 0) die_with_error ("Can't read from unprivileged helper"); if (rec_len == 0) exit (1); /* Privileged helper died and printed error, so exit silently */ if (rec_len < sizeof (PrivSepOp)) die ("Invalid size %zd from unprivileged helper", rec_len); /* Guarantee zero termination of any strings */ ((char *) buffer)[rec_len] = 0; *flags = op->flags; *arg1 = resolve_string_offset (buffer, rec_len, op->arg1_offset); *arg2 = resolve_string_offset (buffer, rec_len, op->arg2_offset); return op->op; } static void parse_args_recurse (int *argcp, char ***argvp, bool in_file, int *total_parsed_argc_p) { SetupOp *op; int argc = *argcp; char **argv = *argvp; /* I can't imagine a case where someone wants more than this. * If you do...you should be able to pass multiple files * via a single tmpfs and linking them there, etc. * * We're adding this hardening due to precedent from * http://googleprojectzero.blogspot.com/2014/08/the-poisoned-nul-byte-2014-edition.html * * I picked 9000 because the Internet told me to and it was hard to * resist. */ static const uint32_t MAX_ARGS = 9000; if (*total_parsed_argc_p > MAX_ARGS) die ("Exceeded maximum number of arguments %u", MAX_ARGS); while (argc > 0) { const char *arg = argv[0]; if (strcmp (arg, "--help") == 0) { usage (EXIT_SUCCESS, stdout); } else if (strcmp (arg, "--version") == 0) { printf ("%s\n", PACKAGE_STRING); exit (0); } else if (strcmp (arg, "--args") == 0) { int the_fd; char *endptr; char *data, *p; char *data_end; size_t data_len; cleanup_free char **data_argv = NULL; char **data_argv_copy; int data_argc; int i; if (in_file) die ("--args not supported in arguments file"); if (argc < 2) die ("--args takes an argument"); the_fd = strtol (argv[1], &endptr, 10); if (argv[1][0] == 0 || endptr[0] != 0 || the_fd < 0) die ("Invalid fd: %s", argv[1]); data = load_file_data (the_fd, &data_len); if (data == NULL) die_with_error ("Can't read --args data"); data_end = data + data_len; data_argc = 0; p = data; while (p != NULL && p < data_end) { data_argc++; (*total_parsed_argc_p)++; if (*total_parsed_argc_p > MAX_ARGS) die ("Exceeded maximum number of arguments %u", MAX_ARGS); p = memchr (p, 0, data_end - p); if (p != NULL) p++; } data_argv = xcalloc (sizeof (char *) * (data_argc + 1)); i = 0; p = data; while (p != NULL && p < data_end) { /* Note: load_file_data always adds a nul terminator, so this is safe * even for the last string. */ data_argv[i++] = p; p = memchr (p, 0, data_end - p); if (p != NULL) p++; } data_argv_copy = data_argv; /* Don't change data_argv, we need to free it */ parse_args_recurse (&data_argc, &data_argv_copy, TRUE, total_parsed_argc_p); argv += 1; argc -= 1; } else if (strcmp (arg, "--unshare-user") == 0) { opt_unshare_user = TRUE; } else if (strcmp (arg, "--unshare-user-try") == 0) { opt_unshare_user_try = TRUE; } else if (strcmp (arg, "--unshare-ipc") == 0) { opt_unshare_ipc = TRUE; } else if (strcmp (arg, "--unshare-pid") == 0) { opt_unshare_pid = TRUE; } else if (strcmp (arg, "--unshare-net") == 0) { opt_unshare_net = TRUE; } else if (strcmp (arg, "--unshare-uts") == 0) { opt_unshare_uts = TRUE; } else if (strcmp (arg, "--unshare-cgroup") == 0) { opt_unshare_cgroup = TRUE; } else if (strcmp (arg, "--unshare-cgroup-try") == 0) { opt_unshare_cgroup_try = TRUE; } else if (strcmp (arg, "--chdir") == 0) { if (argc < 2) die ("--chdir takes one argument"); opt_chdir_path = argv[1]; argv++; argc--; } else if (strcmp (arg, "--remount-ro") == 0) { SetupOp *op = setup_op_new (SETUP_REMOUNT_RO_NO_RECURSIVE); op->dest = argv[1]; argv++; argc--; } else if (strcmp (arg, "--bind") == 0) { if (argc < 3) die ("--bind takes two arguments"); op = setup_op_new (SETUP_BIND_MOUNT); op->source = argv[1]; op->dest = argv[2]; argv += 2; argc -= 2; } else if (strcmp (arg, "--ro-bind") == 0) { if (argc < 3) die ("--ro-bind takes two arguments"); op = setup_op_new (SETUP_RO_BIND_MOUNT); op->source = argv[1]; op->dest = argv[2]; argv += 2; argc -= 2; } else if (strcmp (arg, "--dev-bind") == 0) { if (argc < 3) die ("--dev-bind takes two arguments"); op = setup_op_new (SETUP_DEV_BIND_MOUNT); op->source = argv[1]; op->dest = argv[2]; argv += 2; argc -= 2; } else if (strcmp (arg, "--proc") == 0) { if (argc < 2) die ("--proc takes an argument"); op = setup_op_new (SETUP_MOUNT_PROC); op->dest = argv[1]; argv += 1; argc -= 1; } else if (strcmp (arg, "--exec-label") == 0) { if (argc < 2) die ("--exec-label takes an argument"); opt_exec_label = argv[1]; die_unless_label_valid (opt_exec_label); argv += 1; argc -= 1; } else if (strcmp (arg, "--file-label") == 0) { if (argc < 2) die ("--file-label takes an argument"); opt_file_label = argv[1]; die_unless_label_valid (opt_file_label); if (label_create_file (opt_file_label)) die_with_error ("--file-label setup failed"); argv += 1; argc -= 1; } else if (strcmp (arg, "--dev") == 0) { if (argc < 2) die ("--dev takes an argument"); op = setup_op_new (SETUP_MOUNT_DEV); op->dest = argv[1]; opt_needs_devpts = TRUE; argv += 1; argc -= 1; } else if (strcmp (arg, "--tmpfs") == 0) { if (argc < 2) die ("--tmpfs takes an argument"); op = setup_op_new (SETUP_MOUNT_TMPFS); op->dest = argv[1]; argv += 1; argc -= 1; } else if (strcmp (arg, "--mqueue") == 0) { if (argc < 2) die ("--mqueue takes an argument"); op = setup_op_new (SETUP_MOUNT_MQUEUE); op->dest = argv[1]; argv += 1; argc -= 1; } else if (strcmp (arg, "--dir") == 0) { if (argc < 2) die ("--dir takes an argument"); op = setup_op_new (SETUP_MAKE_DIR); op->dest = argv[1]; argv += 1; argc -= 1; } else if (strcmp (arg, "--file") == 0) { int file_fd; char *endptr; if (argc < 3) die ("--file takes two arguments"); file_fd = strtol (argv[1], &endptr, 10); if (argv[1][0] == 0 || endptr[0] != 0 || file_fd < 0) die ("Invalid fd: %s", argv[1]); op = setup_op_new (SETUP_MAKE_FILE); op->fd = file_fd; op->dest = argv[2]; argv += 2; argc -= 2; } else if (strcmp (arg, "--bind-data") == 0) { int file_fd; char *endptr; if (argc < 3) die ("--bind-data takes two arguments"); file_fd = strtol (argv[1], &endptr, 10); if (argv[1][0] == 0 || endptr[0] != 0 || file_fd < 0) die ("Invalid fd: %s", argv[1]); op = setup_op_new (SETUP_MAKE_BIND_FILE); op->fd = file_fd; op->dest = argv[2]; argv += 2; argc -= 2; } else if (strcmp (arg, "--ro-bind-data") == 0) { int file_fd; char *endptr; if (argc < 3) die ("--ro-bind-data takes two arguments"); file_fd = strtol (argv[1], &endptr, 10); if (argv[1][0] == 0 || endptr[0] != 0 || file_fd < 0) die ("Invalid fd: %s", argv[1]); op = setup_op_new (SETUP_MAKE_RO_BIND_FILE); op->fd = file_fd; op->dest = argv[2]; argv += 2; argc -= 2; } else if (strcmp (arg, "--symlink") == 0) { if (argc < 3) die ("--symlink takes two arguments"); op = setup_op_new (SETUP_MAKE_SYMLINK); op->source = argv[1]; op->dest = argv[2]; argv += 2; argc -= 2; } else if (strcmp (arg, "--lock-file") == 0) { if (argc < 2) die ("--lock-file takes an argument"); (void) lock_file_new (argv[1]); argv += 1; argc -= 1; } else if (strcmp (arg, "--sync-fd") == 0) { int the_fd; char *endptr; if (argc < 2) die ("--sync-fd takes an argument"); the_fd = strtol (argv[1], &endptr, 10); if (argv[1][0] == 0 || endptr[0] != 0 || the_fd < 0) die ("Invalid fd: %s", argv[1]); opt_sync_fd = the_fd; argv += 1; argc -= 1; } else if (strcmp (arg, "--block-fd") == 0) { int the_fd; char *endptr; if (argc < 2) die ("--block-fd takes an argument"); the_fd = strtol (argv[1], &endptr, 10); if (argv[1][0] == 0 || endptr[0] != 0 || the_fd < 0) die ("Invalid fd: %s", argv[1]); opt_block_fd = the_fd; argv += 1; argc -= 1; } else if (strcmp (arg, "--info-fd") == 0) { int the_fd; char *endptr; if (argc < 2) die ("--info-fd takes an argument"); the_fd = strtol (argv[1], &endptr, 10); if (argv[1][0] == 0 || endptr[0] != 0 || the_fd < 0) die ("Invalid fd: %s", argv[1]); opt_info_fd = the_fd; argv += 1; argc -= 1; } else if (strcmp (arg, "--seccomp") == 0) { int the_fd; char *endptr; if (argc < 2) die ("--seccomp takes an argument"); the_fd = strtol (argv[1], &endptr, 10); if (argv[1][0] == 0 || endptr[0] != 0 || the_fd < 0) die ("Invalid fd: %s", argv[1]); opt_seccomp_fd = the_fd; argv += 1; argc -= 1; } else if (strcmp (arg, "--setenv") == 0) { if (argc < 3) die ("--setenv takes two arguments"); xsetenv (argv[1], argv[2], 1); argv += 2; argc -= 2; } else if (strcmp (arg, "--unsetenv") == 0) { if (argc < 2) die ("--unsetenv takes an argument"); xunsetenv (argv[1]); argv += 1; argc -= 1; } else if (strcmp (arg, "--uid") == 0) { int the_uid; char *endptr; if (argc < 2) die ("--uid takes an argument"); the_uid = strtol (argv[1], &endptr, 10); if (argv[1][0] == 0 || endptr[0] != 0 || the_uid < 0) die ("Invalid uid: %s", argv[1]); opt_sandbox_uid = the_uid; argv += 1; argc -= 1; } else if (strcmp (arg, "--gid") == 0) { int the_gid; char *endptr; if (argc < 2) die ("--gid takes an argument"); the_gid = strtol (argv[1], &endptr, 10); if (argv[1][0] == 0 || endptr[0] != 0 || the_gid < 0) die ("Invalid gid: %s", argv[1]); opt_sandbox_gid = the_gid; argv += 1; argc -= 1; } else if (strcmp (arg, "--hostname") == 0) { if (argc < 2) die ("--hostname takes an argument"); op = setup_op_new (SETUP_SET_HOSTNAME); op->dest = argv[1]; op->flags = NO_CREATE_DEST; opt_sandbox_hostname = argv[1]; argv += 1; argc -= 1; } else if (*arg == '-') { die ("Unknown option %s", arg); } else { break; } argv++; argc--; } *argcp = argc; *argvp = argv; } static void parse_args (int *argcp, char ***argvp) { int total_parsed_argc = *argcp; parse_args_recurse (argcp, argvp, FALSE, &total_parsed_argc); } static void read_overflowids (void) { cleanup_free char *uid_data = NULL; cleanup_free char *gid_data = NULL; uid_data = load_file_at (AT_FDCWD, "/proc/sys/kernel/overflowuid"); if (uid_data == NULL) die_with_error ("Can't read /proc/sys/kernel/overflowuid"); overflow_uid = strtol (uid_data, NULL, 10); if (overflow_uid == 0) die ("Can't parse /proc/sys/kernel/overflowuid"); gid_data = load_file_at (AT_FDCWD, "/proc/sys/kernel/overflowgid"); if (gid_data == NULL) die_with_error ("Can't read /proc/sys/kernel/overflowgid"); overflow_gid = strtol (gid_data, NULL, 10); if (overflow_gid == 0) die ("Can't parse /proc/sys/kernel/overflowgid"); } int main (int argc, char **argv) { mode_t old_umask; cleanup_free char *base_path = NULL; int clone_flags; char *old_cwd = NULL; pid_t pid; int event_fd = -1; int child_wait_fd = -1; const char *new_cwd; uid_t ns_uid; gid_t ns_gid; struct stat sbuf; uint64_t val; int res UNUSED; real_uid = getuid (); real_gid = getgid (); /* Get the (optional) privileges we need */ acquire_privs (); /* Never gain any more privs during exec */ if (prctl (PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) < 0) die_with_error ("prctl(PR_SET_NO_NEW_CAPS) failed"); /* The initial code is run with high permissions (i.e. CAP_SYS_ADMIN), so take lots of care. */ read_overflowids (); argv0 = argv[0]; if (isatty (1)) host_tty_dev = ttyname (1); argv++; argc--; if (argc == 0) usage (EXIT_FAILURE, stderr); parse_args (&argc, &argv); /* We have to do this if we weren't installed setuid (and we're not * root), so let's just DWIM */ if (!is_privileged && getuid () != 0) opt_unshare_user = TRUE; if (opt_unshare_user_try && stat ("/proc/self/ns/user", &sbuf) == 0) { bool disabled = FALSE; /* RHEL7 has a kernel module parameter that lets you enable user namespaces */ if (stat ("/sys/module/user_namespace/parameters/enable", &sbuf) == 0) { cleanup_free char *enable = NULL; enable = load_file_at (AT_FDCWD, "/sys/module/user_namespace/parameters/enable"); if (enable != NULL && enable[0] == 'N') disabled = TRUE; } /* Debian lets you disable *unprivileged* user namespaces. However this is not a problem if we're privileged, and if we're not opt_unshare_user is TRUE already, and there is not much we can do, its just a non-working setup. */ if (!disabled) opt_unshare_user = TRUE; } if (argc == 0) usage (EXIT_FAILURE, stderr); __debug__ (("Creating root mount point\n")); if (opt_sandbox_uid == -1) opt_sandbox_uid = real_uid; if (opt_sandbox_gid == -1) opt_sandbox_gid = real_gid; if (!opt_unshare_user && opt_sandbox_uid != real_uid) die ("Specifying --uid requires --unshare-user"); if (!opt_unshare_user && opt_sandbox_gid != real_gid) die ("Specifying --gid requires --unshare-user"); if (!opt_unshare_uts && opt_sandbox_hostname != NULL) die ("Specifying --hostname requires --unshare-uts"); /* We need to read stuff from proc during the pivot_root dance, etc. Lets keep a fd to it open */ proc_fd = open ("/proc", O_RDONLY | O_PATH); if (proc_fd == -1) die_with_error ("Can't open /proc"); /* We need *some* mountpoint where we can mount the root tmpfs. We first try in /run, and if that fails, try in /tmp. */ base_path = xasprintf ("/run/user/%d/.bubblewrap", real_uid); if (mkdir (base_path, 0755) && errno != EEXIST) { free (base_path); base_path = xasprintf ("/tmp/.bubblewrap-%d", real_uid); if (mkdir (base_path, 0755) && errno != EEXIST) die_with_error ("Creating root mountpoint failed"); } __debug__ (("creating new namespace\n")); if (opt_unshare_pid) { event_fd = eventfd (0, EFD_CLOEXEC | EFD_NONBLOCK); if (event_fd == -1) die_with_error ("eventfd()"); } /* We block sigchild here so that we can use signalfd in the monitor. */ block_sigchild (); clone_flags = SIGCHLD | CLONE_NEWNS; if (opt_unshare_user) clone_flags |= CLONE_NEWUSER; if (opt_unshare_pid) clone_flags |= CLONE_NEWPID; if (opt_unshare_net) clone_flags |= CLONE_NEWNET; if (opt_unshare_ipc) clone_flags |= CLONE_NEWIPC; if (opt_unshare_uts) clone_flags |= CLONE_NEWUTS; if (opt_unshare_cgroup) { if (stat ("/proc/self/ns/cgroup", &sbuf)) { if (errno == ENOENT) die ("Cannot create new cgroup namespace because the kernel does not support it"); else die_with_error ("stat on /proc/self/ns/cgroup failed"); } clone_flags |= CLONE_NEWCGROUP; } if (opt_unshare_cgroup_try) if (!stat ("/proc/self/ns/cgroup", &sbuf)) clone_flags |= CLONE_NEWCGROUP; child_wait_fd = eventfd (0, EFD_CLOEXEC); if (child_wait_fd == -1) die_with_error ("eventfd()"); pid = raw_clone (clone_flags, NULL); if (pid == -1) { if (opt_unshare_user) { if (errno == EINVAL) die ("Creating new namespace failed, likely because the kernel does not support user namespaces. bwrap must be installed setuid on such systems."); else if (errno == EPERM && !is_privileged) die ("No permissions to creating new namespace, likely because the kernel does not allow non-privileged user namespaces. On e.g. debian this can be enabled with 'sysctl kernel.unprivileged_userns_clone=1'."); } die_with_error ("Creating new namespace failed"); } ns_uid = opt_sandbox_uid; ns_gid = opt_sandbox_gid; if (pid != 0) { /* Parent, outside sandbox, privileged (initially) */ if (is_privileged && opt_unshare_user) { /* We're running as euid 0, but the uid we want to map is * not 0. This means we're not allowed to write this from * the child user namespace, so we do it from the parent. * * Also, we map uid/gid 0 in the namespace (to overflowuid) * if opt_needs_devpts is true, because otherwise the mount * of devpts fails due to root not being mapped. */ write_uid_gid_map (ns_uid, real_uid, ns_gid, real_gid, pid, TRUE, opt_needs_devpts); } /* Initial launched process, wait for exec:ed command to exit */ /* We don't need any privileges in the launcher, drop them immediately. */ drop_privs (); /* Let child run now that the uid maps are set up */ val = 1; res = write (child_wait_fd, &val, 8); /* Ignore res, if e.g. the child died and closed child_wait_fd we don't want to error out here */ close (child_wait_fd); if (opt_info_fd != -1) { cleanup_free char *output = xasprintf ("{\n \"child-pid\": %i\n}\n", pid); size_t len = strlen (output); if (write (opt_info_fd, output, len) != len) die_with_error ("Write to info_fd"); close (opt_info_fd); } monitor_child (event_fd); exit (0); /* Should not be reached, but better safe... */ } /* Child, in sandbox, privileged in the parent or in the user namespace (if --unshare-user). * * Note that for user namespaces we run as euid 0 during clone(), so * the child user namespace is owned by euid 0., This means that the * regular user namespace parent (with uid != 0) doesn't have any * capabilities in it, which is nice as we can't exploit those. In * particular the parent user namespace doesn't have CAP_PTRACE * which would otherwise allow the parent to hijack of the child * after this point. * * Unfortunately this also means you can't ptrace the final * sandboxed process from outside the sandbox either. */ if (opt_info_fd != -1) close (opt_info_fd); /* Wait for the parent to init uid/gid maps and drop caps */ res = read (child_wait_fd, &val, 8); close (child_wait_fd); /* At this point we can completely drop root uid, but retain the * required permitted caps. This allow us to do full setup as * the user uid, which makes e.g. fuse access work. */ switch_to_user_with_privs (); if (opt_unshare_net && loopback_setup () != 0) die ("Can't create loopback device"); ns_uid = opt_sandbox_uid; ns_gid = opt_sandbox_gid; if (!is_privileged && opt_unshare_user) { /* In the unprivileged case we have to write the uid/gid maps in * the child, because we have no caps in the parent */ if (opt_needs_devpts) { /* This is a bit hacky, but we need to first map the real uid/gid to 0, otherwise we can't mount the devpts filesystem because root is not mapped. Later we will create another child user namespace and map back to the real uid */ ns_uid = 0; ns_gid = 0; } write_uid_gid_map (ns_uid, real_uid, ns_gid, real_gid, -1, TRUE, FALSE); } old_umask = umask (0); /* Need to do this before the chroot, but after we're the real uid */ resolve_symlinks_in_ops (); /* Mark everything as slave, so that we still * receive mounts from the real root, but don't * propagate mounts to the real root. */ if (mount (NULL, "/", NULL, MS_SLAVE | MS_REC, NULL) < 0) die_with_error ("Failed to make / slave"); /* Create a tmpfs which we will use as / in the namespace */ if (mount ("", base_path, "tmpfs", MS_NODEV | MS_NOSUID, NULL) != 0) die_with_error ("Failed to mount tmpfs"); old_cwd = get_current_dir_name (); /* Chdir to the new root tmpfs mount. This will be the CWD during the entire setup. Access old or new root via "oldroot" and "newroot". */ if (chdir (base_path) != 0) die_with_error ("chdir base_path"); /* We create a subdir "$base_path/newroot" for the new root, that * way we can pivot_root to base_path, and put the old root at * "$base_path/oldroot". This avoids problems accessing the oldroot * dir if the user requested to bind mount something over / */ if (mkdir ("newroot", 0755)) die_with_error ("Creating newroot failed"); if (mkdir ("oldroot", 0755)) die_with_error ("Creating oldroot failed"); if (pivot_root (base_path, "oldroot")) die_with_error ("pivot_root"); if (chdir ("/") != 0) die_with_error ("chdir / (base path)"); if (is_privileged) { pid_t child; int privsep_sockets[2]; if (socketpair (AF_UNIX, SOCK_SEQPACKET | SOCK_CLOEXEC, 0, privsep_sockets) != 0) die_with_error ("Can't create privsep socket"); child = fork (); if (child == -1) die_with_error ("Can't fork unprivileged helper"); if (child == 0) { /* Unprivileged setup process */ drop_privs (); close (privsep_sockets[0]); setup_newroot (opt_unshare_pid, privsep_sockets[1]); exit (0); } else { int status; uint32_t buffer[2048]; /* 8k, but is int32 to guarantee nice alignment */ uint32_t op, flags; const char *arg1, *arg2; cleanup_fd int unpriv_socket = -1; unpriv_socket = privsep_sockets[0]; close (privsep_sockets[1]); do { op = read_priv_sec_op (unpriv_socket, buffer, sizeof (buffer), &flags, &arg1, &arg2); privileged_op (-1, op, flags, arg1, arg2); if (write (unpriv_socket, buffer, 1) != 1) die ("Can't write to op_socket"); } while (op != PRIV_SEP_OP_DONE); waitpid (child, &status, 0); /* Continue post setup */ } } else { setup_newroot (opt_unshare_pid, -1); } /* The old root better be rprivate or we will send unmount events to the parent namespace */ if (mount ("oldroot", "oldroot", NULL, MS_REC | MS_PRIVATE, NULL) != 0) die_with_error ("Failed to make old root rprivate"); if (umount2 ("oldroot", MNT_DETACH)) die_with_error ("unmount old root"); if (opt_unshare_user && (ns_uid != opt_sandbox_uid || ns_gid != opt_sandbox_gid)) { /* Now that devpts is mounted and we've no need for mount permissions we can create a new userspace and map our uid 1:1 */ if (unshare (CLONE_NEWUSER)) die_with_error ("unshare user ns"); write_uid_gid_map (opt_sandbox_uid, ns_uid, opt_sandbox_gid, ns_gid, -1, FALSE, FALSE); } /* Now make /newroot the real root */ if (chdir ("/newroot") != 0) die_with_error ("chdir newroot"); if (chroot ("/newroot") != 0) die_with_error ("chroot /newroot"); if (chdir ("/") != 0) die_with_error ("chdir /"); /* All privileged ops are done now, so drop it */ drop_privs (); if (opt_block_fd != -1) { char b[1]; read (opt_block_fd, b, 1); close (opt_block_fd); } if (opt_seccomp_fd != -1) { cleanup_free char *seccomp_data = NULL; size_t seccomp_len; struct sock_fprog prog; seccomp_data = load_file_data (opt_seccomp_fd, &seccomp_len); if (seccomp_data == NULL) die_with_error ("Can't read seccomp data"); if (seccomp_len % 8 != 0) die ("Invalid seccomp data, must be multiple of 8"); prog.len = seccomp_len / 8; prog.filter = (struct sock_filter *) seccomp_data; close (opt_seccomp_fd); if (prctl (PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &prog) != 0) die_with_error ("prctl(PR_SET_SECCOMP)"); } umask (old_umask); new_cwd = "/"; if (opt_chdir_path) { if (chdir (opt_chdir_path)) die_with_error ("Can't chdir to %s", opt_chdir_path); new_cwd = opt_chdir_path; } else if (chdir (old_cwd) == 0) { /* If the old cwd is mapped in the sandbox, go there */ new_cwd = old_cwd; } else { /* If the old cwd is not mapped, go to home */ const char *home = getenv ("HOME"); if (home != NULL && chdir (home) == 0) new_cwd = home; } xsetenv ("PWD", new_cwd, 1); free (old_cwd); __debug__ (("forking for child\n")); if (opt_unshare_pid || lock_files != NULL || opt_sync_fd != -1) { /* We have to have a pid 1 in the pid namespace, because * otherwise we'll get a bunch of zombies as nothing reaps * them. Alternatively if we're using sync_fd or lock_files we * need some process to own these. */ pid = fork (); if (pid == -1) die_with_error ("Can't fork for pid 1"); if (pid != 0) { /* Close fds in pid 1, except stdio and optionally event_fd (for syncing pid 2 lifetime with monitor_child) and opt_sync_fd (for syncing sandbox lifetime with outside process). Any other fds will been passed on to the child though. */ { int dont_close[3]; int j = 0; if (event_fd != -1) dont_close[j++] = event_fd; if (opt_sync_fd != -1) dont_close[j++] = opt_sync_fd; dont_close[j++] = -1; fdwalk (proc_fd, close_extra_fds, dont_close); } return do_init (event_fd, pid); } } __debug__ (("launch executable %s\n", argv[0])); if (proc_fd != -1) close (proc_fd); if (opt_sync_fd != -1) close (opt_sync_fd); /* We want sigchild in the child */ unblock_sigchild (); if (label_exec (opt_exec_label) == -1) die_with_error ("label_exec %s", argv[0]); if (execvp (argv[0], argv) == -1) die_with_error ("execvp %s", argv[0]); return 0; }
./CrossVul/dataset_final_sorted/CWE-20/c/bad_3088_0
crossvul-cpp_data_bad_3979_0
/* $OpenBSD: scp.c,v 1.208 2020/04/30 17:07:10 markus Exp $ */ /* * scp - secure remote copy. This is basically patched BSD rcp which * uses ssh to do the data transfer (instead of using rcmd). * * NOTE: This version should NOT be suid root. (This uses ssh to * do the transfer and ssh has the necessary privileges.) * * 1995 Timo Rinne <tri@iki.fi>, Tatu Ylonen <ylo@cs.hut.fi> * * As far as I am concerned, the code I have written for this software * can be used freely for any purpose. Any derived versions of this * software must be clearly marked as such, and if the derived work is * incompatible with the protocol description in the RFC file, it must be * called by a name other than "ssh" or "Secure Shell". */ /* * Copyright (c) 1999 Theo de Raadt. All rights reserved. * Copyright (c) 1999 Aaron Campbell. 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 ``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 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. */ /* * Parts from: * * Copyright (c) 1983, 1990, 1992, 1993, 1995 * 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 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 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 BY THE REGENTS 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 REGENTS 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 "includes.h" #include <sys/types.h> #ifdef HAVE_SYS_STAT_H # include <sys/stat.h> #endif #ifdef HAVE_POLL_H #include <poll.h> #else # ifdef HAVE_SYS_POLL_H # include <sys/poll.h> # endif #endif #ifdef HAVE_SYS_TIME_H # include <sys/time.h> #endif #include <sys/wait.h> #include <sys/uio.h> #include <ctype.h> #include <dirent.h> #include <errno.h> #include <fcntl.h> #ifdef HAVE_FNMATCH_H #include <fnmatch.h> #endif #include <limits.h> #include <locale.h> #include <pwd.h> #include <signal.h> #include <stdarg.h> #ifdef HAVE_STDINT_H # include <stdint.h> #endif #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <unistd.h> #if defined(HAVE_STRNVIS) && defined(HAVE_VIS_H) && !defined(BROKEN_STRNVIS) #include <vis.h> #endif #include "xmalloc.h" #include "ssh.h" #include "atomicio.h" #include "pathnames.h" #include "log.h" #include "misc.h" #include "progressmeter.h" #include "utf8.h" extern char *__progname; #define COPY_BUFLEN 16384 int do_cmd(char *host, char *remuser, int port, char *cmd, int *fdin, int *fdout); int do_cmd2(char *host, char *remuser, int port, char *cmd, int fdin, int fdout); /* Struct for addargs */ arglist args; arglist remote_remote_args; /* Bandwidth limit */ long long limit_kbps = 0; struct bwlimit bwlimit; /* Name of current file being transferred. */ char *curfile; /* This is set to non-zero to enable verbose mode. */ int verbose_mode = 0; /* This is set to zero if the progressmeter is not desired. */ int showprogress = 1; /* * This is set to non-zero if remote-remote copy should be piped * through this process. */ int throughlocal = 0; /* Non-standard port to use for the ssh connection or -1. */ int sshport = -1; /* This is the program to execute for the secured connection. ("ssh" or -S) */ char *ssh_program = _PATH_SSH_PROGRAM; /* This is used to store the pid of ssh_program */ pid_t do_cmd_pid = -1; static void killchild(int signo) { if (do_cmd_pid > 1) { kill(do_cmd_pid, signo ? signo : SIGTERM); waitpid(do_cmd_pid, NULL, 0); } if (signo) _exit(1); exit(1); } static void suspchild(int signo) { int status; if (do_cmd_pid > 1) { kill(do_cmd_pid, signo); while (waitpid(do_cmd_pid, &status, WUNTRACED) == -1 && errno == EINTR) ; kill(getpid(), SIGSTOP); } } static int do_local_cmd(arglist *a) { u_int i; int status; pid_t pid; if (a->num == 0) fatal("do_local_cmd: no arguments"); if (verbose_mode) { fprintf(stderr, "Executing:"); for (i = 0; i < a->num; i++) fmprintf(stderr, " %s", a->list[i]); fprintf(stderr, "\n"); } if ((pid = fork()) == -1) fatal("do_local_cmd: fork: %s", strerror(errno)); if (pid == 0) { execvp(a->list[0], a->list); perror(a->list[0]); exit(1); } do_cmd_pid = pid; ssh_signal(SIGTERM, killchild); ssh_signal(SIGINT, killchild); ssh_signal(SIGHUP, killchild); while (waitpid(pid, &status, 0) == -1) if (errno != EINTR) fatal("do_local_cmd: waitpid: %s", strerror(errno)); do_cmd_pid = -1; if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) return (-1); return (0); } /* * This function executes the given command as the specified user on the * given host. This returns < 0 if execution fails, and >= 0 otherwise. This * assigns the input and output file descriptors on success. */ int do_cmd(char *host, char *remuser, int port, char *cmd, int *fdin, int *fdout) { int pin[2], pout[2], reserved[2]; if (verbose_mode) fmprintf(stderr, "Executing: program %s host %s, user %s, command %s\n", ssh_program, host, remuser ? remuser : "(unspecified)", cmd); if (port == -1) port = sshport; /* * Reserve two descriptors so that the real pipes won't get * descriptors 0 and 1 because that will screw up dup2 below. */ if (pipe(reserved) == -1) fatal("pipe: %s", strerror(errno)); /* Create a socket pair for communicating with ssh. */ if (pipe(pin) == -1) fatal("pipe: %s", strerror(errno)); if (pipe(pout) == -1) fatal("pipe: %s", strerror(errno)); /* Free the reserved descriptors. */ close(reserved[0]); close(reserved[1]); ssh_signal(SIGTSTP, suspchild); ssh_signal(SIGTTIN, suspchild); ssh_signal(SIGTTOU, suspchild); /* Fork a child to execute the command on the remote host using ssh. */ do_cmd_pid = fork(); if (do_cmd_pid == 0) { /* Child. */ close(pin[1]); close(pout[0]); dup2(pin[0], 0); dup2(pout[1], 1); close(pin[0]); close(pout[1]); replacearg(&args, 0, "%s", ssh_program); if (port != -1) { addargs(&args, "-p"); addargs(&args, "%d", port); } if (remuser != NULL) { addargs(&args, "-l"); addargs(&args, "%s", remuser); } addargs(&args, "--"); addargs(&args, "%s", host); addargs(&args, "%s", cmd); execvp(ssh_program, args.list); perror(ssh_program); exit(1); } else if (do_cmd_pid == -1) { fatal("fork: %s", strerror(errno)); } /* Parent. Close the other side, and return the local side. */ close(pin[0]); *fdout = pin[1]; close(pout[1]); *fdin = pout[0]; ssh_signal(SIGTERM, killchild); ssh_signal(SIGINT, killchild); ssh_signal(SIGHUP, killchild); return 0; } /* * This function executes a command similar to do_cmd(), but expects the * input and output descriptors to be setup by a previous call to do_cmd(). * This way the input and output of two commands can be connected. */ int do_cmd2(char *host, char *remuser, int port, char *cmd, int fdin, int fdout) { pid_t pid; int status; if (verbose_mode) fmprintf(stderr, "Executing: 2nd program %s host %s, user %s, command %s\n", ssh_program, host, remuser ? remuser : "(unspecified)", cmd); if (port == -1) port = sshport; /* Fork a child to execute the command on the remote host using ssh. */ pid = fork(); if (pid == 0) { dup2(fdin, 0); dup2(fdout, 1); replacearg(&args, 0, "%s", ssh_program); if (port != -1) { addargs(&args, "-p"); addargs(&args, "%d", port); } if (remuser != NULL) { addargs(&args, "-l"); addargs(&args, "%s", remuser); } addargs(&args, "-oBatchMode=yes"); addargs(&args, "--"); addargs(&args, "%s", host); addargs(&args, "%s", cmd); execvp(ssh_program, args.list); perror(ssh_program); exit(1); } else if (pid == -1) { fatal("fork: %s", strerror(errno)); } while (waitpid(pid, &status, 0) == -1) if (errno != EINTR) fatal("do_cmd2: waitpid: %s", strerror(errno)); return 0; } typedef struct { size_t cnt; char *buf; } BUF; BUF *allocbuf(BUF *, int, int); void lostconn(int); int okname(char *); void run_err(const char *,...); void verifydir(char *); struct passwd *pwd; uid_t userid; int errs, remin, remout; int Tflag, pflag, iamremote, iamrecursive, targetshouldbedirectory; #define CMDNEEDS 64 char cmd[CMDNEEDS]; /* must hold "rcp -r -p -d\0" */ int response(void); void rsource(char *, struct stat *); void sink(int, char *[], const char *); void source(int, char *[]); void tolocal(int, char *[]); void toremote(int, char *[]); void usage(void); int main(int argc, char **argv) { int ch, fflag, tflag, status, n; char **newargv; const char *errstr; extern char *optarg; extern int optind; /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */ sanitise_stdfd(); seed_rng(); msetlocale(); /* Copy argv, because we modify it */ newargv = xcalloc(MAXIMUM(argc + 1, 1), sizeof(*newargv)); for (n = 0; n < argc; n++) newargv[n] = xstrdup(argv[n]); argv = newargv; __progname = ssh_get_progname(argv[0]); memset(&args, '\0', sizeof(args)); memset(&remote_remote_args, '\0', sizeof(remote_remote_args)); args.list = remote_remote_args.list = NULL; addargs(&args, "%s", ssh_program); addargs(&args, "-x"); addargs(&args, "-oForwardAgent=no"); addargs(&args, "-oPermitLocalCommand=no"); addargs(&args, "-oClearAllForwardings=yes"); addargs(&args, "-oRemoteCommand=none"); addargs(&args, "-oRequestTTY=no"); fflag = Tflag = tflag = 0; while ((ch = getopt(argc, argv, "dfl:prtTvBCc:i:P:q12346S:o:F:J:")) != -1) { switch (ch) { /* User-visible flags. */ case '1': fatal("SSH protocol v.1 is no longer supported"); break; case '2': /* Ignored */ break; case '4': case '6': case 'C': addargs(&args, "-%c", ch); addargs(&remote_remote_args, "-%c", ch); break; case '3': throughlocal = 1; break; case 'o': case 'c': case 'i': case 'F': case 'J': addargs(&remote_remote_args, "-%c", ch); addargs(&remote_remote_args, "%s", optarg); addargs(&args, "-%c", ch); addargs(&args, "%s", optarg); break; case 'P': sshport = a2port(optarg); if (sshport <= 0) fatal("bad port \"%s\"\n", optarg); break; case 'B': addargs(&remote_remote_args, "-oBatchmode=yes"); addargs(&args, "-oBatchmode=yes"); break; case 'l': limit_kbps = strtonum(optarg, 1, 100 * 1024 * 1024, &errstr); if (errstr != NULL) usage(); limit_kbps *= 1024; /* kbps */ bandwidth_limit_init(&bwlimit, limit_kbps, COPY_BUFLEN); break; case 'p': pflag = 1; break; case 'r': iamrecursive = 1; break; case 'S': ssh_program = xstrdup(optarg); break; case 'v': addargs(&args, "-v"); addargs(&remote_remote_args, "-v"); verbose_mode = 1; break; case 'q': addargs(&args, "-q"); addargs(&remote_remote_args, "-q"); showprogress = 0; break; /* Server options. */ case 'd': targetshouldbedirectory = 1; break; case 'f': /* "from" */ iamremote = 1; fflag = 1; break; case 't': /* "to" */ iamremote = 1; tflag = 1; #ifdef HAVE_CYGWIN setmode(0, O_BINARY); #endif break; case 'T': Tflag = 1; break; default: usage(); } } argc -= optind; argv += optind; if ((pwd = getpwuid(userid = getuid())) == NULL) fatal("unknown user %u", (u_int) userid); if (!isatty(STDOUT_FILENO)) showprogress = 0; if (pflag) { /* Cannot pledge: -p allows setuid/setgid files... */ } else { if (pledge("stdio rpath wpath cpath fattr tty proc exec", NULL) == -1) { perror("pledge"); exit(1); } } remin = STDIN_FILENO; remout = STDOUT_FILENO; if (fflag) { /* Follow "protocol", send data. */ (void) response(); source(argc, argv); exit(errs != 0); } if (tflag) { /* Receive data. */ sink(argc, argv, NULL); exit(errs != 0); } if (argc < 2) usage(); if (argc > 2) targetshouldbedirectory = 1; remin = remout = -1; do_cmd_pid = -1; /* Command to be executed on remote system using "ssh". */ (void) snprintf(cmd, sizeof cmd, "scp%s%s%s%s", verbose_mode ? " -v" : "", iamrecursive ? " -r" : "", pflag ? " -p" : "", targetshouldbedirectory ? " -d" : ""); (void) ssh_signal(SIGPIPE, lostconn); if (colon(argv[argc - 1])) /* Dest is remote host. */ toremote(argc, argv); else { if (targetshouldbedirectory) verifydir(argv[argc - 1]); tolocal(argc, argv); /* Dest is local host. */ } /* * Finally check the exit status of the ssh process, if one was forked * and no error has occurred yet */ if (do_cmd_pid != -1 && errs == 0) { if (remin != -1) (void) close(remin); if (remout != -1) (void) close(remout); if (waitpid(do_cmd_pid, &status, 0) == -1) errs = 1; else { if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) errs = 1; } } exit(errs != 0); } /* Callback from atomicio6 to update progress meter and limit bandwidth */ static int scpio(void *_cnt, size_t s) { off_t *cnt = (off_t *)_cnt; *cnt += s; refresh_progress_meter(0); if (limit_kbps > 0) bandwidth_limit(&bwlimit, s); return 0; } static int do_times(int fd, int verb, const struct stat *sb) { /* strlen(2^64) == 20; strlen(10^6) == 7 */ char buf[(20 + 7 + 2) * 2 + 2]; (void)snprintf(buf, sizeof(buf), "T%llu 0 %llu 0\n", (unsigned long long) (sb->st_mtime < 0 ? 0 : sb->st_mtime), (unsigned long long) (sb->st_atime < 0 ? 0 : sb->st_atime)); if (verb) { fprintf(stderr, "File mtime %lld atime %lld\n", (long long)sb->st_mtime, (long long)sb->st_atime); fprintf(stderr, "Sending file timestamps: %s", buf); } (void) atomicio(vwrite, fd, buf, strlen(buf)); return (response()); } static int parse_scp_uri(const char *uri, char **userp, char **hostp, int *portp, char **pathp) { int r; r = parse_uri("scp", uri, userp, hostp, portp, pathp); if (r == 0 && *pathp == NULL) *pathp = xstrdup("."); return r; } /* Appends a string to an array; returns 0 on success, -1 on alloc failure */ static int append(char *cp, char ***ap, size_t *np) { char **tmp; if ((tmp = reallocarray(*ap, *np + 1, sizeof(*tmp))) == NULL) return -1; tmp[(*np)] = cp; (*np)++; *ap = tmp; return 0; } /* * Finds the start and end of the first brace pair in the pattern. * returns 0 on success or -1 for invalid patterns. */ static int find_brace(const char *pattern, int *startp, int *endp) { int i; int in_bracket, brace_level; *startp = *endp = -1; in_bracket = brace_level = 0; for (i = 0; i < INT_MAX && *endp < 0 && pattern[i] != '\0'; i++) { switch (pattern[i]) { case '\\': /* skip next character */ if (pattern[i + 1] != '\0') i++; break; case '[': in_bracket = 1; break; case ']': in_bracket = 0; break; case '{': if (in_bracket) break; if (pattern[i + 1] == '}') { /* Protect a single {}, for find(1), like csh */ i++; /* skip */ break; } if (*startp == -1) *startp = i; brace_level++; break; case '}': if (in_bracket) break; if (*startp < 0) { /* Unbalanced brace */ return -1; } if (--brace_level <= 0) *endp = i; break; } } /* unbalanced brackets/braces */ if (*endp < 0 && (*startp >= 0 || in_bracket)) return -1; return 0; } /* * Assembles and records a successfully-expanded pattern, returns -1 on * alloc failure. */ static int emit_expansion(const char *pattern, int brace_start, int brace_end, int sel_start, int sel_end, char ***patternsp, size_t *npatternsp) { char *cp; int o = 0, tail_len = strlen(pattern + brace_end + 1); if ((cp = malloc(brace_start + (sel_end - sel_start) + tail_len + 1)) == NULL) return -1; /* Pattern before initial brace */ if (brace_start > 0) { memcpy(cp, pattern, brace_start); o = brace_start; } /* Current braced selection */ if (sel_end - sel_start > 0) { memcpy(cp + o, pattern + sel_start, sel_end - sel_start); o += sel_end - sel_start; } /* Remainder of pattern after closing brace */ if (tail_len > 0) { memcpy(cp + o, pattern + brace_end + 1, tail_len); o += tail_len; } cp[o] = '\0'; if (append(cp, patternsp, npatternsp) != 0) { free(cp); return -1; } return 0; } /* * Expand the first encountered brace in pattern, appending the expanded * patterns it yielded to the *patternsp array. * * Returns 0 on success or -1 on allocation failure. * * Signals whether expansion was performed via *expanded and whether * pattern was invalid via *invalid. */ static int brace_expand_one(const char *pattern, char ***patternsp, size_t *npatternsp, int *expanded, int *invalid) { int i; int in_bracket, brace_start, brace_end, brace_level; int sel_start, sel_end; *invalid = *expanded = 0; if (find_brace(pattern, &brace_start, &brace_end) != 0) { *invalid = 1; return 0; } else if (brace_start == -1) return 0; in_bracket = brace_level = 0; for (i = sel_start = brace_start + 1; i < brace_end; i++) { switch (pattern[i]) { case '{': if (in_bracket) break; brace_level++; break; case '}': if (in_bracket) break; brace_level--; break; case '[': in_bracket = 1; break; case ']': in_bracket = 0; break; case '\\': if (i < brace_end - 1) i++; /* skip */ break; } if (pattern[i] == ',' || i == brace_end - 1) { if (in_bracket || brace_level > 0) continue; /* End of a selection, emit an expanded pattern */ /* Adjust end index for last selection */ sel_end = (i == brace_end - 1) ? brace_end : i; if (emit_expansion(pattern, brace_start, brace_end, sel_start, sel_end, patternsp, npatternsp) != 0) return -1; /* move on to the next selection */ sel_start = i + 1; continue; } } if (in_bracket || brace_level > 0) { *invalid = 1; return 0; } /* success */ *expanded = 1; return 0; } /* Expand braces from pattern. Returns 0 on success, -1 on failure */ static int brace_expand(const char *pattern, char ***patternsp, size_t *npatternsp) { char *cp, *cp2, **active = NULL, **done = NULL; size_t i, nactive = 0, ndone = 0; int ret = -1, invalid = 0, expanded = 0; *patternsp = NULL; *npatternsp = 0; /* Start the worklist with the original pattern */ if ((cp = strdup(pattern)) == NULL) return -1; if (append(cp, &active, &nactive) != 0) { free(cp); return -1; } while (nactive > 0) { cp = active[nactive - 1]; nactive--; if (brace_expand_one(cp, &active, &nactive, &expanded, &invalid) == -1) { free(cp); goto fail; } if (invalid) fatal("%s: invalid brace pattern \"%s\"", __func__, cp); if (expanded) { /* * Current entry expanded to new entries on the * active list; discard the progenitor pattern. */ free(cp); continue; } /* * Pattern did not expand; append the finename component to * the completed list */ if ((cp2 = strrchr(cp, '/')) != NULL) *cp2++ = '\0'; else cp2 = cp; if (append(xstrdup(cp2), &done, &ndone) != 0) { free(cp); goto fail; } free(cp); } /* success */ *patternsp = done; *npatternsp = ndone; done = NULL; ndone = 0; ret = 0; fail: for (i = 0; i < nactive; i++) free(active[i]); free(active); for (i = 0; i < ndone; i++) free(done[i]); free(done); return ret; } void toremote(int argc, char **argv) { char *suser = NULL, *host = NULL, *src = NULL; char *bp, *tuser, *thost, *targ; int sport = -1, tport = -1; arglist alist; int i, r; u_int j; memset(&alist, '\0', sizeof(alist)); alist.list = NULL; /* Parse target */ r = parse_scp_uri(argv[argc - 1], &tuser, &thost, &tport, &targ); if (r == -1) { fmprintf(stderr, "%s: invalid uri\n", argv[argc - 1]); ++errs; goto out; } if (r != 0) { if (parse_user_host_path(argv[argc - 1], &tuser, &thost, &targ) == -1) { fmprintf(stderr, "%s: invalid target\n", argv[argc - 1]); ++errs; goto out; } } if (tuser != NULL && !okname(tuser)) { ++errs; goto out; } /* Parse source files */ for (i = 0; i < argc - 1; i++) { free(suser); free(host); free(src); r = parse_scp_uri(argv[i], &suser, &host, &sport, &src); if (r == -1) { fmprintf(stderr, "%s: invalid uri\n", argv[i]); ++errs; continue; } if (r != 0) { parse_user_host_path(argv[i], &suser, &host, &src); } if (suser != NULL && !okname(suser)) { ++errs; continue; } if (host && throughlocal) { /* extended remote to remote */ xasprintf(&bp, "%s -f %s%s", cmd, *src == '-' ? "-- " : "", src); if (do_cmd(host, suser, sport, bp, &remin, &remout) < 0) exit(1); free(bp); xasprintf(&bp, "%s -t %s%s", cmd, *targ == '-' ? "-- " : "", targ); if (do_cmd2(thost, tuser, tport, bp, remin, remout) < 0) exit(1); free(bp); (void) close(remin); (void) close(remout); remin = remout = -1; } else if (host) { /* standard remote to remote */ if (tport != -1 && tport != SSH_DEFAULT_PORT) { /* This would require the remote support URIs */ fatal("target port not supported with two " "remote hosts without the -3 option"); } freeargs(&alist); addargs(&alist, "%s", ssh_program); addargs(&alist, "-x"); addargs(&alist, "-oClearAllForwardings=yes"); addargs(&alist, "-n"); for (j = 0; j < remote_remote_args.num; j++) { addargs(&alist, "%s", remote_remote_args.list[j]); } if (sport != -1) { addargs(&alist, "-p"); addargs(&alist, "%d", sport); } if (suser) { addargs(&alist, "-l"); addargs(&alist, "%s", suser); } addargs(&alist, "--"); addargs(&alist, "%s", host); addargs(&alist, "%s", cmd); addargs(&alist, "%s", src); addargs(&alist, "%s%s%s:%s", tuser ? tuser : "", tuser ? "@" : "", thost, targ); if (do_local_cmd(&alist) != 0) errs = 1; } else { /* local to remote */ if (remin == -1) { xasprintf(&bp, "%s -t %s%s", cmd, *targ == '-' ? "-- " : "", targ); if (do_cmd(thost, tuser, tport, bp, &remin, &remout) < 0) exit(1); if (response() < 0) exit(1); free(bp); } source(1, argv + i); } } out: free(tuser); free(thost); free(targ); free(suser); free(host); free(src); } void tolocal(int argc, char **argv) { char *bp, *host = NULL, *src = NULL, *suser = NULL; arglist alist; int i, r, sport = -1; memset(&alist, '\0', sizeof(alist)); alist.list = NULL; for (i = 0; i < argc - 1; i++) { free(suser); free(host); free(src); r = parse_scp_uri(argv[i], &suser, &host, &sport, &src); if (r == -1) { fmprintf(stderr, "%s: invalid uri\n", argv[i]); ++errs; continue; } if (r != 0) parse_user_host_path(argv[i], &suser, &host, &src); if (suser != NULL && !okname(suser)) { ++errs; continue; } if (!host) { /* Local to local. */ freeargs(&alist); addargs(&alist, "%s", _PATH_CP); if (iamrecursive) addargs(&alist, "-r"); if (pflag) addargs(&alist, "-p"); addargs(&alist, "--"); addargs(&alist, "%s", argv[i]); addargs(&alist, "%s", argv[argc-1]); if (do_local_cmd(&alist)) ++errs; continue; } /* Remote to local. */ xasprintf(&bp, "%s -f %s%s", cmd, *src == '-' ? "-- " : "", src); if (do_cmd(host, suser, sport, bp, &remin, &remout) < 0) { free(bp); ++errs; continue; } free(bp); sink(1, argv + argc - 1, src); (void) close(remin); remin = remout = -1; } free(suser); free(host); free(src); } void source(int argc, char **argv) { struct stat stb; static BUF buffer; BUF *bp; off_t i, statbytes; size_t amt, nr; int fd = -1, haderr, indx; char *last, *name, buf[PATH_MAX + 128], encname[PATH_MAX]; int len; for (indx = 0; indx < argc; ++indx) { name = argv[indx]; statbytes = 0; len = strlen(name); while (len > 1 && name[len-1] == '/') name[--len] = '\0'; if ((fd = open(name, O_RDONLY|O_NONBLOCK, 0)) == -1) goto syserr; if (strchr(name, '\n') != NULL) { strnvis(encname, name, sizeof(encname), VIS_NL); name = encname; } if (fstat(fd, &stb) == -1) { syserr: run_err("%s: %s", name, strerror(errno)); goto next; } if (stb.st_size < 0) { run_err("%s: %s", name, "Negative file size"); goto next; } unset_nonblock(fd); switch (stb.st_mode & S_IFMT) { case S_IFREG: break; case S_IFDIR: if (iamrecursive) { rsource(name, &stb); goto next; } /* FALLTHROUGH */ default: run_err("%s: not a regular file", name); goto next; } if ((last = strrchr(name, '/')) == NULL) last = name; else ++last; curfile = last; if (pflag) { if (do_times(remout, verbose_mode, &stb) < 0) goto next; } #define FILEMODEMASK (S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO) snprintf(buf, sizeof buf, "C%04o %lld %s\n", (u_int) (stb.st_mode & FILEMODEMASK), (long long)stb.st_size, last); if (verbose_mode) fmprintf(stderr, "Sending file modes: %s", buf); (void) atomicio(vwrite, remout, buf, strlen(buf)); if (response() < 0) goto next; if ((bp = allocbuf(&buffer, fd, COPY_BUFLEN)) == NULL) { next: if (fd != -1) { (void) close(fd); fd = -1; } continue; } if (showprogress) start_progress_meter(curfile, stb.st_size, &statbytes); set_nonblock(remout); for (haderr = i = 0; i < stb.st_size; i += bp->cnt) { amt = bp->cnt; if (i + (off_t)amt > stb.st_size) amt = stb.st_size - i; if (!haderr) { if ((nr = atomicio(read, fd, bp->buf, amt)) != amt) { haderr = errno; memset(bp->buf + nr, 0, amt - nr); } } /* Keep writing after error to retain sync */ if (haderr) { (void)atomicio(vwrite, remout, bp->buf, amt); memset(bp->buf, 0, amt); continue; } if (atomicio6(vwrite, remout, bp->buf, amt, scpio, &statbytes) != amt) haderr = errno; } unset_nonblock(remout); if (fd != -1) { if (close(fd) == -1 && !haderr) haderr = errno; fd = -1; } if (!haderr) (void) atomicio(vwrite, remout, "", 1); else run_err("%s: %s", name, strerror(haderr)); (void) response(); if (showprogress) stop_progress_meter(); } } void rsource(char *name, struct stat *statp) { DIR *dirp; struct dirent *dp; char *last, *vect[1], path[PATH_MAX]; if (!(dirp = opendir(name))) { run_err("%s: %s", name, strerror(errno)); return; } last = strrchr(name, '/'); if (last == NULL) last = name; else last++; if (pflag) { if (do_times(remout, verbose_mode, statp) < 0) { closedir(dirp); return; } } (void) snprintf(path, sizeof path, "D%04o %d %.1024s\n", (u_int) (statp->st_mode & FILEMODEMASK), 0, last); if (verbose_mode) fmprintf(stderr, "Entering directory: %s", path); (void) atomicio(vwrite, remout, path, strlen(path)); if (response() < 0) { closedir(dirp); return; } while ((dp = readdir(dirp)) != NULL) { if (dp->d_ino == 0) continue; if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) continue; if (strlen(name) + 1 + strlen(dp->d_name) >= sizeof(path) - 1) { run_err("%s/%s: name too long", name, dp->d_name); continue; } (void) snprintf(path, sizeof path, "%s/%s", name, dp->d_name); vect[0] = path; source(1, vect); } (void) closedir(dirp); (void) atomicio(vwrite, remout, "E\n", 2); (void) response(); } #define TYPE_OVERFLOW(type, val) \ ((sizeof(type) == 4 && (val) > INT32_MAX) || \ (sizeof(type) == 8 && (val) > INT64_MAX) || \ (sizeof(type) != 4 && sizeof(type) != 8)) void sink(int argc, char **argv, const char *src) { static BUF buffer; struct stat stb; enum { YES, NO, DISPLAYED } wrerr; BUF *bp; off_t i; size_t j, count; int amt, exists, first, ofd; mode_t mode, omode, mask; off_t size, statbytes; unsigned long long ull; int setimes, targisdir, wrerrno = 0; char ch, *cp, *np, *targ, *why, *vect[1], buf[2048], visbuf[2048]; char **patterns = NULL; size_t n, npatterns = 0; struct timeval tv[2]; #define atime tv[0] #define mtime tv[1] #define SCREWUP(str) { why = str; goto screwup; } if (TYPE_OVERFLOW(time_t, 0) || TYPE_OVERFLOW(off_t, 0)) SCREWUP("Unexpected off_t/time_t size"); setimes = targisdir = 0; mask = umask(0); if (!pflag) (void) umask(mask); if (argc != 1) { run_err("ambiguous target"); exit(1); } targ = *argv; if (targetshouldbedirectory) verifydir(targ); (void) atomicio(vwrite, remout, "", 1); if (stat(targ, &stb) == 0 && S_ISDIR(stb.st_mode)) targisdir = 1; if (src != NULL && !iamrecursive && !Tflag) { /* * Prepare to try to restrict incoming filenames to match * the requested destination file glob. */ if (brace_expand(src, &patterns, &npatterns) != 0) fatal("%s: could not expand pattern", __func__); } for (first = 1;; first = 0) { cp = buf; if (atomicio(read, remin, cp, 1) != 1) goto done; if (*cp++ == '\n') SCREWUP("unexpected <newline>"); do { if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch)) SCREWUP("lost connection"); *cp++ = ch; } while (cp < &buf[sizeof(buf) - 1] && ch != '\n'); *cp = 0; if (verbose_mode) fmprintf(stderr, "Sink: %s", buf); if (buf[0] == '\01' || buf[0] == '\02') { if (iamremote == 0) { (void) snmprintf(visbuf, sizeof(visbuf), NULL, "%s", buf + 1); (void) atomicio(vwrite, STDERR_FILENO, visbuf, strlen(visbuf)); } if (buf[0] == '\02') exit(1); ++errs; continue; } if (buf[0] == 'E') { (void) atomicio(vwrite, remout, "", 1); goto done; } if (ch == '\n') *--cp = 0; cp = buf; if (*cp == 'T') { setimes++; cp++; if (!isdigit((unsigned char)*cp)) SCREWUP("mtime.sec not present"); ull = strtoull(cp, &cp, 10); if (!cp || *cp++ != ' ') SCREWUP("mtime.sec not delimited"); if (TYPE_OVERFLOW(time_t, ull)) setimes = 0; /* out of range */ mtime.tv_sec = ull; mtime.tv_usec = strtol(cp, &cp, 10); if (!cp || *cp++ != ' ' || mtime.tv_usec < 0 || mtime.tv_usec > 999999) SCREWUP("mtime.usec not delimited"); if (!isdigit((unsigned char)*cp)) SCREWUP("atime.sec not present"); ull = strtoull(cp, &cp, 10); if (!cp || *cp++ != ' ') SCREWUP("atime.sec not delimited"); if (TYPE_OVERFLOW(time_t, ull)) setimes = 0; /* out of range */ atime.tv_sec = ull; atime.tv_usec = strtol(cp, &cp, 10); if (!cp || *cp++ != '\0' || atime.tv_usec < 0 || atime.tv_usec > 999999) SCREWUP("atime.usec not delimited"); (void) atomicio(vwrite, remout, "", 1); continue; } if (*cp != 'C' && *cp != 'D') { /* * Check for the case "rcp remote:foo\* local:bar". * In this case, the line "No match." can be returned * by the shell before the rcp command on the remote is * executed so the ^Aerror_message convention isn't * followed. */ if (first) { run_err("%s", cp); exit(1); } SCREWUP("expected control record"); } mode = 0; for (++cp; cp < buf + 5; cp++) { if (*cp < '0' || *cp > '7') SCREWUP("bad mode"); mode = (mode << 3) | (*cp - '0'); } if (!pflag) mode &= ~mask; if (*cp++ != ' ') SCREWUP("mode not delimited"); if (!isdigit((unsigned char)*cp)) SCREWUP("size not present"); ull = strtoull(cp, &cp, 10); if (!cp || *cp++ != ' ') SCREWUP("size not delimited"); if (TYPE_OVERFLOW(off_t, ull)) SCREWUP("size out of range"); size = (off_t)ull; if (*cp == '\0' || strchr(cp, '/') != NULL || strcmp(cp, ".") == 0 || strcmp(cp, "..") == 0) { run_err("error: unexpected filename: %s", cp); exit(1); } if (npatterns > 0) { for (n = 0; n < npatterns; n++) { if (fnmatch(patterns[n], cp, 0) == 0) break; } if (n >= npatterns) SCREWUP("filename does not match request"); } if (targisdir) { static char *namebuf; static size_t cursize; size_t need; need = strlen(targ) + strlen(cp) + 250; if (need > cursize) { free(namebuf); namebuf = xmalloc(need); cursize = need; } (void) snprintf(namebuf, need, "%s%s%s", targ, strcmp(targ, "/") ? "/" : "", cp); np = namebuf; } else np = targ; curfile = cp; exists = stat(np, &stb) == 0; if (buf[0] == 'D') { int mod_flag = pflag; if (!iamrecursive) SCREWUP("received directory without -r"); if (exists) { if (!S_ISDIR(stb.st_mode)) { errno = ENOTDIR; goto bad; } if (pflag) (void) chmod(np, mode); } else { /* Handle copying from a read-only directory */ mod_flag = 1; if (mkdir(np, mode | S_IRWXU) == -1) goto bad; } vect[0] = xstrdup(np); sink(1, vect, src); if (setimes) { setimes = 0; if (utimes(vect[0], tv) == -1) run_err("%s: set times: %s", vect[0], strerror(errno)); } if (mod_flag) (void) chmod(vect[0], mode); free(vect[0]); continue; } omode = mode; mode |= S_IWUSR; if ((ofd = open(np, O_WRONLY|O_CREAT, mode)) == -1) { bad: run_err("%s: %s", np, strerror(errno)); continue; } (void) atomicio(vwrite, remout, "", 1); if ((bp = allocbuf(&buffer, ofd, COPY_BUFLEN)) == NULL) { (void) close(ofd); continue; } cp = bp->buf; wrerr = NO; statbytes = 0; if (showprogress) start_progress_meter(curfile, size, &statbytes); set_nonblock(remin); for (count = i = 0; i < size; i += bp->cnt) { amt = bp->cnt; if (i + amt > size) amt = size - i; count += amt; do { j = atomicio6(read, remin, cp, amt, scpio, &statbytes); if (j == 0) { run_err("%s", j != EPIPE ? strerror(errno) : "dropped connection"); exit(1); } amt -= j; cp += j; } while (amt > 0); if (count == bp->cnt) { /* Keep reading so we stay sync'd up. */ if (wrerr == NO) { if (atomicio(vwrite, ofd, bp->buf, count) != count) { wrerr = YES; wrerrno = errno; } } count = 0; cp = bp->buf; } } unset_nonblock(remin); if (count != 0 && wrerr == NO && atomicio(vwrite, ofd, bp->buf, count) != count) { wrerr = YES; wrerrno = errno; } if (wrerr == NO && (!exists || S_ISREG(stb.st_mode)) && ftruncate(ofd, size) != 0) { run_err("%s: truncate: %s", np, strerror(errno)); wrerr = DISPLAYED; } if (pflag) { if (exists || omode != mode) #ifdef HAVE_FCHMOD if (fchmod(ofd, omode)) { #else /* HAVE_FCHMOD */ if (chmod(np, omode)) { #endif /* HAVE_FCHMOD */ run_err("%s: set mode: %s", np, strerror(errno)); wrerr = DISPLAYED; } } else { if (!exists && omode != mode) #ifdef HAVE_FCHMOD if (fchmod(ofd, omode & ~mask)) { #else /* HAVE_FCHMOD */ if (chmod(np, omode & ~mask)) { #endif /* HAVE_FCHMOD */ run_err("%s: set mode: %s", np, strerror(errno)); wrerr = DISPLAYED; } } if (close(ofd) == -1) { wrerr = YES; wrerrno = errno; } (void) response(); if (showprogress) stop_progress_meter(); if (setimes && wrerr == NO) { setimes = 0; if (utimes(np, tv) == -1) { run_err("%s: set times: %s", np, strerror(errno)); wrerr = DISPLAYED; } } switch (wrerr) { case YES: run_err("%s: %s", np, strerror(wrerrno)); break; case NO: (void) atomicio(vwrite, remout, "", 1); break; case DISPLAYED: break; } } done: for (n = 0; n < npatterns; n++) free(patterns[n]); free(patterns); return; screwup: for (n = 0; n < npatterns; n++) free(patterns[n]); free(patterns); run_err("protocol error: %s", why); exit(1); } int response(void) { char ch, *cp, resp, rbuf[2048], visbuf[2048]; if (atomicio(read, remin, &resp, sizeof(resp)) != sizeof(resp)) lostconn(0); cp = rbuf; switch (resp) { case 0: /* ok */ return (0); default: *cp++ = resp; /* FALLTHROUGH */ case 1: /* error, followed by error msg */ case 2: /* fatal error, "" */ do { if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch)) lostconn(0); *cp++ = ch; } while (cp < &rbuf[sizeof(rbuf) - 1] && ch != '\n'); if (!iamremote) { cp[-1] = '\0'; (void) snmprintf(visbuf, sizeof(visbuf), NULL, "%s\n", rbuf); (void) atomicio(vwrite, STDERR_FILENO, visbuf, strlen(visbuf)); } ++errs; if (resp == 1) return (-1); exit(1); } /* NOTREACHED */ } void usage(void) { (void) fprintf(stderr, "usage: scp [-346BCpqrTv] [-c cipher] [-F ssh_config] [-i identity_file]\n" " [-J destination] [-l limit] [-o ssh_option] [-P port]\n" " [-S program] source ... target\n"); exit(1); } void run_err(const char *fmt,...) { static FILE *fp; va_list ap; ++errs; if (fp != NULL || (remout != -1 && (fp = fdopen(remout, "w")))) { (void) fprintf(fp, "%c", 0x01); (void) fprintf(fp, "scp: "); va_start(ap, fmt); (void) vfprintf(fp, fmt, ap); va_end(ap); (void) fprintf(fp, "\n"); (void) fflush(fp); } if (!iamremote) { va_start(ap, fmt); vfmprintf(stderr, fmt, ap); va_end(ap); fprintf(stderr, "\n"); } } void verifydir(char *cp) { struct stat stb; if (!stat(cp, &stb)) { if (S_ISDIR(stb.st_mode)) return; errno = ENOTDIR; } run_err("%s: %s", cp, strerror(errno)); killchild(0); } int okname(char *cp0) { int c; char *cp; cp = cp0; do { c = (int)*cp; if (c & 0200) goto bad; if (!isalpha(c) && !isdigit((unsigned char)c)) { switch (c) { case '\'': case '"': case '`': case ' ': case '#': goto bad; default: break; } } } while (*++cp); return (1); bad: fmprintf(stderr, "%s: invalid user name\n", cp0); return (0); } BUF * allocbuf(BUF *bp, int fd, int blksize) { size_t size; #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE struct stat stb; if (fstat(fd, &stb) == -1) { run_err("fstat: %s", strerror(errno)); return (0); } size = ROUNDUP(stb.st_blksize, blksize); if (size == 0) size = blksize; #else /* HAVE_STRUCT_STAT_ST_BLKSIZE */ size = blksize; #endif /* HAVE_STRUCT_STAT_ST_BLKSIZE */ if (bp->cnt >= size) return (bp); bp->buf = xrecallocarray(bp->buf, bp->cnt, size, 1); bp->cnt = size; return (bp); } void lostconn(int signo) { if (!iamremote) (void)write(STDERR_FILENO, "lost connection\n", 16); if (signo) _exit(1); else exit(1); }
./CrossVul/dataset_final_sorted/CWE-20/c/bad_3979_0
crossvul-cpp_data_bad_3722_0
/* * jabberd - Jabber Open Source Server * Copyright (c) 2002 Jeremie Miller, Thomas Muldowney, * Ryan Eatmon, Robert Norris * * 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, MA02111-1307USA */ #define _GNU_SOURCE #include <string.h> #include "s2s.h" #include <idna.h> /* * we handle packets going from the router to the world, and stuff * that comes in on connections we initiated. * * action points: * * out_packet(s2s, nad) - send this packet out * - extract to domain * - get dbconn for this domain using out_route * - if dbconn not available bounce packet * - DONE * - if conn in progress (tcp) * - add packet to queue for this domain * - DONE * - if dbconn state valid for this domain, or packet is dialback * - send packet * - DONE * - if dbconn state invalid for this domain * - bounce packet (502) * - DONE * - add packet to queue for this domain * - if dbconn state inprogress for this domain * - DONE * - out_dialback(dbconn, from, to) * * out_route(s2s, route, out, allow_bad) * - if dbconn not found * - check internal resolver cache for domain * - if not found * - ask resolver for name * - DONE * - if outgoing ip/port is to be reused * - get dbconn for any valid ip/port * - if dbconn not found * - create new dbconn * - initiate connect to ip/port * - DONE * - create new dbconn * - initiate connect to ip/port * - DONE * * out_dialback(dbconn, from, to) - initiate dialback * - generate dbkey: sha1(secret+remote+stream id) * - send auth request: <result to='them' from='us'>dbkey</result> * - set dbconn state for this domain to inprogress * - DONE * * out_resolve(s2s, query) - responses from resolver * - store ip/port/ttl in resolver cache * - flush domain queue -> out_packet(s2s, domain) * - DONE * * event_STREAM - ip/port open * - get dbconn for this sx * - for each route handled by this conn, out_dialback(dbconn, from, to) * - DONE * * event_PACKET: <result from='them' to='us' type='xxx'/> - response to our auth request * - get dbconn for this sx * - if type valid * - set dbconn state for this domain to valid * - flush dbconn queue for this domain -> out_packet(s2s, pkt) * - DONE * - set dbconn state for this domain to invalid * - bounce dbconn queue for this domain (502) * - DONE * * event_PACKET: <verify from='them' to='us' id='123' type='xxx'/> - incoming stream authenticated * - get dbconn for given id * - if type is valid * - set dbconn state for this domain to valid * - send result: <result to='them' from='us' type='xxx'/> * - DONE */ /* forward decls */ static int _out_mio_callback(mio_t m, mio_action_t a, mio_fd_t fd, void *data, void *arg); static int _out_sx_callback(sx_t s, sx_event_t e, void *data, void *arg); static void _out_result(conn_t out, nad_t nad); static void _out_verify(conn_t out, nad_t nad); static void _dns_result_aaaa(struct dns_ctx *ctx, struct dns_rr_a6 *result, void *data); static void _dns_result_a(struct dns_ctx *ctx, struct dns_rr_a4 *result, void *data); /** queue the packet */ static void _out_packet_queue(s2s_t s2s, pkt_t pkt) { char *rkey = s2s_route_key(NULL, pkt->from->domain, pkt->to->domain); jqueue_t q = (jqueue_t) xhash_get(s2s->outq, rkey); if(q == NULL) { log_debug(ZONE, "creating new out packet queue for '%s'", rkey); q = jqueue_new(); q->key = rkey; xhash_put(s2s->outq, q->key, (void *) q); } else { free(rkey); } log_debug(ZONE, "queueing packet for '%s'", q->key); jqueue_push(q, (void *) pkt, 0); } static void _out_dialback(conn_t out, char *rkey, int rkeylen) { char *c, *dbkey, *tmp; nad_t nad; int elem, ns; int from_len, to_len; time_t now; now = time(NULL); c = memchr(rkey, '/', rkeylen); from_len = c - rkey; c++; to_len = rkeylen - (c - rkey); /* kick off the dialback */ tmp = strndup(c, to_len); dbkey = s2s_db_key(NULL, out->s2s->local_secret, tmp, out->s->id); free(tmp); nad = nad_new(); /* request auth */ ns = nad_add_namespace(nad, uri_DIALBACK, "db"); elem = nad_append_elem(nad, ns, "result", 0); nad_set_attr(nad, elem, -1, "from", rkey, from_len); nad_set_attr(nad, elem, -1, "to", c, to_len); nad_append_cdata(nad, dbkey, strlen(dbkey), 1); log_debug(ZONE, "sending auth request for %.*s (key %s)", rkeylen, rkey, dbkey); log_write(out->s2s->log, LOG_NOTICE, "[%d] [%s, port=%d] sending dialback auth request for route '%.*s'", out->fd->fd, out->ip, out->port, rkeylen, rkey); /* off it goes */ sx_nad_write(out->s, nad); free(dbkey); /* we're in progress now */ xhash_put(out->states, pstrdupx(xhash_pool(out->states), rkey, rkeylen), (void *) conn_INPROGRESS); /* record the time that we set conn_INPROGRESS state */ xhash_put(out->states_time, pstrdupx(xhash_pool(out->states_time), rkey, rkeylen), (void *) now); } void _out_dns_mark_bad(conn_t out) { if (out->s2s->dns_bad_timeout > 0) { dnsres_t bad; char *ipport; /* mark this host as bad */ ipport = dns_make_ipport(out->ip, out->port); bad = xhash_get(out->s2s->dns_bad, ipport); if (bad == NULL) { bad = (dnsres_t) calloc(1, sizeof(struct dnsres_st)); bad->key = ipport; xhash_put(out->s2s->dns_bad, ipport, bad); } bad->expiry = time(NULL) + out->s2s->dns_bad_timeout; } } int dns_select(s2s_t s2s, char *ip, int *port, time_t now, dnscache_t dns, int allow_bad) { /* list of results */ dnsres_t l_reuse[DNS_MAX_RESULTS]; dnsres_t l_aaaa[DNS_MAX_RESULTS]; dnsres_t l_a[DNS_MAX_RESULTS]; dnsres_t l_bad[DNS_MAX_RESULTS]; /* running weight sums of results */ int rw_reuse[DNS_MAX_RESULTS]; int rw_aaaa[DNS_MAX_RESULTS]; int rw_a[DNS_MAX_RESULTS]; int s_reuse = 0, s_aaaa = 0, s_a = 0, s_bad = 0; /* count */ int p_reuse = 0, p_aaaa = 0, p_a = 0; /* list prio */ int wt_reuse = 0, wt_aaaa = 0, wt_a = 0; /* weight total */ int c_expired_good = 0; union xhashv xhv; dnsres_t res; char *ipport; int ipport_len; char *c; int c_len; char *tmp; /* for all results: * - if not expired * - put highest priority reuseable addrs into list1 * - put highest priority ipv6 addrs into list2 * - put highest priority ipv4 addrs into list3 * - put bad addrs into list4 * - pick weighted random entry from first non-empty list */ if (dns->results == NULL) { log_debug(ZONE, "negative cache entry for '%s'", dns->name); return -1; } log_debug(ZONE, "selecting DNS result for '%s'", dns->name); xhv.dnsres_val = &res; if (xhash_iter_first(dns->results)) { dnsres_t bad = NULL; do { xhash_iter_get(dns->results, (const char **) &ipport, &ipport_len, xhv.val); if (s2s->dns_bad_timeout > 0) bad = xhash_getx(s2s->dns_bad, ipport, ipport_len); if (now > res->expiry) { /* good host? */ if (bad == NULL) c_expired_good++; log_debug(ZONE, "host '%s' expired", res->key); continue; } else if (bad != NULL && !(now > bad->expiry)) { /* bad host (connection failure) */ l_bad[s_bad++] = res; log_debug(ZONE, "host '%s' bad", res->key); } else if (s2s->out_reuse && xhash_getx(s2s->out_host, ipport, ipport_len) != NULL) { /* existing connection */ log_debug(ZONE, "host '%s' exists", res->key); if (s_reuse == 0 || p_reuse > res->prio) { p_reuse = res->prio; s_reuse = 0; wt_reuse = 0; log_debug(ZONE, "reset prio list, using prio %d", res->prio); } if (res->prio <= p_reuse) { l_reuse[s_reuse] = res; wt_reuse += res->weight; rw_reuse[s_reuse] = wt_reuse; s_reuse++; log_debug(ZONE, "added host with weight %d (%d), running weight %d", (res->weight >> 8), res->weight, wt_reuse); } else { log_debug(ZONE, "ignored host with prio %d", res->prio); } } else if (memchr(ipport, ':', ipport_len) != NULL) { /* ipv6 */ log_debug(ZONE, "host '%s' IPv6", res->key); if (s_aaaa == 0 || p_aaaa > res->prio) { p_aaaa = res->prio; s_aaaa = 0; wt_aaaa = 0; log_debug(ZONE, "reset prio list, using prio %d", res->prio); } if (res->prio <= p_aaaa) { l_aaaa[s_aaaa] = res; wt_aaaa += res->weight; rw_aaaa[s_aaaa] = wt_aaaa; s_aaaa++; log_debug(ZONE, "added host with weight %d (%d), running weight %d", (res->weight >> 8), res->weight, wt_aaaa); } else { log_debug(ZONE, "ignored host with prio %d", res->prio); } } else { /* ipv4 */ log_debug(ZONE, "host '%s' IPv4", res->key); if (s_a == 0 || p_a > res->prio) { p_a = res->prio; s_a = 0; wt_a = 0; log_debug(ZONE, "reset prio list, using prio %d", res->prio); } if (res->prio <= p_a) { l_a[s_a] = res; wt_a += res->weight; rw_a[s_a] = wt_a; s_a++; log_debug(ZONE, "added host with weight %d (%d), running weight %d", (res->weight >> 8), res->weight, wt_a); } else { log_debug(ZONE, "ignored host with prio %d", res->prio); } } } while(xhash_iter_next(dns->results)); } /* pick a result at weighted random (RFC 2782) * all weights are guaranteed to be >= 16 && <= 16776960 * (assuming max 50 hosts, the total/running sums won't exceed 2^31) */ ipport = NULL; if (s_reuse > 0) { int i, r; log_debug(ZONE, "using existing hosts, total weight %d", wt_reuse); assert((wt_reuse + 1) > 0); r = rand() % (wt_reuse + 1); log_debug(ZONE, "random number %d", r); for (i = 0; i < s_reuse; i++) if (rw_reuse[i] >= r) { log_debug(ZONE, "selected host '%s', running weight %d", l_reuse[i]->key, rw_reuse[i]); ipport = l_reuse[i]->key; break; } } else if (s_aaaa > 0 && (s_a == 0 || p_aaaa <= p_a)) { int i, r; log_debug(ZONE, "using IPv6 hosts, total weight %d", wt_aaaa); assert((wt_aaaa + 1) > 0); r = rand() % (wt_aaaa + 1); log_debug(ZONE, "random number %d", r); for (i = 0; i < s_aaaa; i++) if (rw_aaaa[i] >= r) { log_debug(ZONE, "selected host '%s', running weight %d", l_aaaa[i]->key, rw_aaaa[i]); ipport = l_aaaa[i]->key; break; } } else if (s_a > 0) { int i, r; log_debug(ZONE, "using IPv4 hosts, total weight %d", wt_a); assert((wt_a + 1) > 0); r = rand() % (wt_a + 1); log_debug(ZONE, "random number %d", r); for (i = 0; i < s_a; i++) if (rw_a[i] >= r) { log_debug(ZONE, "selected host '%s', running weight %d", l_a[i]->key, rw_a[i]); ipport = l_a[i]->key; break; } } else if (s_bad > 0) { ipport = l_bad[rand() % s_bad]->key; log_debug(ZONE, "using bad hosts, allow_bad=%d", allow_bad); /* there are expired good hosts, expire cache immediately */ if (c_expired_good > 0) { log_debug(ZONE, "expiring this DNS cache entry, %d expired hosts", c_expired_good); dns->expiry = 0; } if (!allow_bad) return -1; } /* results cannot all expire before the collection does */ assert(ipport != NULL); /* copy the ip and port to the packet */ ipport_len = strlen(ipport); c = strchr(ipport, '/'); strncpy(ip, ipport, c-ipport); ip[c-ipport] = '\0'; c++; c_len = ipport_len - (c - ipport); tmp = strndup(c, c_len); *port = atoi(tmp); free(tmp); return 0; } /** find/make a connection for a route */ int out_route(s2s_t s2s, char *route, int routelen, conn_t *out, int allow_bad) { dnscache_t dns; char ipport[INET6_ADDRSTRLEN + 16], *dkey, *c; time_t now; int reuse = 0; char ip[INET6_ADDRSTRLEN] = {0}; int port, c_len, from_len; c = memchr(route, '/', routelen); from_len = c - route; c++; c_len = routelen - (c - route); dkey = strndup(c, c_len); log_debug(ZONE, "trying to find connection for '%s'", dkey); *out = (conn_t) xhash_get(s2s->out_dest, dkey); if(*out == NULL) { log_debug(ZONE, "connection for '%s' not found", dkey); /* check resolver cache for ip/port */ dns = xhash_get(s2s->dnscache, dkey); if(dns == NULL) { /* new resolution */ log_debug(ZONE, "no dns for %s, preparing for resolution", dkey); dns = (dnscache_t) calloc(1, sizeof(struct dnscache_st)); strcpy(dns->name, dkey); xhash_put(s2s->dnscache, dns->name, (void *) dns); #if 0 /* this is good for testing */ dns->pending = 0; strcpy(dns->ip, "127.0.0.1"); dns->port = 3000; dns->expiry = time(NULL) + 99999999; #endif } /* resolution in progress */ if(dns->pending) { log_debug(ZONE, "pending resolution"); free(dkey); return 0; } /* has it expired (this is 0 for new cache objects, so they're always expired */ now = time(NULL); /* each entry must be expired no earlier than the collection */ if(now > dns->expiry) { /* resolution required */ log_debug(ZONE, "requesting resolution for %s", dkey); dns->init_time = time(NULL); dns->pending = 1; dns_resolve_domain(s2s, dns); free(dkey); return 0; } /* dns is valid */ if (dns_select(s2s, ip, &port, now, dns, allow_bad)) { /* failed to find anything acceptable */ free(dkey); return -1; } /* re-request resolution if dns_select expired the data */ if (now > dns->expiry) { /* resolution required */ log_debug(ZONE, "requesting resolution for %s", dkey); dns->init_time = time(NULL); dns->pending = 1; dns_resolve_domain(s2s, dns); free(dkey); return 0; } /* generate the ip/port pair, this is the hash key for the conn */ snprintf(ipport, INET6_ADDRSTRLEN + 16, "%s/%d", ip, port); /* try to re-use an existing connection */ if (s2s->out_reuse) *out = (conn_t) xhash_get(s2s->out_host, ipport); if (*out != NULL) { log_write(s2s->log, LOG_NOTICE, "[%d] [%s, port=%d] using connection for '%s'", (*out)->fd->fd, (*out)->ip, (*out)->port, dkey); /* associate existing connection with domain */ xhash_put(s2s->out_dest, s2s->out_reuse ? pstrdup(xhash_pool((*out)->routes), dkey) : dkey, (void *) *out); reuse = 1; } else{ /* no conn, create one */ *out = (conn_t) calloc(1, sizeof(struct conn_st)); (*out)->s2s = s2s; (*out)->key = strdup(ipport); if (s2s->out_reuse) (*out)->dkey = NULL; else (*out)->dkey = dkey; strcpy((*out)->ip, ip); (*out)->port = port; (*out)->states = xhash_new(101); (*out)->states_time = xhash_new(101); (*out)->routes = xhash_new(101); (*out)->init_time = time(NULL); if (s2s->out_reuse) xhash_put(s2s->out_host, (*out)->key, (void *) *out); xhash_put(s2s->out_dest, s2s->out_reuse ? pstrdup(xhash_pool((*out)->routes), dkey) : dkey, (void *) *out); xhash_put((*out)->routes, pstrdupx(xhash_pool((*out)->routes), route, routelen), (void *) 1); /* connect */ log_debug(ZONE, "initiating connection to %s", ipport); /* APPLE: multiple origin_ips may be specified; use IPv6 if possible or otherwise IPv4 */ int ip_is_v6 = 0; if (strchr(ip, ':') != NULL) ip_is_v6 = 1; int i; for (i = 0; i < s2s->origin_nips; i++) { // only bother with mio_connect if the src and dst IPs are of the same type if ((ip_is_v6 && (strchr(s2s->origin_ips[i], ':') != NULL)) || // both are IPv6 (! ip_is_v6 && (strchr(s2s->origin_ips[i], ':') == NULL))) // both are IPv4 (*out)->fd = mio_connect(s2s->mio, port, ip, s2s->origin_ips[i], _out_mio_callback, (void *) *out); if ((*out)->fd != NULL) break; } if ((*out)->fd == NULL) { log_write(s2s->log, LOG_NOTICE, "[%d] [%s, port=%d] mio_connect error: %s (%d)", -1, (*out)->ip, (*out)->port, MIO_STRERROR(MIO_ERROR), MIO_ERROR); _out_dns_mark_bad(*out); if (s2s->out_reuse) xhash_zap(s2s->out_host, (*out)->key); xhash_zap(s2s->out_dest, dkey); xhash_free((*out)->states); xhash_free((*out)->states_time); xhash_free((*out)->routes); free((*out)->key); free((*out)->dkey); free(*out); *out = NULL; /* try again without allowing bad hosts */ return out_route(s2s, route, routelen, out, 0); } else { log_write(s2s->log, LOG_NOTICE, "[%d] [%s, port=%d] outgoing connection for '%s'", (*out)->fd->fd, (*out)->ip, (*out)->port, dkey); (*out)->s = sx_new(s2s->sx_env, (*out)->fd->fd, _out_sx_callback, (void *) *out); #ifdef HAVE_SSL /* Send a stream version of 1.0 if we can do STARTTLS */ if(s2s->sx_ssl != NULL) { sx_client_init((*out)->s, S2S_DB_HEADER, uri_SERVER, dkey, pstrdupx(xhash_pool((*out)->routes), route, from_len), "1.0"); } else { sx_client_init((*out)->s, S2S_DB_HEADER, uri_SERVER, NULL, NULL, NULL); } #else sx_client_init((*out)->s, S2S_DB_HEADER, uri_SERVER, NULL, NULL, NULL); #endif /* dkey is now used by the hash table */ return 0; } } } else { log_debug(ZONE, "connection for '%s' found (%d %s/%d)", dkey, (*out)->fd->fd, (*out)->ip, (*out)->port); } /* connection in progress, or re-using connection: add to routes list */ if (!(*out)->online || reuse) { if (xhash_getx((*out)->routes, route, routelen) == NULL) xhash_put((*out)->routes, pstrdupx(xhash_pool((*out)->routes), route, routelen), (void *) 1); } free(dkey); return 0; } void out_pkt_free(pkt_t pkt) { nad_free(pkt->nad); jid_free(pkt->from); jid_free(pkt->to); free(pkt); } /** send a packet out */ int out_packet(s2s_t s2s, pkt_t pkt) { char *rkey; int rkeylen; conn_t out; conn_state_t state; int ret; /* perform check against whitelist */ if (s2s->enable_whitelist > 0 && (pkt->to->domain != NULL) && (s2s_domain_in_whitelist(s2s, pkt->to->domain) == 0)) { log_write(s2s->log, LOG_NOTICE, "sending a packet to domain not in the whitelist, dropping it"); if (pkt->to != NULL) jid_free(pkt->to); if (pkt->from != NULL) jid_free(pkt->from); if (pkt->nad != NULL) nad_free(pkt->nad); free(pkt); return; } /* new route key */ rkey = s2s_route_key(NULL, pkt->from->domain, pkt->to->domain); rkeylen = strlen(rkey); /* get a connection */ ret = out_route(s2s, rkey, rkeylen, &out, 1); if (out == NULL) { /* connection not available, queue packet */ _out_packet_queue(s2s, pkt); /* check if out_route was successful in attempting a connection */ if (ret) { /* bounce queue */ out_bounce_route_queue(s2s, rkey, rkeylen, stanza_err_SERVICE_UNAVAILABLE); free(rkey); return -1; } free(rkey); return 0; } /* connection in progress */ if(!out->online) { log_debug(ZONE, "connection in progress, queueing packet"); _out_packet_queue(s2s, pkt); free(rkey); return 0; } /* connection state */ state = (conn_state_t) xhash_get(out->states, rkey); /* valid conns or dialback packets */ if(state == conn_VALID || pkt->db) { log_debug(ZONE, "writing packet for %s to outgoing conn %d", rkey, out->fd->fd); /* send it straight out */ if(pkt->db) { /* if this is a db:verify packet, increment counter and set timestamp */ if(NAD_ENAME_L(pkt->nad, 0) == 6 && strncmp("verify", NAD_ENAME(pkt->nad, 0), 6) == 0) { out->verify++; out->last_verify = time(NULL); } /* dialback packet */ sx_nad_write(out->s, pkt->nad); } else { /* if the outgoing stanza has a jabber:client namespace, remove it so that the stream jabber:server namespaces will apply (XMPP 11.2.2) */ int ns = nad_find_namespace(pkt->nad, 1, uri_CLIENT, NULL); if(ns >= 0) { /* clear the namespaces of elem 0 (internal route element) and elem 1 (message|iq|presence) */ pkt->nad->elems[0].ns = -1; pkt->nad->elems[0].my_ns = -1; pkt->nad->elems[1].ns = -1; pkt->nad->elems[1].my_ns = -1; } /* send it out */ sx_nad_write_elem(out->s, pkt->nad, 1); } /* update timestamp */ out->last_packet = time(NULL); jid_free(pkt->from); jid_free(pkt->to); free(pkt); free(rkey); return 0; } /* can't be handled yet, queue */ _out_packet_queue(s2s, pkt); /* if dialback is in progress, then we're done for now */ if(state == conn_INPROGRESS) { free(rkey); return 0; } /* this is a new route - send dialback auth request to piggyback on the existing connection */ if (out->s2s->require_tls == 0 || out->s->ssf > 0) { _out_dialback(out, rkey, rkeylen); } free(rkey); return 0; } char *dns_make_ipport(char *host, int port) { char *c; assert(port > 0 && port < 65536); c = (char *) malloc(strlen(host) + 7); sprintf(c, "%s/%d", host, port); return c; } static void _dns_add_result(dnsquery_t query, char *ip, int port, int prio, int weight, unsigned int ttl) { char *ipport = dns_make_ipport(ip, port); dnsres_t res = xhash_get(query->results, ipport); if (res != NULL) { if (prio < res->prio) res->prio = prio; if (prio < res->prio) { /* duplicate host at lower prio - reset weight */ res->weight = weight; } else if (prio == res->prio) { /* duplicate host at same prio - add to weight */ res->weight += weight; if (res->weight > (65535 << 8)) res->weight = (65535 << 8); } if (ttl > res->expiry) res->expiry = ttl; if (ttl > query->expiry) query->expiry = ttl; log_debug(ZONE, "dns result updated for %s@%p: %s (%d/%d/%d)", query->name, query, ipport, res->prio, (res->weight >> 8), res->expiry); } else if (xhash_count(query->results) < DNS_MAX_RESULTS) { res = pmalloc(xhash_pool(query->results), sizeof(struct dnsres_st)); res->key = pstrdup(xhash_pool(query->results), ipport); res->prio = prio; res->weight = weight; res->expiry = ttl; if (ttl > query->expiry) query->expiry = ttl; xhash_put(query->results, res->key, res); log_debug(ZONE, "dns result added for %s@%p: %s (%d/%d/%d)", query->name, query, ipport, res->prio, (res->weight >> 8), res->expiry); } else { log_debug(ZONE, "dns result ignored for %s@%p: %s (%d/%d/%d)", query->name, query, ipport, prio, (weight >> 8), ttl); } free(ipport); } static void _dns_add_host(dnsquery_t query, char *ip, int port, int prio, int weight, unsigned int ttl) { char *ipport = dns_make_ipport(ip, port); dnsres_t res = xhash_get(query->hosts, ipport); /* update host weights: * RFC 2482 "In the presence of records containing weights greater * than 0, records with weight 0 should have a very small chance of * being selected." * 0 -> 16 * 1-65535 -> 256-16776960 */ if (weight == 0) weight = 1 << 4; else weight <<= 8; if (res != NULL) { if (prio < res->prio) res->prio = prio; if (prio < res->prio) { /* duplicate host at lower prio - reset weight */ res->weight = weight; } else if (prio == res->prio) { /* duplicate host at same prio - add to weight */ res->weight += weight; if (res->weight > (65535 << 8)) res->weight = (65535 << 8); } if (ttl > res->expiry) res->expiry = ttl; log_debug(ZONE, "dns host updated for %s@%p: %s (%d/%d/%d)", query->name, query, ipport, res->prio, (res->weight >> 8), res->expiry); } else if (xhash_count(query->hosts) < DNS_MAX_RESULTS) { res = pmalloc(xhash_pool(query->hosts), sizeof(struct dnsres_st)); res->key = pstrdup(xhash_pool(query->hosts), ipport); res->prio = prio; res->weight = weight; res->expiry = ttl; xhash_put(query->hosts, res->key, res); log_debug(ZONE, "dns host added for %s@%p: %s (%d/%d/%d)", query->name, query, ipport, res->prio, (res->weight >> 8), res->expiry); } else { log_debug(ZONE, "dns host ignored for %s@%p: %s (%d/%d/%d)", query->name, query, ipport, prio, (weight >> 8), ttl); } free(ipport); } /* this function is called with a NULL ctx to start the SRV process */ static void _dns_result_srv(struct dns_ctx *ctx, struct dns_rr_srv *result, void *data) { dnsquery_t query = data; assert(query != NULL); query->query = NULL; if (ctx != NULL && result == NULL) { log_debug(ZONE, "dns failure for %s@%p: SRV %s (%d)", query->name, query, query->s2s->lookup_srv[query->srv_i], dns_status(ctx)); } else if (result != NULL) { int i; log_debug(ZONE, "dns response for %s@%p: SRV %s %d (%d)", query->name, query, result->dnssrv_qname, result->dnssrv_nrr, result->dnssrv_ttl); for (i = 0; i < result->dnssrv_nrr; i++) { if (strlen(result->dnssrv_srv[i].name) > 0 && result->dnssrv_srv[i].port > 0 && result->dnssrv_srv[i].port < 65536) { log_debug(ZONE, "dns response for %s@%p: SRV %s[%d] %s/%d (%d/%d)", query->name, query, result->dnssrv_qname, i, result->dnssrv_srv[i].name, result->dnssrv_srv[i].port, result->dnssrv_srv[i].priority, result->dnssrv_srv[i].weight); _dns_add_host(query, result->dnssrv_srv[i].name, result->dnssrv_srv[i].port, result->dnssrv_srv[i].priority, result->dnssrv_srv[i].weight, result->dnssrv_ttl); } } free(result); } /* check next SRV service name */ query->srv_i++; if (query->srv_i < query->s2s->lookup_nsrv) { log_debug(ZONE, "dns request for %s@%p: SRV %s", query->name, query, query->s2s->lookup_srv[query->srv_i]); query->query = dns_submit_srv(NULL, query->name, query->s2s->lookup_srv[query->srv_i], "tcp", DNS_NOSRCH, _dns_result_srv, query); /* if submit failed, call ourselves with a NULL result */ if (query->query == NULL) _dns_result_srv(ctx, NULL, query); } else { /* no more SRV records to check, resolve hosts */ if (xhash_count(query->hosts) > 0) { _dns_result_a(NULL, NULL, query); /* no SRV records returned, resolve hostname */ } else { query->cur_host = strdup(query->name); query->cur_port = 5269; query->cur_prio = 0; query->cur_weight = 0; query->cur_expiry = 0; if (query->s2s->resolve_aaaa) { log_debug(ZONE, "dns request for %s@%p: AAAA %s", query->name, query, query->name); query->query = dns_submit_a6(NULL, query->name, DNS_NOSRCH, _dns_result_aaaa, query); /* if submit failed, call ourselves with a NULL result */ if (query->query == NULL) _dns_result_aaaa(ctx, NULL, query); } else { log_debug(ZONE, "dns request for %s@%p: A %s", query->name, query, query->name); query->query = dns_submit_a4(NULL, query->name, DNS_NOSRCH, _dns_result_a, query); /* if submit failed, call ourselves with a NULL result */ if (query->query == NULL) _dns_result_a(ctx, NULL, query); } } } } static void _dns_result_aaaa(struct dns_ctx *ctx, struct dns_rr_a6 *result, void *data) { dnsquery_t query = data; char ip[INET6_ADDRSTRLEN]; int i; assert(query != NULL); query->query = NULL; if (ctx != NULL && result == NULL) { log_debug(ZONE, "dns failure for %s@%p: AAAA %s (%d)", query->name, query, query->cur_host, dns_status(ctx)); } else if (result != NULL) { log_debug(ZONE, "dns response for %s@%p: AAAA %s %d (%d)", query->name, query, result->dnsa6_qname, result->dnsa6_nrr, result->dnsa6_ttl); if (query->cur_expiry > 0 && result->dnsa6_ttl > query->cur_expiry) result->dnsa6_ttl = query->cur_expiry; for (i = 0; i < result->dnsa6_nrr; i++) { if (inet_ntop(AF_INET6, &result->dnsa6_addr[i], ip, INET6_ADDRSTRLEN) != NULL) { log_debug(ZONE, "dns response for %s@%p: AAAA %s[%d] %s/%d", query->name, query, result->dnsa6_qname, i, ip, query->cur_port); _dns_add_result(query, ip, query->cur_port, query->cur_prio, query->cur_weight, result->dnsa6_ttl); } } } if (query->cur_host != NULL) { /* do ipv4 resolution too */ log_debug(ZONE, "dns request for %s@%p: A %s", query->name, query, query->cur_host); query->query = dns_submit_a4(NULL, query->cur_host, DNS_NOSRCH, _dns_result_a, query); /* if submit failed, call ourselves with a NULL result */ if (query->query == NULL) _dns_result_a(ctx, NULL, query); } else { /* uh-oh */ log_debug(ZONE, "dns result for %s@%p: AAAA host vanished...", query->name, query); _dns_result_a(NULL, NULL, query); } free(result); } /* try /etc/hosts if the A process did not return any results */ static int _etc_hosts_lookup(const char *cszName, char *szIP, const int ciMaxIPLen) { #define EHL_LINE_LEN 260 int iSuccess = 0; size_t iLen; char szLine[EHL_LINE_LEN + 1]; /* one extra for the space character (*) */ char *pcStart, *pcEnd; FILE *fHosts; do { /* initialization */ fHosts = NULL; /* sanity checks */ if ((cszName == NULL) || (szIP == NULL) || (ciMaxIPLen <= 0)) break; szIP[0] = 0; /* open the hosts file */ #ifdef _WIN32 pcStart = getenv("WINDIR"); if (pcStart != NULL) { sprintf(szLine, "%s\\system32\\drivers\\etc\\hosts", pcStart); } else { strcpy(szLine, "C:\\WINDOWS\\system32\\drivers\\etc\\hosts"); } #else strcpy(szLine, "/etc/hosts"); #endif fHosts = fopen(szLine, "r"); if (fHosts == NULL) break; /* read line by line ... */ while (fgets(szLine, EHL_LINE_LEN, fHosts) != NULL) { /* remove comments */ pcStart = strchr (szLine, '#'); if (pcStart != NULL) *pcStart = 0; strcat(szLine, " "); /* append a space character for easier parsing (*) */ /* first to appear: IP address */ iLen = strspn(szLine, "1234567890."); if ((iLen < 7) || (iLen > 15)) /* superficial test for anything between x.x.x.x and xxx.xxx.xxx.xxx */ continue; pcEnd = szLine + iLen; *pcEnd = 0; pcEnd++; /* not beyond the end of the line yet (*) */ /* check strings separated by blanks, tabs or newlines */ pcStart = pcEnd + strspn(pcEnd, " \t\n"); while (*pcStart != 0) { pcEnd = pcStart + strcspn(pcStart, " \t\n"); *pcEnd = 0; pcEnd++; /* not beyond the end of the line yet (*) */ if (strcasecmp(pcStart, cszName) == 0) { strncpy(szIP, szLine, ciMaxIPLen - 1); szIP[ciMaxIPLen - 1] = '\0'; iSuccess = 1; break; } pcStart = pcEnd + strspn(pcEnd, " \t\n"); } if (iSuccess) break; } } while (0); if (fHosts != NULL) fclose(fHosts); return (iSuccess); } /* this function is called with a NULL ctx to start the A/AAAA process */ static void _dns_result_a(struct dns_ctx *ctx, struct dns_rr_a4 *result, void *data) { dnsquery_t query = data; assert(query != NULL); query->query = NULL; if (ctx != NULL && result == NULL) { #define DRA_IP_LEN 16 char szIP[DRA_IP_LEN]; if (_etc_hosts_lookup (query->name, szIP, DRA_IP_LEN)) { log_debug(ZONE, "/etc/lookup for %s@%p: %s (%d)", query->name, query, szIP, query->s2s->etc_hosts_ttl); _dns_add_result (query, szIP, query->cur_port, query->cur_prio, query->cur_weight, query->s2s->etc_hosts_ttl); } else { log_debug(ZONE, "dns failure for %s@%p: A %s (%d)", query->name, query, query->cur_host, dns_status(ctx)); } } else if (result != NULL) { char ip[INET_ADDRSTRLEN]; int i; log_debug(ZONE, "dns response for %s@%p: A %s %d (%d)", query->name, query, result->dnsa4_qname, result->dnsa4_nrr, result->dnsa4_ttl); if (query->cur_expiry > 0 && result->dnsa4_ttl > query->cur_expiry) result->dnsa4_ttl = query->cur_expiry; for (i = 0; i < result->dnsa4_nrr; i++) { if (inet_ntop(AF_INET, &result->dnsa4_addr[i], ip, INET_ADDRSTRLEN) != NULL) { log_debug(ZONE, "dns response for %s@%p: A %s[%d] %s/%d", query->name, query, result->dnsa4_qname, i, ip, query->cur_port); _dns_add_result(query, ip, query->cur_port, query->cur_prio, query->cur_weight, result->dnsa4_ttl); } } free(result); } /* resolve the next host in the list */ if (xhash_iter_first(query->hosts)) { char *ipport, *c, *tmp; int ipport_len, ip_len, port_len; dnsres_t res; union xhashv xhv; xhv.dnsres_val = &res; /* get the first entry */ xhash_iter_get(query->hosts, (const char **) &ipport, &ipport_len, xhv.val); /* remove the host from the list */ xhash_iter_zap(query->hosts); c = memchr(ipport, '/', ipport_len); ip_len = c - ipport; c++; port_len = ipport_len - (c - ipport); /* resolve hostname */ free(query->cur_host); query->cur_host = strndup(ipport, ip_len); tmp = strndup(c, port_len); query->cur_port = atoi(tmp); free(tmp); query->cur_prio = res->prio; query->cur_weight = res->weight; query->cur_expiry = res->expiry; log_debug(ZONE, "dns ttl for %s@%p limited to %d", query->name, query, query->cur_expiry); if (query->s2s->resolve_aaaa) { log_debug(ZONE, "dns request for %s@%p: AAAA %s", query->name, query, query->cur_host); query->query = dns_submit_a6(NULL, query->cur_host, DNS_NOSRCH, _dns_result_aaaa, query); /* if submit failed, call ourselves with a NULL result */ if (query->query == NULL) _dns_result_aaaa(ctx, NULL, query); } else { log_debug(ZONE, "dns request for %s@%p: A %s", query->name, query, query->cur_host); query->query = dns_submit_a4(NULL, query->cur_host, DNS_NOSRCH, _dns_result_a, query); /* if submit failed, call ourselves with a NULL result */ if (query->query == NULL) _dns_result_a(ctx, NULL, query); } /* finished */ } else { time_t now = time(NULL); char *domain; free(query->cur_host); query->cur_host = NULL; log_debug(ZONE, "dns requests for %s@%p complete: %d (%d)", query->name, query, xhash_count(query->results), query->expiry); /* update query TTL */ if (query->expiry > query->s2s->dns_max_ttl) query->expiry = query->s2s->dns_max_ttl; if (query->expiry < query->s2s->dns_min_ttl) query->expiry = query->s2s->dns_min_ttl; query->expiry += now; /* update result TTLs - the query expiry MUST NOT be longer than all result expiries */ if (xhash_iter_first(query->results)) { union xhashv xhv; dnsres_t res; xhv.dnsres_val = &res; do { xhash_iter_get(query->results, NULL, NULL, xhv.val); if (res->expiry > query->s2s->dns_max_ttl) res->expiry = query->s2s->dns_max_ttl; if (res->expiry < query->s2s->dns_min_ttl) res->expiry = query->s2s->dns_min_ttl; res->expiry += now; } while(xhash_iter_next(query->results)); } xhash_free(query->hosts); query->hosts = NULL; if (idna_to_unicode_8z8z(query->name, &domain, 0) != IDNA_SUCCESS) { log_write(query->s2s->log, LOG_ERR, "idna dns decode for %s failed", query->name); /* fake empty results to shortcut resolution failure */ xhash_free(query->results); query->results = xhash_new(71); query->expiry = time(NULL) + 99999999; domain = strdup(query->name); } out_resolve(query->s2s, domain, query->results, query->expiry); free(domain); free(query->name); free(query); } } void dns_resolve_domain(s2s_t s2s, dnscache_t dns) { dnsquery_t query = (dnsquery_t) calloc(1, sizeof(struct dnsquery_st)); query->s2s = s2s; query->results = xhash_new(71); if (idna_to_ascii_8z(dns->name, &query->name, 0) != IDNA_SUCCESS) { log_write(s2s->log, LOG_ERR, "idna dns encode for %s failed", dns->name); /* shortcut resolution failure */ query->expiry = time(NULL) + 99999999; out_resolve(query->s2s, dns->name, query->results, query->expiry); return; } query->hosts = xhash_new(71); query->srv_i = -1; query->expiry = 0; query->cur_host = NULL; query->cur_port = 0; query->cur_expiry = 0; query->query = NULL; dns->query = query; log_debug(ZONE, "dns resolve for %s@%p started", query->name, query); /* - resolve all SRV records to host/port * - if no results, include domain/5269 * - resolve all host/port combinations * - return result */ _dns_result_srv(NULL, NULL, query); } /** responses from the resolver */ void out_resolve(s2s_t s2s, char *domain, xht results, time_t expiry) { dnscache_t dns; /* no results, resolve failed */ if(xhash_count(results) == 0) { dns = xhash_get(s2s->dnscache, domain); if (dns != NULL) { /* store negative DNS cache */ xhash_free(dns->results); dns->query = NULL; dns->results = NULL; dns->expiry = expiry; dns->pending = 0; } log_write(s2s->log, LOG_NOTICE, "dns lookup for %s failed", domain); /* bounce queue */ out_bounce_domain_queues(s2s, domain, stanza_err_REMOTE_SERVER_NOT_FOUND); xhash_free(results); return; } log_write(s2s->log, LOG_NOTICE, "dns lookup for %s returned %d result%s (ttl %d)", domain, xhash_count(results), xhash_count(results)!=1?"s":"", expiry - time(NULL)); /* get the cache entry */ dns = xhash_get(s2s->dnscache, domain); if(dns == NULL) { /* retry using punycode */ char *punydomain; if (idna_to_ascii_8z(domain, &punydomain, 0) == IDNA_SUCCESS) { dns = xhash_get(s2s->dnscache, punydomain); free(punydomain); } } if(dns == NULL) { log_write(s2s->log, LOG_ERR, "weird, never requested %s resolution", domain); return; } /* fill it out */ xhash_free(dns->results); dns->query = NULL; dns->results = results; dns->expiry = expiry; dns->pending = 0; out_flush_domain_queues(s2s, domain); /* delete the cache entry if caching is disabled */ if (!s2s->dns_cache_enabled && !dns->pending) { xhash_free(dns->results); xhash_zap(s2s->dnscache, domain); free(dns); } } /** mio callback for outgoing conns */ static int _out_mio_callback(mio_t m, mio_action_t a, mio_fd_t fd, void *data, void *arg) { conn_t out = (conn_t) arg; char ipport[INET6_ADDRSTRLEN + 17]; int nbytes; switch(a) { case action_READ: log_debug(ZONE, "read action on fd %d", fd->fd); /* they did something */ out->last_activity = time(NULL); ioctl(fd->fd, FIONREAD, &nbytes); if(nbytes == 0) { sx_kill(out->s); return 0; } return sx_can_read(out->s); case action_WRITE: log_debug(ZONE, "write action on fd %d", fd->fd); /* update activity timestamp */ out->last_activity = time(NULL); return sx_can_write(out->s); case action_CLOSE: log_debug(ZONE, "close action on fd %d", fd->fd); jqueue_push(out->s2s->dead, (void *) out->s, 0); log_write(out->s2s->log, LOG_NOTICE, "[%d] [%s, port=%d] disconnect, packets: %i", fd->fd, out->ip, out->port, out->packet_count); if (out->s2s->out_reuse) { /* generate the ip/port pair */ snprintf(ipport, INET6_ADDRSTRLEN + 16, "%s/%d", out->ip, out->port); xhash_zap(out->s2s->out_host, ipport); } if (xhash_iter_first(out->routes)) { char *rkey; int rkeylen; char *c; int c_len; /* remove all the out_dest entries */ do { xhash_iter_get(out->routes, (const char **) &rkey, &rkeylen, NULL); c = memchr(rkey, '/', rkeylen); c++; c_len = rkeylen - (c - rkey); log_debug(ZONE, "route '%.*s'", rkeylen, rkey); if (xhash_getx(out->s2s->out_dest, c, c_len) != NULL) { log_debug(ZONE, "removing dest entry for '%.*s'", c_len, c); xhash_zapx(out->s2s->out_dest, c, c_len); } } while(xhash_iter_next(out->routes)); } if (xhash_iter_first(out->routes)) { char *rkey; int rkeylen; jqueue_t q; int npkt; /* retry all the routes */ do { xhash_iter_get(out->routes, (const char **) &rkey, &rkeylen, NULL); q = xhash_getx(out->s2s->outq, rkey, rkeylen); if (out->s2s->retry_limit > 0 && q != NULL && jqueue_age(q) > out->s2s->retry_limit) { log_write(out->s2s->log, LOG_NOTICE, "[%d] [%s, port=%d] retry limit reached for '%.*s' queue", fd->fd, out->ip, out->port, rkeylen, rkey); q = NULL; } if (q != NULL && (npkt = jqueue_size(q)) > 0 && xhash_get(out->states, rkey) != (void*) conn_INPROGRESS) { conn_t retry; log_debug(ZONE, "retrying connection for '%.*s' queue", rkeylen, rkey); if (!out_route(out->s2s, rkey, rkeylen, &retry, 0)) { log_debug(ZONE, "retry successful"); if (retry != NULL) { /* flush queue */ out_flush_route_queue(out->s2s, rkey, rkeylen); } } else { log_debug(ZONE, "retry failed"); /* bounce queue */ out_bounce_route_queue(out->s2s, rkey, rkeylen, stanza_err_SERVICE_UNAVAILABLE); _out_dns_mark_bad(out); } } else { /* bounce queue */ out_bounce_route_queue(out->s2s, rkey, rkeylen, stanza_err_REMOTE_SERVER_TIMEOUT); _out_dns_mark_bad(out); } } while(xhash_iter_next(out->routes)); } jqueue_push(out->s2s->dead_conn, (void *) out, 0); case action_ACCEPT: break; } return 0; } void send_dialbacks(conn_t out) { char *rkey; int rkeylen; if (out->s2s->dns_bad_timeout > 0) { dnsres_t bad = xhash_get(out->s2s->dns_bad, out->key); if (bad != NULL) { log_debug(ZONE, "removing bad host entry for '%s'", out->key); xhash_zap(out->s2s->dns_bad, out->key); free(bad->key); free(bad); } } if (xhash_iter_first(out->routes)) { log_debug(ZONE, "sending dialback packets for %s", out->key); do { xhash_iter_get(out->routes, (const char **) &rkey, &rkeylen, NULL); _out_dialback(out, rkey, rkeylen); } while(xhash_iter_next(out->routes)); } return; } static int _out_sx_callback(sx_t s, sx_event_t e, void *data, void *arg) { conn_t out = (conn_t) arg; sx_buf_t buf = (sx_buf_t) data; int len, ns, elem, starttls = 0; sx_error_t *sxe; nad_t nad; switch(e) { case event_WANT_READ: log_debug(ZONE, "want read"); mio_read(out->s2s->mio, out->fd); break; case event_WANT_WRITE: log_debug(ZONE, "want write"); mio_write(out->s2s->mio, out->fd); break; case event_READ: log_debug(ZONE, "reading from %d", out->fd->fd); /* do the read */ len = recv(out->fd->fd, buf->data, buf->len, 0); if(len < 0) { if(MIO_WOULDBLOCK) { buf->len = 0; return 0; } log_write(out->s2s->log, LOG_NOTICE, "[%d] [%s, port=%d] read error: %s (%d)", out->fd->fd, out->ip, out->port, MIO_STRERROR(MIO_ERROR), MIO_ERROR); if (!out->online) { _out_dns_mark_bad(out); } sx_kill(s); return -1; } else if(len == 0) { /* they went away */ sx_kill(s); return -1; } log_debug(ZONE, "read %d bytes", len); buf->len = len; return len; case event_WRITE: log_debug(ZONE, "writing to %d", out->fd->fd); len = send(out->fd->fd, buf->data, buf->len, 0); if(len >= 0) { log_debug(ZONE, "%d bytes written", len); return len; } if(MIO_WOULDBLOCK) return 0; log_write(out->s2s->log, LOG_NOTICE, "[%d] [%s, port=%d] write error: %s (%d)", out->fd->fd, out->ip, out->port, MIO_STRERROR(MIO_ERROR), MIO_ERROR); if (!out->online) { _out_dns_mark_bad(out); } sx_kill(s); return -1; case event_ERROR: sxe = (sx_error_t *) data; log_write(out->s2s->log, LOG_NOTICE, "[%d] [%s, port=%d] error: %s (%s)", out->fd->fd, out->ip, out->port, sxe->generic, sxe->specific); /* mark as bad if we did not manage to connect or there is unrecoverable stream error */ if (!out->online || (sxe->code == SX_ERR_STREAM && (strstr(sxe->specific, "host-gone") || /* it's not there now */ strstr(sxe->specific, "host-unknown") || /* they do not service the host */ strstr(sxe->specific, "not-authorized") || /* they do not want us there */ strstr(sxe->specific, "see-other-host") || /* we do not support redirections yet */ strstr(sxe->specific, "system-shutdown") || /* they are going down */ strstr(sxe->specific, "policy-violation") || /* they do not want us there */ strstr(sxe->specific, "remote-connection-failed") || /* the required remote entity is gone */ strstr(sxe->specific, "unsupported-encoding") || /* they do not like our encoding */ strstr(sxe->specific, "undefined-condition") || /* something bad happend */ strstr(sxe->specific, "internal-server-error") || /* that server is broken */ strstr(sxe->specific, "unsupported-version") /* they do not support our stream version */ ))) { _out_dns_mark_bad(out); } sx_kill(s); return -1; case event_OPEN: log_debug(ZONE, "OPEN event for %s", out->key); break; case event_STREAM: /* check stream version - NULl = pre-xmpp (some jabber1 servers) */ log_debug(ZONE, "STREAM event for %s stream version is %s", out->key, out->s->res_version); /* first time, bring them online */ if(!out->online) { log_debug(ZONE, "outgoing conn to %s is online", out->key); /* if no stream version from either side, kick off dialback for each route, */ /* otherwise wait for stream features */ if (((out->s->res_version==NULL) || (out->s2s->sx_ssl == NULL)) && out->s2s->require_tls == 0) { log_debug(ZONE, "no stream version, sending dialbacks for %s immediately", out->key); out->online = 1; send_dialbacks(out); } else log_debug(ZONE, "outgoing conn to %s - waiting for STREAM features", out->key); } break; case event_PACKET: /* we're counting packets */ out->packet_count++; out->s2s->packet_count++; nad = (nad_t) data; /* watch for the features packet - STARTTLS and/or SASL*/ if ((out->s->res_version!=NULL) && NAD_NURI_L(nad, NAD_ENS(nad, 0)) == strlen(uri_STREAMS) && strncmp(uri_STREAMS, NAD_NURI(nad, NAD_ENS(nad, 0)), strlen(uri_STREAMS)) == 0 && NAD_ENAME_L(nad, 0) == 8 && strncmp("features", NAD_ENAME(nad, 0), 8) == 0) { log_debug(ZONE, "got the stream features packet"); #ifdef HAVE_SSL /* starttls if we can */ if(out->s2s->sx_ssl != NULL && s->ssf == 0) { ns = nad_find_scoped_namespace(nad, uri_TLS, NULL); if(ns >= 0) { elem = nad_find_elem(nad, 0, ns, "starttls", 1); if(elem >= 0) { log_debug(ZONE, "got STARTTLS in stream features"); if(sx_ssl_client_starttls(out->s2s->sx_ssl, s, out->s2s->local_pemfile) == 0) { starttls = 1; nad_free(nad); return 0; } log_write(out->s2s->log, LOG_ERR, "unable to establish encrypted session with peer"); } } } /* If we're not establishing a starttls connection, send dialbacks */ if (!starttls) { if (out->s2s->require_tls == 0 || s->ssf > 0) { log_debug(ZONE, "No STARTTLS, sending dialbacks for %s", out->key); out->online = 1; send_dialbacks(out); } else { log_debug(ZONE, "No STARTTLS, dialbacks disabled for non-TLS connections, cannot complete negotiation"); } } #else if (out->s2s->require_tls == 0) { out->online = 1; send_dialbacks(out); } #endif } /* we only accept dialback packets */ if(NAD_ENS(nad, 0) < 0 || NAD_NURI_L(nad, NAD_ENS(nad, 0)) != uri_DIALBACK_L || strncmp(uri_DIALBACK, NAD_NURI(nad, NAD_ENS(nad, 0)), uri_DIALBACK_L) != 0) { log_debug(ZONE, "got a non-dialback packet on an outgoing conn, dropping it"); nad_free(nad); return 0; } /* and then only result and verify */ if(NAD_ENAME_L(nad, 0) == 6) { if(strncmp("result", NAD_ENAME(nad, 0), 6) == 0) { _out_result(out, nad); return 0; } if(strncmp("verify", NAD_ENAME(nad, 0), 6) == 0) { _out_verify(out, nad); return 0; } } log_debug(ZONE, "unknown dialback packet, dropping it"); nad_free(nad); return 0; case event_CLOSED: if (out->fd != NULL) { mio_close(out->s2s->mio, out->fd); out->fd = NULL; } return -1; } return 0; } /** process incoming auth responses */ static void _out_result(conn_t out, nad_t nad) { int attr; jid_t from, to; char *rkey; int rkeylen; attr = nad_find_attr(nad, 0, -1, "from", NULL); if(attr < 0 || (from = jid_new(NAD_AVAL(nad, attr), NAD_AVAL_L(nad, attr))) == NULL) { log_debug(ZONE, "missing or invalid from on db result packet"); nad_free(nad); return; } attr = nad_find_attr(nad, 0, -1, "to", NULL); if(attr < 0 || (to = jid_new(NAD_AVAL(nad, attr), NAD_AVAL_L(nad, attr))) == NULL) { log_debug(ZONE, "missing or invalid to on db result packet"); jid_free(from); nad_free(nad); return; } rkey = s2s_route_key(NULL, to->domain, from->domain); rkeylen = strlen(rkey); /* key is valid */ if(nad_find_attr(nad, 0, -1, "type", "valid") >= 0) { log_write(out->s2s->log, LOG_NOTICE, "[%d] [%s, port=%d] outgoing route '%s' is now valid%s%s", out->fd->fd, out->ip, out->port, rkey, (out->s->flags & SX_SSL_WRAPPER) ? ", TLS negotiated" : "", out->s->compressed ? ", ZLIB compression enabled" : ""); xhash_put(out->states, pstrdup(xhash_pool(out->states), rkey), (void *) conn_VALID); /* !!! small leak here */ log_debug(ZONE, "%s valid, flushing queue", rkey); /* flush the queue */ out_flush_route_queue(out->s2s, rkey, rkeylen); free(rkey); jid_free(from); jid_free(to); nad_free(nad); return; } /* invalid */ log_write(out->s2s->log, LOG_NOTICE, "[%d] [%s, port=%d] outgoing route '%s' is now invalid", out->fd->fd, out->ip, out->port, rkey); /* close connection */ log_write(out->s2s->log, LOG_NOTICE, "[%d] [%s, port=%d] closing connection", out->fd->fd, out->ip, out->port); /* report stream error */ sx_error(out->s, stream_err_INVALID_ID, "dialback negotiation failed"); /* close the stream */ sx_close(out->s); /* bounce queue */ out_bounce_route_queue(out->s2s, rkey, rkeylen, stanza_err_SERVICE_UNAVAILABLE); free(rkey); jid_free(from); jid_free(to); nad_free(nad); } /** incoming stream authenticated */ static void _out_verify(conn_t out, nad_t nad) { int attr, ns; jid_t from, to; conn_t in; char *rkey; int valid; attr = nad_find_attr(nad, 0, -1, "from", NULL); if(attr < 0 || (from = jid_new(NAD_AVAL(nad, attr), NAD_AVAL_L(nad, attr))) == NULL) { log_debug(ZONE, "missing or invalid from on db verify packet"); nad_free(nad); return; } attr = nad_find_attr(nad, 0, -1, "to", NULL); if(attr < 0 || (to = jid_new(NAD_AVAL(nad, attr), NAD_AVAL_L(nad, attr))) == NULL) { log_debug(ZONE, "missing or invalid to on db verify packet"); jid_free(from); nad_free(nad); return; } attr = nad_find_attr(nad, 0, -1, "id", NULL); if(attr < 0) { log_debug(ZONE, "missing id on db verify packet"); jid_free(from); jid_free(to); nad_free(nad); return; } /* get the incoming conn */ in = xhash_getx(out->s2s->in, NAD_AVAL(nad, attr), NAD_AVAL_L(nad, attr)); if(in == NULL) { log_debug(ZONE, "got a verify for incoming conn %.*s, but it doesn't exist, dropping the packet", NAD_AVAL_L(nad, attr), NAD_AVAL(nad, attr)); jid_free(from); jid_free(to); nad_free(nad); return; } rkey = s2s_route_key(NULL, to->domain, from->domain); attr = nad_find_attr(nad, 0, -1, "type", "valid"); if(attr >= 0) { xhash_put(in->states, pstrdup(xhash_pool(in->states), rkey), (void *) conn_VALID); log_write(in->s2s->log, LOG_NOTICE, "[%d] [%s, port=%d] incoming route '%s' is now valid%s%s", in->fd->fd, in->ip, in->port, rkey, (in->s->flags & SX_SSL_WRAPPER) ? ", TLS negotiated" : "", in->s->compressed ? ", ZLIB compression enabled" : ""); valid = 1; } else { log_write(in->s2s->log, LOG_NOTICE, "[%d] [%s, port=%d] incoming route '%s' is now invalid", in->fd->fd, in->ip, in->port, rkey); valid = 0; } free(rkey); nad_free(nad); /* decrement outstanding verify counter */ --out->verify; /* let them know what happened */ nad = nad_new(); ns = nad_add_namespace(nad, uri_DIALBACK, "db"); nad_append_elem(nad, ns, "result", 0); nad_append_attr(nad, -1, "to", from->domain); nad_append_attr(nad, -1, "from", to->domain); nad_append_attr(nad, -1, "type", valid ? "valid" : "invalid"); /* off it goes */ sx_nad_write(in->s, nad); /* if invalid, close the stream */ if (!valid) { /* generate stream error */ sx_error(in->s, stream_err_INVALID_ID, "dialback negotiation failed"); /* close the incoming stream */ sx_close(in->s); } jid_free(from); jid_free(to); } /* bounce all packets in the queues for domain */ int out_bounce_domain_queues(s2s_t s2s, const char *domain, int err) { char *rkey; int rkeylen; int pktcount = 0; if (xhash_iter_first(s2s->outq)) { do { xhash_iter_get(s2s->outq, (const char **) &rkey, &rkeylen, NULL); if(s2s_route_key_match(NULL, (char *) domain, rkey, rkeylen)) pktcount += out_bounce_route_queue(s2s, rkey, rkeylen, err); } while(xhash_iter_next(s2s->outq)); } return pktcount; } /* bounce all packets in the queue for route */ int out_bounce_route_queue(s2s_t s2s, char *rkey, int rkeylen, int err) { jqueue_t q; pkt_t pkt; int pktcount = 0; q = xhash_getx(s2s->outq, rkey, rkeylen); if(q == NULL) return 0; while((pkt = jqueue_pull(q)) != NULL) { /* only packets with content, in namespace jabber:client and not already errors */ if(pkt->nad->ecur > 1 && NAD_NURI_L(pkt->nad, NAD_ENS(pkt->nad, 1)) == strlen(uri_CLIENT) && strncmp(NAD_NURI(pkt->nad, NAD_ENS(pkt->nad, 1)), uri_CLIENT, strlen(uri_CLIENT)) == 0 && nad_find_attr(pkt->nad, 0, -1, "error", NULL) < 0) { sx_nad_write(s2s->router, stanza_tofrom(stanza_tofrom(stanza_error(pkt->nad, 1, err), 1), 0)); pktcount++; } else nad_free(pkt->nad); jid_free(pkt->to); jid_free(pkt->from); free(pkt); } /* delete queue and remove domain from queue hash */ log_debug(ZONE, "deleting out packet queue for %.*s", rkeylen, rkey); rkey = q->key; jqueue_free(q); xhash_zap(s2s->outq, rkey); free(rkey); return pktcount; } int out_bounce_conn_queues(conn_t out, int err) { char *rkey; int rkeylen; int pktcount = 0; /* bounce queues for all domains handled by this connection - iterate through routes */ if (xhash_iter_first(out->routes)) { do { xhash_iter_get(out->routes, (const char **) &rkey, &rkeylen, NULL); pktcount += out_bounce_route_queue(out->s2s, rkey, rkeylen, err); } while(xhash_iter_next(out->routes)); } return pktcount; } void out_flush_domain_queues(s2s_t s2s, const char *domain) { char *rkey; int rkeylen; char *c; int c_len; if (xhash_iter_first(s2s->outq)) { do { xhash_iter_get(s2s->outq, (const char **) &rkey, &rkeylen, NULL); c = memchr(rkey, '/', rkeylen); c++; c_len = rkeylen - (c - rkey); if (strncmp(domain, c, c_len) == 0) out_flush_route_queue(s2s, rkey, rkeylen); } while(xhash_iter_next(s2s->outq)); } } void out_flush_route_queue(s2s_t s2s, char *rkey, int rkeylen) { jqueue_t q; pkt_t pkt; int npkt, i, ret; q = xhash_getx(s2s->outq, rkey, rkeylen); if(q == NULL) return; npkt = jqueue_size(q); log_debug(ZONE, "flushing %d packets for '%.*s' to out_packet", npkt, rkeylen, rkey); for(i = 0; i < npkt; i++) { pkt = jqueue_pull(q); if(pkt) { ret = out_packet(s2s, pkt); if (ret) { /* uh-oh. the queue was deleted... q and pkt have been freed if q->key == rkey, rkey has also been freed */ return; } } } /* delete queue for route and remove route from queue hash */ if (jqueue_size(q) == 0) { log_debug(ZONE, "deleting out packet queue for '%.*s'", rkeylen, rkey); rkey = q->key; jqueue_free(q); xhash_zap(s2s->outq, rkey); free(rkey); } else { log_debug(ZONE, "emptied queue gained more packets..."); } }
./CrossVul/dataset_final_sorted/CWE-20/c/bad_3722_0
crossvul-cpp_data_bad_3379_0
404: Not Found
./CrossVul/dataset_final_sorted/CWE-20/c/bad_3379_0
crossvul-cpp_data_good_1399_0
/* BGP attributes management routines. * Copyright (C) 1996, 97, 98, 1999 Kunihiro Ishiguro * * This file is part of GNU Zebra. * * GNU Zebra 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. * * GNU Zebra 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; see the file COPYING; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include <zebra.h> #include "linklist.h" #include "prefix.h" #include "memory.h" #include "vector.h" #include "stream.h" #include "log.h" #include "hash.h" #include "jhash.h" #include "queue.h" #include "table.h" #include "filter.h" #include "command.h" #include "bgpd/bgpd.h" #include "bgpd/bgp_attr.h" #include "bgpd/bgp_route.h" #include "bgpd/bgp_aspath.h" #include "bgpd/bgp_community.h" #include "bgpd/bgp_debug.h" #include "bgpd/bgp_errors.h" #include "bgpd/bgp_label.h" #include "bgpd/bgp_packet.h" #include "bgpd/bgp_ecommunity.h" #include "bgpd/bgp_lcommunity.h" #include "bgpd/bgp_updgrp.h" #include "bgpd/bgp_encap_types.h" #if ENABLE_BGP_VNC #include "bgpd/rfapi/bgp_rfapi_cfg.h" #include "bgp_encap_types.h" #include "bgp_vnc_types.h" #endif #include "bgp_encap_types.h" #include "bgp_evpn.h" #include "bgp_flowspec_private.h" /* Attribute strings for logging. */ static const struct message attr_str[] = { {BGP_ATTR_ORIGIN, "ORIGIN"}, {BGP_ATTR_AS_PATH, "AS_PATH"}, {BGP_ATTR_NEXT_HOP, "NEXT_HOP"}, {BGP_ATTR_MULTI_EXIT_DISC, "MULTI_EXIT_DISC"}, {BGP_ATTR_LOCAL_PREF, "LOCAL_PREF"}, {BGP_ATTR_ATOMIC_AGGREGATE, "ATOMIC_AGGREGATE"}, {BGP_ATTR_AGGREGATOR, "AGGREGATOR"}, {BGP_ATTR_COMMUNITIES, "COMMUNITY"}, {BGP_ATTR_ORIGINATOR_ID, "ORIGINATOR_ID"}, {BGP_ATTR_CLUSTER_LIST, "CLUSTER_LIST"}, {BGP_ATTR_DPA, "DPA"}, {BGP_ATTR_ADVERTISER, "ADVERTISER"}, {BGP_ATTR_RCID_PATH, "RCID_PATH"}, {BGP_ATTR_MP_REACH_NLRI, "MP_REACH_NLRI"}, {BGP_ATTR_MP_UNREACH_NLRI, "MP_UNREACH_NLRI"}, {BGP_ATTR_EXT_COMMUNITIES, "EXT_COMMUNITIES"}, {BGP_ATTR_AS4_PATH, "AS4_PATH"}, {BGP_ATTR_AS4_AGGREGATOR, "AS4_AGGREGATOR"}, {BGP_ATTR_AS_PATHLIMIT, "AS_PATHLIMIT"}, {BGP_ATTR_PMSI_TUNNEL, "PMSI_TUNNEL_ATTRIBUTE"}, {BGP_ATTR_ENCAP, "ENCAP"}, #if ENABLE_BGP_VNC_ATTR {BGP_ATTR_VNC, "VNC"}, #endif {BGP_ATTR_LARGE_COMMUNITIES, "LARGE_COMMUNITY"}, {BGP_ATTR_PREFIX_SID, "PREFIX_SID"}, {0}}; static const struct message attr_flag_str[] = { {BGP_ATTR_FLAG_OPTIONAL, "Optional"}, {BGP_ATTR_FLAG_TRANS, "Transitive"}, {BGP_ATTR_FLAG_PARTIAL, "Partial"}, /* bgp_attr_flags_diagnose() relies on this bit being last in this list */ {BGP_ATTR_FLAG_EXTLEN, "Extended Length"}, {0}}; static struct hash *cluster_hash; static void *cluster_hash_alloc(void *p) { const struct cluster_list *val = (const struct cluster_list *)p; struct cluster_list *cluster; cluster = XMALLOC(MTYPE_CLUSTER, sizeof(struct cluster_list)); cluster->length = val->length; if (cluster->length) { cluster->list = XMALLOC(MTYPE_CLUSTER_VAL, val->length); memcpy(cluster->list, val->list, val->length); } else cluster->list = NULL; cluster->refcnt = 0; return cluster; } /* Cluster list related functions. */ static struct cluster_list *cluster_parse(struct in_addr *pnt, int length) { struct cluster_list tmp; struct cluster_list *cluster; tmp.length = length; tmp.list = pnt; cluster = hash_get(cluster_hash, &tmp, cluster_hash_alloc); cluster->refcnt++; return cluster; } int cluster_loop_check(struct cluster_list *cluster, struct in_addr originator) { int i; for (i = 0; i < cluster->length / 4; i++) if (cluster->list[i].s_addr == originator.s_addr) return 1; return 0; } static unsigned int cluster_hash_key_make(void *p) { const struct cluster_list *cluster = p; return jhash(cluster->list, cluster->length, 0); } static bool cluster_hash_cmp(const void *p1, const void *p2) { const struct cluster_list *cluster1 = p1; const struct cluster_list *cluster2 = p2; return (cluster1->length == cluster2->length && memcmp(cluster1->list, cluster2->list, cluster1->length) == 0); } static void cluster_free(struct cluster_list *cluster) { if (cluster->list) XFREE(MTYPE_CLUSTER_VAL, cluster->list); XFREE(MTYPE_CLUSTER, cluster); } static struct cluster_list *cluster_intern(struct cluster_list *cluster) { struct cluster_list *find; find = hash_get(cluster_hash, cluster, cluster_hash_alloc); find->refcnt++; return find; } void cluster_unintern(struct cluster_list *cluster) { if (cluster->refcnt) cluster->refcnt--; if (cluster->refcnt == 0) { hash_release(cluster_hash, cluster); cluster_free(cluster); } } static void cluster_init(void) { cluster_hash = hash_create(cluster_hash_key_make, cluster_hash_cmp, "BGP Cluster"); } static void cluster_finish(void) { hash_clean(cluster_hash, (void (*)(void *))cluster_free); hash_free(cluster_hash); cluster_hash = NULL; } static struct hash *encap_hash = NULL; #if ENABLE_BGP_VNC static struct hash *vnc_hash = NULL; #endif struct bgp_attr_encap_subtlv *encap_tlv_dup(struct bgp_attr_encap_subtlv *orig) { struct bgp_attr_encap_subtlv *new; struct bgp_attr_encap_subtlv *tail; struct bgp_attr_encap_subtlv *p; for (p = orig, tail = new = NULL; p; p = p->next) { int size = sizeof(struct bgp_attr_encap_subtlv) + p->length; if (tail) { tail->next = XCALLOC(MTYPE_ENCAP_TLV, size); tail = tail->next; } else { tail = new = XCALLOC(MTYPE_ENCAP_TLV, size); } assert(tail); memcpy(tail, p, size); tail->next = NULL; } return new; } static void encap_free(struct bgp_attr_encap_subtlv *p) { struct bgp_attr_encap_subtlv *next; while (p) { next = p->next; p->next = NULL; XFREE(MTYPE_ENCAP_TLV, p); p = next; } } void bgp_attr_flush_encap(struct attr *attr) { if (!attr) return; if (attr->encap_subtlvs) { encap_free(attr->encap_subtlvs); attr->encap_subtlvs = NULL; } #if ENABLE_BGP_VNC if (attr->vnc_subtlvs) { encap_free(attr->vnc_subtlvs); attr->vnc_subtlvs = NULL; } #endif } /* * Compare encap sub-tlv chains * * 1 = equivalent * 0 = not equivalent * * This algorithm could be made faster if needed */ static int encap_same(const struct bgp_attr_encap_subtlv *h1, const struct bgp_attr_encap_subtlv *h2) { const struct bgp_attr_encap_subtlv *p; const struct bgp_attr_encap_subtlv *q; if (h1 == h2) return 1; if (h1 == NULL || h2 == NULL) return 0; for (p = h1; p; p = p->next) { for (q = h2; q; q = q->next) { if ((p->type == q->type) && (p->length == q->length) && !memcmp(p->value, q->value, p->length)) { break; } } if (!q) return 0; } for (p = h2; p; p = p->next) { for (q = h1; q; q = q->next) { if ((p->type == q->type) && (p->length == q->length) && !memcmp(p->value, q->value, p->length)) { break; } } if (!q) return 0; } return 1; } static void *encap_hash_alloc(void *p) { /* Encap structure is already allocated. */ return p; } typedef enum { ENCAP_SUBTLV_TYPE, #if ENABLE_BGP_VNC VNC_SUBTLV_TYPE #endif } encap_subtlv_type; static struct bgp_attr_encap_subtlv * encap_intern(struct bgp_attr_encap_subtlv *encap, encap_subtlv_type type) { struct bgp_attr_encap_subtlv *find; struct hash *hash = encap_hash; #if ENABLE_BGP_VNC if (type == VNC_SUBTLV_TYPE) hash = vnc_hash; #endif find = hash_get(hash, encap, encap_hash_alloc); if (find != encap) encap_free(encap); find->refcnt++; return find; } static void encap_unintern(struct bgp_attr_encap_subtlv **encapp, encap_subtlv_type type) { struct bgp_attr_encap_subtlv *encap = *encapp; if (encap->refcnt) encap->refcnt--; if (encap->refcnt == 0) { struct hash *hash = encap_hash; #if ENABLE_BGP_VNC if (type == VNC_SUBTLV_TYPE) hash = vnc_hash; #endif hash_release(hash, encap); encap_free(encap); *encapp = NULL; } } static unsigned int encap_hash_key_make(void *p) { const struct bgp_attr_encap_subtlv *encap = p; return jhash(encap->value, encap->length, 0); } static bool encap_hash_cmp(const void *p1, const void *p2) { return encap_same((const struct bgp_attr_encap_subtlv *)p1, (const struct bgp_attr_encap_subtlv *)p2); } static void encap_init(void) { encap_hash = hash_create(encap_hash_key_make, encap_hash_cmp, "BGP Encap Hash"); #if ENABLE_BGP_VNC vnc_hash = hash_create(encap_hash_key_make, encap_hash_cmp, "BGP VNC Hash"); #endif } static void encap_finish(void) { hash_clean(encap_hash, (void (*)(void *))encap_free); hash_free(encap_hash); encap_hash = NULL; #if ENABLE_BGP_VNC hash_clean(vnc_hash, (void (*)(void *))encap_free); hash_free(vnc_hash); vnc_hash = NULL; #endif } static bool overlay_index_same(const struct attr *a1, const struct attr *a2) { if (!a1 && a2) return false; if (!a2 && a1) return false; if (!a1 && !a2) return true; return !memcmp(&(a1->evpn_overlay), &(a2->evpn_overlay), sizeof(struct overlay_index)); } /* Unknown transit attribute. */ static struct hash *transit_hash; static void transit_free(struct transit *transit) { if (transit->val) XFREE(MTYPE_TRANSIT_VAL, transit->val); XFREE(MTYPE_TRANSIT, transit); } static void *transit_hash_alloc(void *p) { /* Transit structure is already allocated. */ return p; } static struct transit *transit_intern(struct transit *transit) { struct transit *find; find = hash_get(transit_hash, transit, transit_hash_alloc); if (find != transit) transit_free(transit); find->refcnt++; return find; } void transit_unintern(struct transit *transit) { if (transit->refcnt) transit->refcnt--; if (transit->refcnt == 0) { hash_release(transit_hash, transit); transit_free(transit); } } static unsigned int transit_hash_key_make(void *p) { const struct transit *transit = p; return jhash(transit->val, transit->length, 0); } static bool transit_hash_cmp(const void *p1, const void *p2) { const struct transit *transit1 = p1; const struct transit *transit2 = p2; return (transit1->length == transit2->length && memcmp(transit1->val, transit2->val, transit1->length) == 0); } static void transit_init(void) { transit_hash = hash_create(transit_hash_key_make, transit_hash_cmp, "BGP Transit Hash"); } static void transit_finish(void) { hash_clean(transit_hash, (void (*)(void *))transit_free); hash_free(transit_hash); transit_hash = NULL; } /* Attribute hash routines. */ static struct hash *attrhash; /* Shallow copy of an attribute * Though, not so shallow that it doesn't copy the contents * of the attr_extra pointed to by 'extra' */ void bgp_attr_dup(struct attr *new, struct attr *orig) { *new = *orig; } unsigned long int attr_count(void) { return attrhash->count; } unsigned long int attr_unknown_count(void) { return transit_hash->count; } unsigned int attrhash_key_make(void *p) { const struct attr *attr = (struct attr *)p; uint32_t key = 0; #define MIX(val) key = jhash_1word(val, key) #define MIX3(a, b, c) key = jhash_3words((a), (b), (c), key) MIX3(attr->origin, attr->nexthop.s_addr, attr->med); MIX3(attr->local_pref, attr->aggregator_as, attr->aggregator_addr.s_addr); MIX3(attr->weight, attr->mp_nexthop_global_in.s_addr, attr->originator_id.s_addr); MIX3(attr->tag, attr->label, attr->label_index); if (attr->aspath) MIX(aspath_key_make(attr->aspath)); if (attr->community) MIX(community_hash_make(attr->community)); if (attr->lcommunity) MIX(lcommunity_hash_make(attr->lcommunity)); if (attr->ecommunity) MIX(ecommunity_hash_make(attr->ecommunity)); if (attr->cluster) MIX(cluster_hash_key_make(attr->cluster)); if (attr->transit) MIX(transit_hash_key_make(attr->transit)); if (attr->encap_subtlvs) MIX(encap_hash_key_make(attr->encap_subtlvs)); #if ENABLE_BGP_VNC if (attr->vnc_subtlvs) MIX(encap_hash_key_make(attr->vnc_subtlvs)); #endif MIX(attr->mp_nexthop_len); key = jhash(attr->mp_nexthop_global.s6_addr, IPV6_MAX_BYTELEN, key); key = jhash(attr->mp_nexthop_local.s6_addr, IPV6_MAX_BYTELEN, key); MIX(attr->nh_ifindex); MIX(attr->nh_lla_ifindex); return key; } bool attrhash_cmp(const void *p1, const void *p2) { const struct attr *attr1 = p1; const struct attr *attr2 = p2; if (attr1->flag == attr2->flag && attr1->origin == attr2->origin && attr1->nexthop.s_addr == attr2->nexthop.s_addr && attr1->aspath == attr2->aspath && attr1->community == attr2->community && attr1->med == attr2->med && attr1->local_pref == attr2->local_pref && attr1->rmap_change_flags == attr2->rmap_change_flags) { if (attr1->aggregator_as == attr2->aggregator_as && attr1->aggregator_addr.s_addr == attr2->aggregator_addr.s_addr && attr1->weight == attr2->weight && attr1->tag == attr2->tag && attr1->label_index == attr2->label_index && attr1->mp_nexthop_len == attr2->mp_nexthop_len && attr1->ecommunity == attr2->ecommunity && attr1->lcommunity == attr2->lcommunity && attr1->cluster == attr2->cluster && attr1->transit == attr2->transit && (attr1->encap_tunneltype == attr2->encap_tunneltype) && encap_same(attr1->encap_subtlvs, attr2->encap_subtlvs) #if ENABLE_BGP_VNC && encap_same(attr1->vnc_subtlvs, attr2->vnc_subtlvs) #endif && IPV6_ADDR_SAME(&attr1->mp_nexthop_global, &attr2->mp_nexthop_global) && IPV6_ADDR_SAME(&attr1->mp_nexthop_local, &attr2->mp_nexthop_local) && IPV4_ADDR_SAME(&attr1->mp_nexthop_global_in, &attr2->mp_nexthop_global_in) && IPV4_ADDR_SAME(&attr1->originator_id, &attr2->originator_id) && overlay_index_same(attr1, attr2) && attr1->nh_ifindex == attr2->nh_ifindex && attr1->nh_lla_ifindex == attr2->nh_lla_ifindex) return true; } return false; } static void attrhash_init(void) { attrhash = hash_create(attrhash_key_make, attrhash_cmp, "BGP Attributes"); } /* * special for hash_clean below */ static void attr_vfree(void *attr) { XFREE(MTYPE_ATTR, attr); } static void attrhash_finish(void) { hash_clean(attrhash, attr_vfree); hash_free(attrhash); attrhash = NULL; } static void attr_show_all_iterator(struct hash_backet *backet, struct vty *vty) { struct attr *attr = backet->data; vty_out(vty, "attr[%ld] nexthop %s\n", attr->refcnt, inet_ntoa(attr->nexthop)); vty_out(vty, "\tflags: %" PRIu64 " med: %u local_pref: %u origin: %u weight: %u label: %u\n", attr->flag, attr->med, attr->local_pref, attr->origin, attr->weight, attr->label); } void attr_show_all(struct vty *vty) { hash_iterate(attrhash, (void (*)(struct hash_backet *, void *))attr_show_all_iterator, vty); } static void *bgp_attr_hash_alloc(void *p) { struct attr *val = (struct attr *)p; struct attr *attr; attr = XMALLOC(MTYPE_ATTR, sizeof(struct attr)); *attr = *val; if (val->encap_subtlvs) { val->encap_subtlvs = NULL; } #if ENABLE_BGP_VNC if (val->vnc_subtlvs) { val->vnc_subtlvs = NULL; } #endif attr->refcnt = 0; return attr; } /* Internet argument attribute. */ struct attr *bgp_attr_intern(struct attr *attr) { struct attr *find; /* Intern referenced strucutre. */ if (attr->aspath) { if (!attr->aspath->refcnt) attr->aspath = aspath_intern(attr->aspath); else attr->aspath->refcnt++; } if (attr->community) { if (!attr->community->refcnt) attr->community = community_intern(attr->community); else attr->community->refcnt++; } if (attr->ecommunity) { if (!attr->ecommunity->refcnt) attr->ecommunity = ecommunity_intern(attr->ecommunity); else attr->ecommunity->refcnt++; } if (attr->lcommunity) { if (!attr->lcommunity->refcnt) attr->lcommunity = lcommunity_intern(attr->lcommunity); else attr->lcommunity->refcnt++; } if (attr->cluster) { if (!attr->cluster->refcnt) attr->cluster = cluster_intern(attr->cluster); else attr->cluster->refcnt++; } if (attr->transit) { if (!attr->transit->refcnt) attr->transit = transit_intern(attr->transit); else attr->transit->refcnt++; } if (attr->encap_subtlvs) { if (!attr->encap_subtlvs->refcnt) attr->encap_subtlvs = encap_intern(attr->encap_subtlvs, ENCAP_SUBTLV_TYPE); else attr->encap_subtlvs->refcnt++; } #if ENABLE_BGP_VNC if (attr->vnc_subtlvs) { if (!attr->vnc_subtlvs->refcnt) attr->vnc_subtlvs = encap_intern(attr->vnc_subtlvs, VNC_SUBTLV_TYPE); else attr->vnc_subtlvs->refcnt++; } #endif /* At this point, attr only contains intern'd pointers. that means * if we find it in attrhash, it has all the same pointers and we * correctly updated the refcounts on these. * If we don't find it, we need to allocate a one because in all * cases this returns a new reference to a hashed attr, but the input * wasn't on hash. */ find = (struct attr *)hash_get(attrhash, attr, bgp_attr_hash_alloc); find->refcnt++; return find; } /* Make network statement's attribute. */ struct attr *bgp_attr_default_set(struct attr *attr, uint8_t origin) { memset(attr, 0, sizeof(struct attr)); attr->origin = origin; attr->flag |= ATTR_FLAG_BIT(BGP_ATTR_ORIGIN); attr->aspath = aspath_empty(); attr->flag |= ATTR_FLAG_BIT(BGP_ATTR_AS_PATH); attr->weight = BGP_ATTR_DEFAULT_WEIGHT; attr->tag = 0; attr->label_index = BGP_INVALID_LABEL_INDEX; attr->label = MPLS_INVALID_LABEL; attr->flag |= ATTR_FLAG_BIT(BGP_ATTR_NEXT_HOP); attr->mp_nexthop_len = IPV6_MAX_BYTELEN; return attr; } /* Create the attributes for an aggregate */ struct attr *bgp_attr_aggregate_intern(struct bgp *bgp, uint8_t origin, struct aspath *aspath, struct community *community, struct ecommunity *ecommunity, struct lcommunity *lcommunity, int as_set, uint8_t atomic_aggregate) { struct attr attr; struct attr *new; memset(&attr, 0, sizeof(struct attr)); /* Origin attribute. */ attr.origin = origin; attr.flag |= ATTR_FLAG_BIT(BGP_ATTR_ORIGIN); /* AS path attribute. */ if (aspath) attr.aspath = aspath_intern(aspath); else attr.aspath = aspath_empty(); attr.flag |= ATTR_FLAG_BIT(BGP_ATTR_AS_PATH); /* Next hop attribute. */ attr.flag |= ATTR_FLAG_BIT(BGP_ATTR_NEXT_HOP); if (community) { uint32_t gshut = COMMUNITY_GSHUT; /* If we are not shutting down ourselves and we are * aggregating a route that contains the GSHUT community we * need to remove that community when creating the aggregate */ if (!bgp_flag_check(bgp, BGP_FLAG_GRACEFUL_SHUTDOWN) && community_include(community, gshut)) { community_del_val(community, &gshut); } attr.community = community; attr.flag |= ATTR_FLAG_BIT(BGP_ATTR_COMMUNITIES); } if (ecommunity) { attr.ecommunity = ecommunity; attr.flag |= ATTR_FLAG_BIT(BGP_ATTR_EXT_COMMUNITIES); } if (lcommunity) { attr.lcommunity = lcommunity; attr.flag |= ATTR_FLAG_BIT(BGP_ATTR_LARGE_COMMUNITIES); } if (bgp_flag_check(bgp, BGP_FLAG_GRACEFUL_SHUTDOWN)) { bgp_attr_add_gshut_community(&attr); } attr.label_index = BGP_INVALID_LABEL_INDEX; attr.label = MPLS_INVALID_LABEL; attr.weight = BGP_ATTR_DEFAULT_WEIGHT; attr.mp_nexthop_len = IPV6_MAX_BYTELEN; if (!as_set || atomic_aggregate) attr.flag |= ATTR_FLAG_BIT(BGP_ATTR_ATOMIC_AGGREGATE); attr.flag |= ATTR_FLAG_BIT(BGP_ATTR_AGGREGATOR); if (CHECK_FLAG(bgp->config, BGP_CONFIG_CONFEDERATION)) attr.aggregator_as = bgp->confed_id; else attr.aggregator_as = bgp->as; attr.aggregator_addr = bgp->router_id; attr.label_index = BGP_INVALID_LABEL_INDEX; attr.label = MPLS_INVALID_LABEL; new = bgp_attr_intern(&attr); aspath_unintern(&new->aspath); return new; } /* Unintern just the sub-components of the attr, but not the attr */ void bgp_attr_unintern_sub(struct attr *attr) { /* aspath refcount shoud be decrement. */ if (attr->aspath) aspath_unintern(&attr->aspath); UNSET_FLAG(attr->flag, ATTR_FLAG_BIT(BGP_ATTR_AS_PATH)); if (attr->community) community_unintern(&attr->community); UNSET_FLAG(attr->flag, ATTR_FLAG_BIT(BGP_ATTR_COMMUNITIES)); if (attr->ecommunity) ecommunity_unintern(&attr->ecommunity); UNSET_FLAG(attr->flag, ATTR_FLAG_BIT(BGP_ATTR_EXT_COMMUNITIES)); if (attr->lcommunity) lcommunity_unintern(&attr->lcommunity); UNSET_FLAG(attr->flag, ATTR_FLAG_BIT(BGP_ATTR_LARGE_COMMUNITIES)); if (attr->cluster) cluster_unintern(attr->cluster); UNSET_FLAG(attr->flag, ATTR_FLAG_BIT(BGP_ATTR_CLUSTER_LIST)); if (attr->transit) transit_unintern(attr->transit); if (attr->encap_subtlvs) encap_unintern(&attr->encap_subtlvs, ENCAP_SUBTLV_TYPE); #if ENABLE_BGP_VNC if (attr->vnc_subtlvs) encap_unintern(&attr->vnc_subtlvs, VNC_SUBTLV_TYPE); #endif } /* * We have some show commands that let you experimentally * apply a route-map. When we apply the route-map * we are reseting values but not saving them for * posterity via intern'ing( because route-maps don't * do that) but at this point in time we need * to compare the new attr to the old and if the * routemap has changed it we need to, as Snoop Dog says, * Drop it like it's hot */ void bgp_attr_undup(struct attr *new, struct attr *old) { if (new->aspath != old->aspath) aspath_free(new->aspath); if (new->community != old->community) community_free(&new->community); if (new->ecommunity != old->ecommunity) ecommunity_free(&new->ecommunity); if (new->lcommunity != old->lcommunity) lcommunity_free(&new->lcommunity); } /* Free bgp attribute and aspath. */ void bgp_attr_unintern(struct attr **pattr) { struct attr *attr = *pattr; struct attr *ret; struct attr tmp; /* Decrement attribute reference. */ attr->refcnt--; tmp = *attr; /* If reference becomes zero then free attribute object. */ if (attr->refcnt == 0) { ret = hash_release(attrhash, attr); assert(ret != NULL); XFREE(MTYPE_ATTR, attr); *pattr = NULL; } bgp_attr_unintern_sub(&tmp); } void bgp_attr_flush(struct attr *attr) { if (attr->aspath && !attr->aspath->refcnt) { aspath_free(attr->aspath); attr->aspath = NULL; } if (attr->community && !attr->community->refcnt) community_free(&attr->community); if (attr->ecommunity && !attr->ecommunity->refcnt) ecommunity_free(&attr->ecommunity); if (attr->lcommunity && !attr->lcommunity->refcnt) lcommunity_free(&attr->lcommunity); if (attr->cluster && !attr->cluster->refcnt) { cluster_free(attr->cluster); attr->cluster = NULL; } if (attr->transit && !attr->transit->refcnt) { transit_free(attr->transit); attr->transit = NULL; } if (attr->encap_subtlvs && !attr->encap_subtlvs->refcnt) { encap_free(attr->encap_subtlvs); attr->encap_subtlvs = NULL; } #if ENABLE_BGP_VNC if (attr->vnc_subtlvs && !attr->vnc_subtlvs->refcnt) { encap_free(attr->vnc_subtlvs); attr->vnc_subtlvs = NULL; } #endif } /* Implement draft-scudder-idr-optional-transitive behaviour and * avoid resetting sessions for malformed attributes which are * are partial/optional and hence where the error likely was not * introduced by the sending neighbour. */ static bgp_attr_parse_ret_t bgp_attr_malformed(struct bgp_attr_parser_args *args, uint8_t subcode, bgp_size_t length) { struct peer *const peer = args->peer; const uint8_t flags = args->flags; /* startp and length must be special-cased, as whether or not to * send the attribute data with the NOTIFY depends on the error, * the caller therefore signals this with the seperate length argument */ uint8_t *notify_datap = (length > 0 ? args->startp : NULL); /* Only relax error handling for eBGP peers */ if (peer->sort != BGP_PEER_EBGP) { bgp_notify_send_with_data(peer, BGP_NOTIFY_UPDATE_ERR, subcode, notify_datap, length); return BGP_ATTR_PARSE_ERROR; } /* Adjust the stream getp to the end of the attribute, in case we can * still proceed but the caller hasn't read all the attribute. */ stream_set_getp(BGP_INPUT(peer), (args->startp - STREAM_DATA(BGP_INPUT(peer))) + args->total); switch (args->type) { /* where an attribute is relatively inconsequential, e.g. it does not * affect route selection, and can be safely ignored, then any such * attributes which are malformed should just be ignored and the route * processed as normal. */ case BGP_ATTR_AS4_AGGREGATOR: case BGP_ATTR_AGGREGATOR: case BGP_ATTR_ATOMIC_AGGREGATE: return BGP_ATTR_PARSE_PROCEED; /* Core attributes, particularly ones which may influence route * selection, should always cause session resets */ case BGP_ATTR_ORIGIN: case BGP_ATTR_AS_PATH: case BGP_ATTR_NEXT_HOP: case BGP_ATTR_MULTI_EXIT_DISC: case BGP_ATTR_LOCAL_PREF: case BGP_ATTR_COMMUNITIES: case BGP_ATTR_ORIGINATOR_ID: case BGP_ATTR_CLUSTER_LIST: case BGP_ATTR_MP_REACH_NLRI: case BGP_ATTR_MP_UNREACH_NLRI: case BGP_ATTR_EXT_COMMUNITIES: bgp_notify_send_with_data(peer, BGP_NOTIFY_UPDATE_ERR, subcode, notify_datap, length); return BGP_ATTR_PARSE_ERROR; } /* Partial optional attributes that are malformed should not cause * the whole session to be reset. Instead treat it as a withdrawal * of the routes, if possible. */ if (CHECK_FLAG(flags, BGP_ATTR_FLAG_TRANS) && CHECK_FLAG(flags, BGP_ATTR_FLAG_OPTIONAL) && CHECK_FLAG(flags, BGP_ATTR_FLAG_PARTIAL)) return BGP_ATTR_PARSE_WITHDRAW; /* default to reset */ return BGP_ATTR_PARSE_ERROR_NOTIFYPLS; } /* Find out what is wrong with the path attribute flag bits and log the error. "Flag bits" here stand for Optional, Transitive and Partial, but not for Extended Length. Checking O/T/P bits at once implies, that the attribute being diagnosed is defined by RFC as either a "well-known" or an "optional, non-transitive" attribute. */ static void bgp_attr_flags_diagnose(struct bgp_attr_parser_args *args, uint8_t desired_flags /* how RFC says it must be */ ) { uint8_t seen = 0, i; uint8_t real_flags = args->flags; const uint8_t attr_code = args->type; desired_flags &= ~BGP_ATTR_FLAG_EXTLEN; real_flags &= ~BGP_ATTR_FLAG_EXTLEN; for (i = 0; i <= 2; i++) /* O,T,P, but not E */ if (CHECK_FLAG(desired_flags, attr_flag_str[i].key) != CHECK_FLAG(real_flags, attr_flag_str[i].key)) { flog_err(EC_BGP_ATTR_FLAG, "%s attribute must%s be flagged as \"%s\"", lookup_msg(attr_str, attr_code, NULL), CHECK_FLAG(desired_flags, attr_flag_str[i].key) ? "" : " not", attr_flag_str[i].str); seen = 1; } if (!seen) { zlog_debug( "Strange, %s called for attr %s, but no problem found with flags" " (real flags 0x%x, desired 0x%x)", __func__, lookup_msg(attr_str, attr_code, NULL), real_flags, desired_flags); } } /* Required flags for attributes. EXTLEN will be masked off when testing, * as will PARTIAL for optional+transitive attributes. */ const uint8_t attr_flags_values[] = { [BGP_ATTR_ORIGIN] = BGP_ATTR_FLAG_TRANS, [BGP_ATTR_AS_PATH] = BGP_ATTR_FLAG_TRANS, [BGP_ATTR_NEXT_HOP] = BGP_ATTR_FLAG_TRANS, [BGP_ATTR_MULTI_EXIT_DISC] = BGP_ATTR_FLAG_OPTIONAL, [BGP_ATTR_LOCAL_PREF] = BGP_ATTR_FLAG_TRANS, [BGP_ATTR_ATOMIC_AGGREGATE] = BGP_ATTR_FLAG_TRANS, [BGP_ATTR_AGGREGATOR] = BGP_ATTR_FLAG_TRANS | BGP_ATTR_FLAG_OPTIONAL, [BGP_ATTR_COMMUNITIES] = BGP_ATTR_FLAG_TRANS | BGP_ATTR_FLAG_OPTIONAL, [BGP_ATTR_ORIGINATOR_ID] = BGP_ATTR_FLAG_OPTIONAL, [BGP_ATTR_CLUSTER_LIST] = BGP_ATTR_FLAG_OPTIONAL, [BGP_ATTR_MP_REACH_NLRI] = BGP_ATTR_FLAG_OPTIONAL, [BGP_ATTR_MP_UNREACH_NLRI] = BGP_ATTR_FLAG_OPTIONAL, [BGP_ATTR_EXT_COMMUNITIES] = BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_TRANS, [BGP_ATTR_AS4_PATH] = BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_TRANS, [BGP_ATTR_AS4_AGGREGATOR] = BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_TRANS, [BGP_ATTR_PMSI_TUNNEL] = BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_TRANS, [BGP_ATTR_LARGE_COMMUNITIES] = BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_TRANS, [BGP_ATTR_PREFIX_SID] = BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_TRANS, }; static const size_t attr_flags_values_max = array_size(attr_flags_values) - 1; static int bgp_attr_flag_invalid(struct bgp_attr_parser_args *args) { uint8_t mask = BGP_ATTR_FLAG_EXTLEN; const uint8_t flags = args->flags; const uint8_t attr_code = args->type; /* there may be attributes we don't know about */ if (attr_code > attr_flags_values_max) return 0; if (attr_flags_values[attr_code] == 0) return 0; /* RFC4271, "For well-known attributes, the Transitive bit MUST be set * to * 1." */ if (!CHECK_FLAG(BGP_ATTR_FLAG_OPTIONAL, flags) && !CHECK_FLAG(BGP_ATTR_FLAG_TRANS, flags)) { flog_err( EC_BGP_ATTR_FLAG, "%s well-known attributes must have transitive flag set (%x)", lookup_msg(attr_str, attr_code, NULL), flags); return 1; } /* "For well-known attributes and for optional non-transitive * attributes, * the Partial bit MUST be set to 0." */ if (CHECK_FLAG(flags, BGP_ATTR_FLAG_PARTIAL)) { if (!CHECK_FLAG(flags, BGP_ATTR_FLAG_OPTIONAL)) { flog_err(EC_BGP_ATTR_FLAG, "%s well-known attribute " "must NOT have the partial flag set (%x)", lookup_msg(attr_str, attr_code, NULL), flags); return 1; } if (CHECK_FLAG(flags, BGP_ATTR_FLAG_OPTIONAL) && !CHECK_FLAG(flags, BGP_ATTR_FLAG_TRANS)) { flog_err(EC_BGP_ATTR_FLAG, "%s optional + transitive attribute " "must NOT have the partial flag set (%x)", lookup_msg(attr_str, attr_code, NULL), flags); return 1; } } /* Optional transitive attributes may go through speakers that don't * reocgnise them and set the Partial bit. */ if (CHECK_FLAG(flags, BGP_ATTR_FLAG_OPTIONAL) && CHECK_FLAG(flags, BGP_ATTR_FLAG_TRANS)) SET_FLAG(mask, BGP_ATTR_FLAG_PARTIAL); if ((flags & ~mask) == attr_flags_values[attr_code]) return 0; bgp_attr_flags_diagnose(args, attr_flags_values[attr_code]); return 1; } /* Get origin attribute of the update message. */ static bgp_attr_parse_ret_t bgp_attr_origin(struct bgp_attr_parser_args *args) { struct peer *const peer = args->peer; struct attr *const attr = args->attr; const bgp_size_t length = args->length; /* If any recognized attribute has Attribute Length that conflicts with the expected length (based on the attribute type code), then the Error Subcode is set to Attribute Length Error. The Data field contains the erroneous attribute (type, length and value). */ if (length != 1) { flog_err(EC_BGP_ATTR_LEN, "Origin attribute length is not one %d", length); return bgp_attr_malformed(args, BGP_NOTIFY_UPDATE_ATTR_LENG_ERR, args->total); } /* Fetch origin attribute. */ attr->origin = stream_getc(BGP_INPUT(peer)); /* If the ORIGIN attribute has an undefined value, then the Error Subcode is set to Invalid Origin Attribute. The Data field contains the unrecognized attribute (type, length and value). */ if ((attr->origin != BGP_ORIGIN_IGP) && (attr->origin != BGP_ORIGIN_EGP) && (attr->origin != BGP_ORIGIN_INCOMPLETE)) { flog_err(EC_BGP_ATTR_ORIGIN, "Origin attribute value is invalid %d", attr->origin); return bgp_attr_malformed(args, BGP_NOTIFY_UPDATE_INVAL_ORIGIN, args->total); } /* Set oring attribute flag. */ attr->flag |= ATTR_FLAG_BIT(BGP_ATTR_ORIGIN); return 0; } /* Parse AS path information. This function is wrapper of aspath_parse. */ static int bgp_attr_aspath(struct bgp_attr_parser_args *args) { struct attr *const attr = args->attr; struct peer *const peer = args->peer; const bgp_size_t length = args->length; /* * peer with AS4 => will get 4Byte ASnums * otherwise, will get 16 Bit */ attr->aspath = aspath_parse(peer->curr, length, CHECK_FLAG(peer->cap, PEER_CAP_AS4_RCV)); /* In case of IBGP, length will be zero. */ if (!attr->aspath) { flog_err(EC_BGP_ATTR_MAL_AS_PATH, "Malformed AS path from %s, length is %d", peer->host, length); return bgp_attr_malformed(args, BGP_NOTIFY_UPDATE_MAL_AS_PATH, 0); } /* Set aspath attribute flag. */ attr->flag |= ATTR_FLAG_BIT(BGP_ATTR_AS_PATH); return BGP_ATTR_PARSE_PROCEED; } static bgp_attr_parse_ret_t bgp_attr_aspath_check(struct peer *const peer, struct attr *const attr) { /* These checks were part of bgp_attr_aspath, but with * as4 we should to check aspath things when * aspath synthesizing with as4_path has already taken place. * Otherwise we check ASPATH and use the synthesized thing, and that is * not right. * So do the checks later, i.e. here */ struct aspath *aspath; /* Confederation sanity check. */ if ((peer->sort == BGP_PEER_CONFED && !aspath_left_confed_check(attr->aspath)) || (peer->sort == BGP_PEER_EBGP && aspath_confed_check(attr->aspath))) { flog_err(EC_BGP_ATTR_MAL_AS_PATH, "Malformed AS path from %s", peer->host); bgp_notify_send(peer, BGP_NOTIFY_UPDATE_ERR, BGP_NOTIFY_UPDATE_MAL_AS_PATH); return BGP_ATTR_PARSE_ERROR; } /* First AS check for EBGP. */ if (CHECK_FLAG(peer->flags, PEER_FLAG_ENFORCE_FIRST_AS)) { if (peer->sort == BGP_PEER_EBGP && !aspath_firstas_check(attr->aspath, peer->as)) { flog_err(EC_BGP_ATTR_FIRST_AS, "%s incorrect first AS (must be %u)", peer->host, peer->as); bgp_notify_send(peer, BGP_NOTIFY_UPDATE_ERR, BGP_NOTIFY_UPDATE_MAL_AS_PATH); return BGP_ATTR_PARSE_ERROR; } } /* local-as prepend */ if (peer->change_local_as && !CHECK_FLAG(peer->flags, PEER_FLAG_LOCAL_AS_NO_PREPEND)) { aspath = aspath_dup(attr->aspath); aspath = aspath_add_seq(aspath, peer->change_local_as); aspath_unintern(&attr->aspath); attr->aspath = aspath_intern(aspath); } return BGP_ATTR_PARSE_PROCEED; } /* Parse AS4 path information. This function is another wrapper of aspath_parse. */ static int bgp_attr_as4_path(struct bgp_attr_parser_args *args, struct aspath **as4_path) { struct peer *const peer = args->peer; struct attr *const attr = args->attr; const bgp_size_t length = args->length; *as4_path = aspath_parse(peer->curr, length, 1); /* In case of IBGP, length will be zero. */ if (!*as4_path) { flog_err(EC_BGP_ATTR_MAL_AS_PATH, "Malformed AS4 path from %s, length is %d", peer->host, length); return bgp_attr_malformed(args, BGP_NOTIFY_UPDATE_MAL_AS_PATH, 0); } /* Set aspath attribute flag. */ attr->flag |= ATTR_FLAG_BIT(BGP_ATTR_AS4_PATH); return BGP_ATTR_PARSE_PROCEED; } /* Nexthop attribute. */ static bgp_attr_parse_ret_t bgp_attr_nexthop(struct bgp_attr_parser_args *args) { struct peer *const peer = args->peer; struct attr *const attr = args->attr; const bgp_size_t length = args->length; in_addr_t nexthop_h, nexthop_n; /* Check nexthop attribute length. */ if (length != 4) { flog_err(EC_BGP_ATTR_LEN, "Nexthop attribute length isn't four [%d]", length); return bgp_attr_malformed(args, BGP_NOTIFY_UPDATE_ATTR_LENG_ERR, args->total); } /* According to section 6.3 of RFC4271, syntactically incorrect NEXT_HOP attribute must result in a NOTIFICATION message (this is implemented below). At the same time, semantically incorrect NEXT_HOP is more likely to be just logged locally (this is implemented somewhere else). The UPDATE message gets ignored in any of these cases. */ nexthop_n = stream_get_ipv4(peer->curr); nexthop_h = ntohl(nexthop_n); if ((IPV4_NET0(nexthop_h) || IPV4_NET127(nexthop_h) || IPV4_CLASS_DE(nexthop_h)) && !BGP_DEBUG( allow_martians, ALLOW_MARTIANS)) /* loopbacks may be used in testing */ { char buf[INET_ADDRSTRLEN]; inet_ntop(AF_INET, &nexthop_n, buf, INET_ADDRSTRLEN); flog_err(EC_BGP_ATTR_MARTIAN_NH, "Martian nexthop %s", buf); return bgp_attr_malformed( args, BGP_NOTIFY_UPDATE_INVAL_NEXT_HOP, args->total); } attr->nexthop.s_addr = nexthop_n; attr->flag |= ATTR_FLAG_BIT(BGP_ATTR_NEXT_HOP); return BGP_ATTR_PARSE_PROCEED; } /* MED atrribute. */ static bgp_attr_parse_ret_t bgp_attr_med(struct bgp_attr_parser_args *args) { struct peer *const peer = args->peer; struct attr *const attr = args->attr; const bgp_size_t length = args->length; /* Length check. */ if (length != 4) { flog_err(EC_BGP_ATTR_LEN, "MED attribute length isn't four [%d]", length); return bgp_attr_malformed(args, BGP_NOTIFY_UPDATE_ATTR_LENG_ERR, args->total); } attr->med = stream_getl(peer->curr); attr->flag |= ATTR_FLAG_BIT(BGP_ATTR_MULTI_EXIT_DISC); return BGP_ATTR_PARSE_PROCEED; } /* Local preference attribute. */ static bgp_attr_parse_ret_t bgp_attr_local_pref(struct bgp_attr_parser_args *args) { struct peer *const peer = args->peer; struct attr *const attr = args->attr; const bgp_size_t length = args->length; /* Length check. */ if (length != 4) { flog_err(EC_BGP_ATTR_LEN, "LOCAL_PREF attribute length isn't 4 [%u]", length); return bgp_attr_malformed(args, BGP_NOTIFY_UPDATE_ATTR_LENG_ERR, args->total); } /* If it is contained in an UPDATE message that is received from an external peer, then this attribute MUST be ignored by the receiving speaker. */ if (peer->sort == BGP_PEER_EBGP) { stream_forward_getp(peer->curr, length); return BGP_ATTR_PARSE_PROCEED; } attr->local_pref = stream_getl(peer->curr); /* Set the local-pref flag. */ attr->flag |= ATTR_FLAG_BIT(BGP_ATTR_LOCAL_PREF); return BGP_ATTR_PARSE_PROCEED; } /* Atomic aggregate. */ static int bgp_attr_atomic(struct bgp_attr_parser_args *args) { struct attr *const attr = args->attr; const bgp_size_t length = args->length; /* Length check. */ if (length != 0) { flog_err(EC_BGP_ATTR_LEN, "ATOMIC_AGGREGATE attribute length isn't 0 [%u]", length); return bgp_attr_malformed(args, BGP_NOTIFY_UPDATE_ATTR_LENG_ERR, args->total); } /* Set atomic aggregate flag. */ attr->flag |= ATTR_FLAG_BIT(BGP_ATTR_ATOMIC_AGGREGATE); return BGP_ATTR_PARSE_PROCEED; } /* Aggregator attribute */ static int bgp_attr_aggregator(struct bgp_attr_parser_args *args) { struct peer *const peer = args->peer; struct attr *const attr = args->attr; const bgp_size_t length = args->length; int wantedlen = 6; /* peer with AS4 will send 4 Byte AS, peer without will send 2 Byte */ if (CHECK_FLAG(peer->cap, PEER_CAP_AS4_RCV)) wantedlen = 8; if (length != wantedlen) { flog_err(EC_BGP_ATTR_LEN, "AGGREGATOR attribute length isn't %u [%u]", wantedlen, length); return bgp_attr_malformed(args, BGP_NOTIFY_UPDATE_ATTR_LENG_ERR, args->total); } if (CHECK_FLAG(peer->cap, PEER_CAP_AS4_RCV)) attr->aggregator_as = stream_getl(peer->curr); else attr->aggregator_as = stream_getw(peer->curr); attr->aggregator_addr.s_addr = stream_get_ipv4(peer->curr); /* Set atomic aggregate flag. */ attr->flag |= ATTR_FLAG_BIT(BGP_ATTR_AGGREGATOR); return BGP_ATTR_PARSE_PROCEED; } /* New Aggregator attribute */ static bgp_attr_parse_ret_t bgp_attr_as4_aggregator(struct bgp_attr_parser_args *args, as_t *as4_aggregator_as, struct in_addr *as4_aggregator_addr) { struct peer *const peer = args->peer; struct attr *const attr = args->attr; const bgp_size_t length = args->length; if (length != 8) { flog_err(EC_BGP_ATTR_LEN, "New Aggregator length is not 8 [%d]", length); return bgp_attr_malformed(args, BGP_NOTIFY_UPDATE_ATTR_LENG_ERR, 0); } *as4_aggregator_as = stream_getl(peer->curr); as4_aggregator_addr->s_addr = stream_get_ipv4(peer->curr); attr->flag |= ATTR_FLAG_BIT(BGP_ATTR_AS4_AGGREGATOR); return BGP_ATTR_PARSE_PROCEED; } /* Munge Aggregator and New-Aggregator, AS_PATH and NEW_AS_PATH. */ static bgp_attr_parse_ret_t bgp_attr_munge_as4_attrs(struct peer *const peer, struct attr *const attr, struct aspath *as4_path, as_t as4_aggregator, struct in_addr *as4_aggregator_addr) { int ignore_as4_path = 0; struct aspath *newpath; if (!attr->aspath) { /* NULL aspath shouldn't be possible as bgp_attr_parse should * have * checked that all well-known, mandatory attributes were * present. * * Can only be a problem with peer itself - hard error */ return BGP_ATTR_PARSE_ERROR; } if (CHECK_FLAG(peer->cap, PEER_CAP_AS4_RCV)) { /* peer can do AS4, so we ignore AS4_PATH and AS4_AGGREGATOR * if given. * It is worth a warning though, because the peer really * should not send them */ if (BGP_DEBUG(as4, AS4)) { if (attr->flag & (ATTR_FLAG_BIT(BGP_ATTR_AS4_PATH))) zlog_debug("[AS4] %s %s AS4_PATH", peer->host, "AS4 capable peer, yet it sent"); if (attr->flag & (ATTR_FLAG_BIT(BGP_ATTR_AS4_AGGREGATOR))) zlog_debug("[AS4] %s %s AS4_AGGREGATOR", peer->host, "AS4 capable peer, yet it sent"); } return BGP_ATTR_PARSE_PROCEED; } /* We have a asn16 peer. First, look for AS4_AGGREGATOR * because that may override AS4_PATH */ if (attr->flag & (ATTR_FLAG_BIT(BGP_ATTR_AS4_AGGREGATOR))) { if (attr->flag & (ATTR_FLAG_BIT(BGP_ATTR_AGGREGATOR))) { /* received both. * if the as_number in aggregator is not AS_TRANS, * then AS4_AGGREGATOR and AS4_PATH shall be ignored * and the Aggregator shall be taken as * info on the aggregating node, and the AS_PATH * shall be taken as the AS_PATH * otherwise * the Aggregator shall be ignored and the * AS4_AGGREGATOR shall be taken as the * Aggregating node and the AS_PATH is to be * constructed "as in all other cases" */ if (attr->aggregator_as != BGP_AS_TRANS) { /* ignore */ if (BGP_DEBUG(as4, AS4)) zlog_debug( "[AS4] %s BGP not AS4 capable peer" " send AGGREGATOR != AS_TRANS and" " AS4_AGGREGATOR, so ignore" " AS4_AGGREGATOR and AS4_PATH", peer->host); ignore_as4_path = 1; } else { /* "New_aggregator shall be taken as aggregator" */ attr->aggregator_as = as4_aggregator; attr->aggregator_addr.s_addr = as4_aggregator_addr->s_addr; } } else { /* We received a AS4_AGGREGATOR but no AGGREGATOR. * That is bogus - but reading the conditions * we have to handle AS4_AGGREGATOR as if it were * AGGREGATOR in that case */ if (BGP_DEBUG(as4, AS4)) zlog_debug( "[AS4] %s BGP not AS4 capable peer send" " AS4_AGGREGATOR but no AGGREGATOR, will take" " it as if AGGREGATOR with AS_TRANS had been there", peer->host); attr->aggregator_as = as4_aggregator; /* sweep it under the carpet and simulate a "good" * AGGREGATOR */ attr->flag |= (ATTR_FLAG_BIT(BGP_ATTR_AGGREGATOR)); } } /* need to reconcile NEW_AS_PATH and AS_PATH */ if (!ignore_as4_path && (attr->flag & (ATTR_FLAG_BIT(BGP_ATTR_AS4_PATH)))) { newpath = aspath_reconcile_as4(attr->aspath, as4_path); if (!newpath) return BGP_ATTR_PARSE_ERROR; aspath_unintern(&attr->aspath); attr->aspath = aspath_intern(newpath); } return BGP_ATTR_PARSE_PROCEED; } /* Community attribute. */ static bgp_attr_parse_ret_t bgp_attr_community(struct bgp_attr_parser_args *args) { struct peer *const peer = args->peer; struct attr *const attr = args->attr; const bgp_size_t length = args->length; if (length == 0) { attr->community = NULL; return BGP_ATTR_PARSE_PROCEED; } attr->community = community_parse((uint32_t *)stream_pnt(peer->curr), length); /* XXX: fix community_parse to use stream API and remove this */ stream_forward_getp(peer->curr, length); if (!attr->community) return bgp_attr_malformed(args, BGP_NOTIFY_UPDATE_OPT_ATTR_ERR, args->total); attr->flag |= ATTR_FLAG_BIT(BGP_ATTR_COMMUNITIES); return BGP_ATTR_PARSE_PROCEED; } /* Originator ID attribute. */ static bgp_attr_parse_ret_t bgp_attr_originator_id(struct bgp_attr_parser_args *args) { struct peer *const peer = args->peer; struct attr *const attr = args->attr; const bgp_size_t length = args->length; /* Length check. */ if (length != 4) { flog_err(EC_BGP_ATTR_LEN, "Bad originator ID length %d", length); return bgp_attr_malformed(args, BGP_NOTIFY_UPDATE_ATTR_LENG_ERR, args->total); } attr->originator_id.s_addr = stream_get_ipv4(peer->curr); attr->flag |= ATTR_FLAG_BIT(BGP_ATTR_ORIGINATOR_ID); return BGP_ATTR_PARSE_PROCEED; } /* Cluster list attribute. */ static bgp_attr_parse_ret_t bgp_attr_cluster_list(struct bgp_attr_parser_args *args) { struct peer *const peer = args->peer; struct attr *const attr = args->attr; const bgp_size_t length = args->length; /* Check length. */ if (length % 4) { flog_err(EC_BGP_ATTR_LEN, "Bad cluster list length %d", length); return bgp_attr_malformed(args, BGP_NOTIFY_UPDATE_ATTR_LENG_ERR, args->total); } attr->cluster = cluster_parse((struct in_addr *)stream_pnt(peer->curr), length); /* XXX: Fix cluster_parse to use stream API and then remove this */ stream_forward_getp(peer->curr, length); attr->flag |= ATTR_FLAG_BIT(BGP_ATTR_CLUSTER_LIST); return BGP_ATTR_PARSE_PROCEED; } /* Multiprotocol reachability information parse. */ int bgp_mp_reach_parse(struct bgp_attr_parser_args *args, struct bgp_nlri *mp_update) { iana_afi_t pkt_afi; afi_t afi; iana_safi_t pkt_safi; safi_t safi; bgp_size_t nlri_len; size_t start; struct stream *s; struct peer *const peer = args->peer; struct attr *const attr = args->attr; const bgp_size_t length = args->length; /* Set end of packet. */ s = BGP_INPUT(peer); start = stream_get_getp(s); /* safe to read statically sized header? */ #define BGP_MP_REACH_MIN_SIZE 5 #define LEN_LEFT (length - (stream_get_getp(s) - start)) if ((length > STREAM_READABLE(s)) || (length < BGP_MP_REACH_MIN_SIZE)) { zlog_info("%s: %s sent invalid length, %lu", __func__, peer->host, (unsigned long)length); return BGP_ATTR_PARSE_ERROR_NOTIFYPLS; } /* Load AFI, SAFI. */ pkt_afi = stream_getw(s); pkt_safi = stream_getc(s); /* Convert AFI, SAFI to internal values, check. */ if (bgp_map_afi_safi_iana2int(pkt_afi, pkt_safi, &afi, &safi)) { /* Log if AFI or SAFI is unrecognized. This is not an error * unless * the attribute is otherwise malformed. */ if (bgp_debug_update(peer, NULL, NULL, 0)) zlog_debug( "%s: MP_REACH received AFI %u or SAFI %u is unrecognized", peer->host, pkt_afi, pkt_safi); return BGP_ATTR_PARSE_ERROR; } /* Get nexthop length. */ attr->mp_nexthop_len = stream_getc(s); if (LEN_LEFT < attr->mp_nexthop_len) { zlog_info( "%s: %s, MP nexthop length, %u, goes past end of attribute", __func__, peer->host, attr->mp_nexthop_len); return BGP_ATTR_PARSE_ERROR_NOTIFYPLS; } /* Nexthop length check. */ switch (attr->mp_nexthop_len) { case 0: if (safi != SAFI_FLOWSPEC) { zlog_info("%s: (%s) Wrong multiprotocol next hop length: %d", __func__, peer->host, attr->mp_nexthop_len); return BGP_ATTR_PARSE_ERROR_NOTIFYPLS; } break; case BGP_ATTR_NHLEN_VPNV4: stream_getl(s); /* RD high */ stream_getl(s); /* RD low */ /* * NOTE: intentional fall through * - for consistency in rx processing * * The following comment is to signal GCC this intention * and suppress the warning */ /* FALLTHRU */ case BGP_ATTR_NHLEN_IPV4: stream_get(&attr->mp_nexthop_global_in, s, IPV4_MAX_BYTELEN); /* Probably needed for RFC 2283 */ if (attr->nexthop.s_addr == 0) memcpy(&attr->nexthop.s_addr, &attr->mp_nexthop_global_in, IPV4_MAX_BYTELEN); break; case BGP_ATTR_NHLEN_IPV6_GLOBAL: case BGP_ATTR_NHLEN_VPNV6_GLOBAL: if (attr->mp_nexthop_len == BGP_ATTR_NHLEN_VPNV6_GLOBAL) { stream_getl(s); /* RD high */ stream_getl(s); /* RD low */ } stream_get(&attr->mp_nexthop_global, s, IPV6_MAX_BYTELEN); if (IN6_IS_ADDR_LINKLOCAL(&attr->mp_nexthop_global)) { if (!peer->nexthop.ifp) { zlog_warn("%s: interface not set appropriately to handle some attributes", peer->host); return BGP_ATTR_PARSE_WITHDRAW; } attr->nh_ifindex = peer->nexthop.ifp->ifindex; } break; case BGP_ATTR_NHLEN_IPV6_GLOBAL_AND_LL: case BGP_ATTR_NHLEN_VPNV6_GLOBAL_AND_LL: if (attr->mp_nexthop_len == BGP_ATTR_NHLEN_VPNV6_GLOBAL_AND_LL) { stream_getl(s); /* RD high */ stream_getl(s); /* RD low */ } stream_get(&attr->mp_nexthop_global, s, IPV6_MAX_BYTELEN); if (IN6_IS_ADDR_LINKLOCAL(&attr->mp_nexthop_global)) { if (!peer->nexthop.ifp) { zlog_warn("%s: interface not set appropriately to handle some attributes", peer->host); return BGP_ATTR_PARSE_WITHDRAW; } attr->nh_ifindex = peer->nexthop.ifp->ifindex; } if (attr->mp_nexthop_len == BGP_ATTR_NHLEN_VPNV6_GLOBAL_AND_LL) { stream_getl(s); /* RD high */ stream_getl(s); /* RD low */ } stream_get(&attr->mp_nexthop_local, s, IPV6_MAX_BYTELEN); if (!IN6_IS_ADDR_LINKLOCAL(&attr->mp_nexthop_local)) { char buf1[INET6_ADDRSTRLEN]; char buf2[INET6_ADDRSTRLEN]; if (bgp_debug_update(peer, NULL, NULL, 1)) zlog_debug( "%s rcvd nexthops %s, %s -- ignoring non-LL value", peer->host, inet_ntop(AF_INET6, &attr->mp_nexthop_global, buf1, INET6_ADDRSTRLEN), inet_ntop(AF_INET6, &attr->mp_nexthop_local, buf2, INET6_ADDRSTRLEN)); attr->mp_nexthop_len = IPV6_MAX_BYTELEN; } if (!peer->nexthop.ifp) { zlog_warn("%s: Interface not set appropriately to handle this some attributes", peer->host); return BGP_ATTR_PARSE_WITHDRAW; } attr->nh_lla_ifindex = peer->nexthop.ifp->ifindex; break; default: zlog_info("%s: (%s) Wrong multiprotocol next hop length: %d", __func__, peer->host, attr->mp_nexthop_len); return BGP_ATTR_PARSE_ERROR_NOTIFYPLS; } if (!LEN_LEFT) { zlog_info("%s: (%s) Failed to read SNPA and NLRI(s)", __func__, peer->host); return BGP_ATTR_PARSE_ERROR_NOTIFYPLS; } { uint8_t val; if ((val = stream_getc(s))) flog_warn( EC_BGP_DEFUNCT_SNPA_LEN, "%s sent non-zero value, %u, for defunct SNPA-length field", peer->host, val); } /* must have nrli_len, what is left of the attribute */ nlri_len = LEN_LEFT; if (nlri_len > STREAM_READABLE(s)) { zlog_info("%s: (%s) Failed to read NLRI", __func__, peer->host); return BGP_ATTR_PARSE_ERROR_NOTIFYPLS; } if (!nlri_len) { zlog_info("%s: (%s) No Reachability, Treating as a EOR marker", __func__, peer->host); mp_update->afi = afi; mp_update->safi = safi; return BGP_ATTR_PARSE_EOR; } mp_update->afi = afi; mp_update->safi = safi; mp_update->nlri = stream_pnt(s); mp_update->length = nlri_len; stream_forward_getp(s, nlri_len); attr->flag |= ATTR_FLAG_BIT(BGP_ATTR_MP_REACH_NLRI); return BGP_ATTR_PARSE_PROCEED; #undef LEN_LEFT } /* Multiprotocol unreachable parse */ int bgp_mp_unreach_parse(struct bgp_attr_parser_args *args, struct bgp_nlri *mp_withdraw) { struct stream *s; iana_afi_t pkt_afi; afi_t afi; iana_safi_t pkt_safi; safi_t safi; uint16_t withdraw_len; struct peer *const peer = args->peer; struct attr *const attr = args->attr; const bgp_size_t length = args->length; s = peer->curr; #define BGP_MP_UNREACH_MIN_SIZE 3 if ((length > STREAM_READABLE(s)) || (length < BGP_MP_UNREACH_MIN_SIZE)) return BGP_ATTR_PARSE_ERROR_NOTIFYPLS; pkt_afi = stream_getw(s); pkt_safi = stream_getc(s); /* Convert AFI, SAFI to internal values, check. */ if (bgp_map_afi_safi_iana2int(pkt_afi, pkt_safi, &afi, &safi)) { /* Log if AFI or SAFI is unrecognized. This is not an error * unless * the attribute is otherwise malformed. */ if (bgp_debug_update(peer, NULL, NULL, 0)) zlog_debug( "%s: MP_UNREACH received AFI %u or SAFI %u is unrecognized", peer->host, pkt_afi, pkt_safi); return BGP_ATTR_PARSE_ERROR; } withdraw_len = length - BGP_MP_UNREACH_MIN_SIZE; mp_withdraw->afi = afi; mp_withdraw->safi = safi; mp_withdraw->nlri = stream_pnt(s); mp_withdraw->length = withdraw_len; stream_forward_getp(s, withdraw_len); attr->flag |= ATTR_FLAG_BIT(BGP_ATTR_MP_UNREACH_NLRI); return BGP_ATTR_PARSE_PROCEED; } /* Large Community attribute. */ static bgp_attr_parse_ret_t bgp_attr_large_community(struct bgp_attr_parser_args *args) { struct peer *const peer = args->peer; struct attr *const attr = args->attr; const bgp_size_t length = args->length; /* * Large community follows new attribute format. */ if (length == 0) { attr->lcommunity = NULL; /* Empty extcomm doesn't seem to be invalid per se */ return BGP_ATTR_PARSE_PROCEED; } attr->lcommunity = lcommunity_parse((uint8_t *)stream_pnt(peer->curr), length); /* XXX: fix ecommunity_parse to use stream API */ stream_forward_getp(peer->curr, length); if (!attr->lcommunity) return bgp_attr_malformed(args, BGP_NOTIFY_UPDATE_OPT_ATTR_ERR, args->total); attr->flag |= ATTR_FLAG_BIT(BGP_ATTR_LARGE_COMMUNITIES); return BGP_ATTR_PARSE_PROCEED; } /* Extended Community attribute. */ static bgp_attr_parse_ret_t bgp_attr_ext_communities(struct bgp_attr_parser_args *args) { struct peer *const peer = args->peer; struct attr *const attr = args->attr; const bgp_size_t length = args->length; uint8_t sticky = 0; if (length == 0) { attr->ecommunity = NULL; /* Empty extcomm doesn't seem to be invalid per se */ return BGP_ATTR_PARSE_PROCEED; } attr->ecommunity = ecommunity_parse((uint8_t *)stream_pnt(peer->curr), length); /* XXX: fix ecommunity_parse to use stream API */ stream_forward_getp(peer->curr, length); if (!attr->ecommunity) return bgp_attr_malformed(args, BGP_NOTIFY_UPDATE_OPT_ATTR_ERR, args->total); attr->flag |= ATTR_FLAG_BIT(BGP_ATTR_EXT_COMMUNITIES); /* Extract MAC mobility sequence number, if any. */ attr->mm_seqnum = bgp_attr_mac_mobility_seqnum(attr, &sticky); attr->sticky = sticky; /* Check if this is a Gateway MAC-IP advertisement */ attr->default_gw = bgp_attr_default_gw(attr); /* Handle scenario where router flag ecommunity is not * set but default gw ext community is present. * Use default gateway, set and propogate R-bit. */ if (attr->default_gw) attr->router_flag = 1; /* Check EVPN Neighbor advertisement flags, R-bit */ bgp_attr_evpn_na_flag(attr, &attr->router_flag); /* Extract the Rmac, if any */ bgp_attr_rmac(attr, &attr->rmac); return BGP_ATTR_PARSE_PROCEED; } /* Parse Tunnel Encap attribute in an UPDATE */ static int bgp_attr_encap(uint8_t type, struct peer *peer, /* IN */ bgp_size_t length, /* IN: attr's length field */ struct attr *attr, /* IN: caller already allocated */ uint8_t flag, /* IN: attr's flags field */ uint8_t *startp) { bgp_size_t total; uint16_t tunneltype = 0; total = length + (CHECK_FLAG(flag, BGP_ATTR_FLAG_EXTLEN) ? 4 : 3); if (!CHECK_FLAG(flag, BGP_ATTR_FLAG_TRANS) || !CHECK_FLAG(flag, BGP_ATTR_FLAG_OPTIONAL)) { zlog_info( "Tunnel Encap attribute flag isn't optional and transitive %d", flag); bgp_notify_send_with_data(peer, BGP_NOTIFY_UPDATE_ERR, BGP_NOTIFY_UPDATE_ATTR_FLAG_ERR, startp, total); return -1; } if (BGP_ATTR_ENCAP == type) { /* read outer TLV type and length */ uint16_t tlv_length; if (length < 4) { zlog_info( "Tunnel Encap attribute not long enough to contain outer T,L"); bgp_notify_send_with_data( peer, BGP_NOTIFY_UPDATE_ERR, BGP_NOTIFY_UPDATE_OPT_ATTR_ERR, startp, total); return -1; } tunneltype = stream_getw(BGP_INPUT(peer)); tlv_length = stream_getw(BGP_INPUT(peer)); length -= 4; if (tlv_length != length) { zlog_info("%s: tlv_length(%d) != length(%d)", __func__, tlv_length, length); } } while (length >= 4) { uint16_t subtype = 0; uint16_t sublength = 0; struct bgp_attr_encap_subtlv *tlv; if (BGP_ATTR_ENCAP == type) { subtype = stream_getc(BGP_INPUT(peer)); sublength = stream_getc(BGP_INPUT(peer)); length -= 2; #if ENABLE_BGP_VNC } else { subtype = stream_getw(BGP_INPUT(peer)); sublength = stream_getw(BGP_INPUT(peer)); length -= 4; #endif } if (sublength > length) { zlog_info( "Tunnel Encap attribute sub-tlv length %d exceeds remaining length %d", sublength, length); bgp_notify_send_with_data( peer, BGP_NOTIFY_UPDATE_ERR, BGP_NOTIFY_UPDATE_OPT_ATTR_ERR, startp, total); return -1; } /* alloc and copy sub-tlv */ /* TBD make sure these are freed when attributes are released */ tlv = XCALLOC(MTYPE_ENCAP_TLV, sizeof(struct bgp_attr_encap_subtlv) + sublength); tlv->type = subtype; tlv->length = sublength; stream_get(tlv->value, peer->curr, sublength); length -= sublength; /* attach tlv to encap chain */ if (BGP_ATTR_ENCAP == type) { struct bgp_attr_encap_subtlv *stlv_last; for (stlv_last = attr->encap_subtlvs; stlv_last && stlv_last->next; stlv_last = stlv_last->next) ; if (stlv_last) { stlv_last->next = tlv; } else { attr->encap_subtlvs = tlv; } #if ENABLE_BGP_VNC } else { struct bgp_attr_encap_subtlv *stlv_last; for (stlv_last = attr->vnc_subtlvs; stlv_last && stlv_last->next; stlv_last = stlv_last->next) ; if (stlv_last) { stlv_last->next = tlv; } else { attr->vnc_subtlvs = tlv; } #endif } } if (BGP_ATTR_ENCAP == type) { attr->encap_tunneltype = tunneltype; } if (length) { /* spurious leftover data */ zlog_info( "Tunnel Encap attribute length is bad: %d leftover octets", length); bgp_notify_send_with_data(peer, BGP_NOTIFY_UPDATE_ERR, BGP_NOTIFY_UPDATE_OPT_ATTR_ERR, startp, total); return -1; } return 0; } /* * Read an individual SID value returning how much data we have read * Returns 0 if there was an error that needs to be passed up the stack */ static bgp_attr_parse_ret_t bgp_attr_psid_sub(int32_t type, int32_t length, struct bgp_attr_parser_args *args, struct bgp_nlri *mp_update) { struct peer *const peer = args->peer; struct attr *const attr = args->attr; uint32_t label_index; struct in6_addr ipv6_sid; uint32_t srgb_base; uint32_t srgb_range; int srgb_count; if (type == BGP_PREFIX_SID_LABEL_INDEX) { if (length != BGP_PREFIX_SID_LABEL_INDEX_LENGTH) { flog_err( EC_BGP_ATTR_LEN, "Prefix SID label index length is %d instead of %d", length, BGP_PREFIX_SID_LABEL_INDEX_LENGTH); return bgp_attr_malformed(args, BGP_NOTIFY_UPDATE_ATTR_LENG_ERR, args->total); } /* Ignore flags and reserved */ stream_getc(peer->curr); stream_getw(peer->curr); /* Fetch the label index and see if it is valid. */ label_index = stream_getl(peer->curr); if (label_index == BGP_INVALID_LABEL_INDEX) return bgp_attr_malformed(args, BGP_NOTIFY_UPDATE_OPT_ATTR_ERR, args->total); /* Store label index; subsequently, we'll check on * address-family */ attr->label_index = label_index; /* * Ignore the Label index attribute unless received for * labeled-unicast * SAFI. */ if (!mp_update->length || mp_update->safi != SAFI_LABELED_UNICAST) attr->label_index = BGP_INVALID_LABEL_INDEX; } /* Placeholder code for the IPv6 SID type */ else if (type == BGP_PREFIX_SID_IPV6) { if (length != BGP_PREFIX_SID_IPV6_LENGTH) { flog_err(EC_BGP_ATTR_LEN, "Prefix SID IPv6 length is %d instead of %d", length, BGP_PREFIX_SID_IPV6_LENGTH); return bgp_attr_malformed(args, BGP_NOTIFY_UPDATE_ATTR_LENG_ERR, args->total); } /* Ignore reserved */ stream_getc(peer->curr); stream_getw(peer->curr); stream_get(&ipv6_sid, peer->curr, 16); } /* Placeholder code for the Originator SRGB type */ else if (type == BGP_PREFIX_SID_ORIGINATOR_SRGB) { /* Ignore flags */ stream_getw(peer->curr); length -= 2; if (length % BGP_PREFIX_SID_ORIGINATOR_SRGB_LENGTH) { flog_err( EC_BGP_ATTR_LEN, "Prefix SID Originator SRGB length is %d, it must be a multiple of %d ", length, BGP_PREFIX_SID_ORIGINATOR_SRGB_LENGTH); return bgp_attr_malformed( args, BGP_NOTIFY_UPDATE_ATTR_LENG_ERR, args->total); } srgb_count = length / BGP_PREFIX_SID_ORIGINATOR_SRGB_LENGTH; for (int i = 0; i < srgb_count; i++) { stream_get(&srgb_base, peer->curr, 3); stream_get(&srgb_range, peer->curr, 3); } } return BGP_ATTR_PARSE_PROCEED; } /* Prefix SID attribute * draft-ietf-idr-bgp-prefix-sid-05 */ bgp_attr_parse_ret_t bgp_attr_prefix_sid(int32_t tlength, struct bgp_attr_parser_args *args, struct bgp_nlri *mp_update) { struct peer *const peer = args->peer; struct attr *const attr = args->attr; bgp_attr_parse_ret_t ret; attr->flag |= ATTR_FLAG_BIT(BGP_ATTR_PREFIX_SID); while (tlength) { int32_t type, length; type = stream_getc(peer->curr); length = stream_getw(peer->curr); ret = bgp_attr_psid_sub(type, length, args, mp_update); if (ret != BGP_ATTR_PARSE_PROCEED) return ret; /* * Subtract length + the T and the L * since length is the Vector portion */ tlength -= length + 3; if (tlength < 0) { flog_err( EC_BGP_ATTR_LEN, "Prefix SID internal length %d causes us to read beyond the total Prefix SID length", length); return bgp_attr_malformed(args, BGP_NOTIFY_UPDATE_ATTR_LENG_ERR, args->total); } } return BGP_ATTR_PARSE_PROCEED; } /* PMSI tunnel attribute (RFC 6514) * Basic validation checks done here. */ static bgp_attr_parse_ret_t bgp_attr_pmsi_tunnel(struct bgp_attr_parser_args *args) { struct peer *const peer = args->peer; struct attr *const attr = args->attr; const bgp_size_t length = args->length; uint8_t tnl_type; /* Verify that the receiver is expecting "ingress replication" as we * can only support that. */ if (length < 2) { flog_err(EC_BGP_ATTR_LEN, "Bad PMSI tunnel attribute length %d", length); return bgp_attr_malformed(args, BGP_NOTIFY_UPDATE_ATTR_LENG_ERR, args->total); } stream_getc(peer->curr); /* Flags */ tnl_type = stream_getc(peer->curr); if (tnl_type > PMSI_TNLTYPE_MAX) { flog_err(EC_BGP_ATTR_PMSI_TYPE, "Invalid PMSI tunnel attribute type %d", tnl_type); return bgp_attr_malformed(args, BGP_NOTIFY_UPDATE_OPT_ATTR_ERR, args->total); } if (tnl_type == PMSI_TNLTYPE_INGR_REPL) { if (length != 9) { flog_err(EC_BGP_ATTR_PMSI_LEN, "Bad PMSI tunnel attribute length %d for IR", length); return bgp_attr_malformed( args, BGP_NOTIFY_UPDATE_ATTR_LENG_ERR, args->total); } } attr->flag |= ATTR_FLAG_BIT(BGP_ATTR_PMSI_TUNNEL); attr->pmsi_tnl_type = tnl_type; /* Forward read pointer of input stream. */ stream_forward_getp(peer->curr, length - 2); return BGP_ATTR_PARSE_PROCEED; } /* BGP unknown attribute treatment. */ static bgp_attr_parse_ret_t bgp_attr_unknown(struct bgp_attr_parser_args *args) { bgp_size_t total = args->total; struct transit *transit; struct peer *const peer = args->peer; struct attr *const attr = args->attr; uint8_t *const startp = args->startp; const uint8_t type = args->type; const uint8_t flag = args->flags; const bgp_size_t length = args->length; if (bgp_debug_update(peer, NULL, NULL, 1)) zlog_debug( "%s Unknown attribute is received (type %d, length %d)", peer->host, type, length); /* Forward read pointer of input stream. */ stream_forward_getp(peer->curr, length); /* If any of the mandatory well-known attributes are not recognized, then the Error Subcode is set to Unrecognized Well-known Attribute. The Data field contains the unrecognized attribute (type, length and value). */ if (!CHECK_FLAG(flag, BGP_ATTR_FLAG_OPTIONAL)) { return bgp_attr_malformed(args, BGP_NOTIFY_UPDATE_UNREC_ATTR, args->total); } /* Unrecognized non-transitive optional attributes must be quietly ignored and not passed along to other BGP peers. */ if (!CHECK_FLAG(flag, BGP_ATTR_FLAG_TRANS)) return BGP_ATTR_PARSE_PROCEED; /* If a path with recognized transitive optional attribute is accepted and passed along to other BGP peers and the Partial bit in the Attribute Flags octet is set to 1 by some previous AS, it is not set back to 0 by the current AS. */ SET_FLAG(*startp, BGP_ATTR_FLAG_PARTIAL); /* Store transitive attribute to the end of attr->transit. */ if (!attr->transit) attr->transit = XCALLOC(MTYPE_TRANSIT, sizeof(struct transit)); transit = attr->transit; if (transit->val) transit->val = XREALLOC(MTYPE_TRANSIT_VAL, transit->val, transit->length + total); else transit->val = XMALLOC(MTYPE_TRANSIT_VAL, total); memcpy(transit->val + transit->length, startp, total); transit->length += total; return BGP_ATTR_PARSE_PROCEED; } /* Well-known attribute check. */ static int bgp_attr_check(struct peer *peer, struct attr *attr) { uint8_t type = 0; /* BGP Graceful-Restart End-of-RIB for IPv4 unicast is signaled as an * empty UPDATE. */ if (CHECK_FLAG(peer->cap, PEER_CAP_RESTART_RCV) && !attr->flag) return BGP_ATTR_PARSE_PROCEED; /* "An UPDATE message that contains the MP_UNREACH_NLRI is not required to carry any other path attributes.", though if MP_REACH_NLRI or NLRI are present, it should. Check for any other attribute being present instead. */ if ((!CHECK_FLAG(attr->flag, ATTR_FLAG_BIT(BGP_ATTR_MP_REACH_NLRI)) && CHECK_FLAG(attr->flag, ATTR_FLAG_BIT(BGP_ATTR_MP_UNREACH_NLRI)))) return BGP_ATTR_PARSE_PROCEED; if (!CHECK_FLAG(attr->flag, ATTR_FLAG_BIT(BGP_ATTR_ORIGIN))) type = BGP_ATTR_ORIGIN; if (!CHECK_FLAG(attr->flag, ATTR_FLAG_BIT(BGP_ATTR_AS_PATH))) type = BGP_ATTR_AS_PATH; /* RFC 2858 makes Next-Hop optional/ignored, if MP_REACH_NLRI is present * and * NLRI is empty. We can't easily check NLRI empty here though. */ if (!CHECK_FLAG(attr->flag, ATTR_FLAG_BIT(BGP_ATTR_NEXT_HOP)) && !CHECK_FLAG(attr->flag, ATTR_FLAG_BIT(BGP_ATTR_MP_REACH_NLRI))) type = BGP_ATTR_NEXT_HOP; if (peer->sort == BGP_PEER_IBGP && !CHECK_FLAG(attr->flag, ATTR_FLAG_BIT(BGP_ATTR_LOCAL_PREF))) type = BGP_ATTR_LOCAL_PREF; if (type) { flog_warn(EC_BGP_MISSING_ATTRIBUTE, "%s Missing well-known attribute %s.", peer->host, lookup_msg(attr_str, type, NULL)); bgp_notify_send_with_data(peer, BGP_NOTIFY_UPDATE_ERR, BGP_NOTIFY_UPDATE_MISS_ATTR, &type, 1); return BGP_ATTR_PARSE_ERROR; } return BGP_ATTR_PARSE_PROCEED; } /* Read attribute of update packet. This function is called from bgp_update_receive() in bgp_packet.c. */ bgp_attr_parse_ret_t bgp_attr_parse(struct peer *peer, struct attr *attr, bgp_size_t size, struct bgp_nlri *mp_update, struct bgp_nlri *mp_withdraw) { bgp_attr_parse_ret_t ret; uint8_t flag = 0; uint8_t type = 0; bgp_size_t length; uint8_t *startp, *endp; uint8_t *attr_endp; uint8_t seen[BGP_ATTR_BITMAP_SIZE]; /* we need the as4_path only until we have synthesized the as_path with * it */ /* same goes for as4_aggregator */ struct aspath *as4_path = NULL; as_t as4_aggregator = 0; struct in_addr as4_aggregator_addr = {.s_addr = 0}; /* Initialize bitmap. */ memset(seen, 0, BGP_ATTR_BITMAP_SIZE); /* End pointer of BGP attribute. */ endp = BGP_INPUT_PNT(peer) + size; /* Get attributes to the end of attribute length. */ while (BGP_INPUT_PNT(peer) < endp) { /* Check remaining length check.*/ if (endp - BGP_INPUT_PNT(peer) < BGP_ATTR_MIN_LEN) { /* XXX warning: long int format, int arg (arg 5) */ flog_warn( EC_BGP_ATTRIBUTE_TOO_SMALL, "%s: error BGP attribute length %lu is smaller than min len", peer->host, (unsigned long)(endp - stream_pnt(BGP_INPUT(peer)))); bgp_notify_send(peer, BGP_NOTIFY_UPDATE_ERR, BGP_NOTIFY_UPDATE_ATTR_LENG_ERR); return BGP_ATTR_PARSE_ERROR; } /* Fetch attribute flag and type. */ startp = BGP_INPUT_PNT(peer); /* "The lower-order four bits of the Attribute Flags octet are unused. They MUST be zero when sent and MUST be ignored when received." */ flag = 0xF0 & stream_getc(BGP_INPUT(peer)); type = stream_getc(BGP_INPUT(peer)); /* Check whether Extended-Length applies and is in bounds */ if (CHECK_FLAG(flag, BGP_ATTR_FLAG_EXTLEN) && ((endp - startp) < (BGP_ATTR_MIN_LEN + 1))) { flog_warn( EC_BGP_EXT_ATTRIBUTE_TOO_SMALL, "%s: Extended length set, but just %lu bytes of attr header", peer->host, (unsigned long)(endp - stream_pnt(BGP_INPUT(peer)))); bgp_notify_send(peer, BGP_NOTIFY_UPDATE_ERR, BGP_NOTIFY_UPDATE_ATTR_LENG_ERR); return BGP_ATTR_PARSE_ERROR; } /* Check extended attribue length bit. */ if (CHECK_FLAG(flag, BGP_ATTR_FLAG_EXTLEN)) length = stream_getw(BGP_INPUT(peer)); else length = stream_getc(BGP_INPUT(peer)); /* If any attribute appears more than once in the UPDATE message, then the Error Subcode is set to Malformed Attribute List. */ if (CHECK_BITMAP(seen, type)) { flog_warn( EC_BGP_ATTRIBUTE_REPEATED, "%s: error BGP attribute type %d appears twice in a message", peer->host, type); bgp_notify_send(peer, BGP_NOTIFY_UPDATE_ERR, BGP_NOTIFY_UPDATE_MAL_ATTR); return BGP_ATTR_PARSE_ERROR; } /* Set type to bitmap to check duplicate attribute. `type' is unsigned char so it never overflow bitmap range. */ SET_BITMAP(seen, type); /* Overflow check. */ attr_endp = BGP_INPUT_PNT(peer) + length; if (attr_endp > endp) { flog_warn( EC_BGP_ATTRIBUTE_TOO_LARGE, "%s: BGP type %d length %d is too large, attribute total length is %d. attr_endp is %p. endp is %p", peer->host, type, length, size, attr_endp, endp); /* * RFC 4271 6.3 * If any recognized attribute has an Attribute * Length that conflicts with the expected length * (based on the attribute type code), then the * Error Subcode MUST be set to Attribute Length * Error. The Data field MUST contain the erroneous * attribute (type, length, and value). * ---------- * We do not currently have a good way to determine the * length of the attribute independent of the length * received in the message. Instead we send the * minimum between the amount of data we have and the * amount specified by the attribute length field. * * Instead of directly passing in the packet buffer and * offset we use the stream_get* functions to read into * a stack buffer, since they perform bounds checking * and we are working with untrusted data. */ unsigned char ndata[BGP_MAX_PACKET_SIZE]; memset(ndata, 0x00, sizeof(ndata)); size_t lfl = CHECK_FLAG(flag, BGP_ATTR_FLAG_EXTLEN) ? 2 : 1; /* Rewind to end of flag field */ stream_forward_getp(BGP_INPUT(peer), -(1 + lfl)); /* Type */ stream_get(&ndata[0], BGP_INPUT(peer), 1); /* Length */ stream_get(&ndata[1], BGP_INPUT(peer), lfl); /* Value */ size_t atl = attr_endp - startp; size_t ndl = MIN(atl, STREAM_READABLE(BGP_INPUT(peer))); stream_get(&ndata[lfl + 1], BGP_INPUT(peer), ndl); bgp_notify_send_with_data( peer, BGP_NOTIFY_UPDATE_ERR, BGP_NOTIFY_UPDATE_ATTR_LENG_ERR, ndata, ndl + lfl + 1); return BGP_ATTR_PARSE_ERROR; } struct bgp_attr_parser_args attr_args = { .peer = peer, .length = length, .attr = attr, .type = type, .flags = flag, .startp = startp, .total = attr_endp - startp, }; /* If any recognized attribute has Attribute Flags that conflict with the Attribute Type Code, then the Error Subcode is set to Attribute Flags Error. The Data field contains the erroneous attribute (type, length and value). */ if (bgp_attr_flag_invalid(&attr_args)) { ret = bgp_attr_malformed( &attr_args, BGP_NOTIFY_UPDATE_ATTR_FLAG_ERR, attr_args.total); if (ret == BGP_ATTR_PARSE_PROCEED) continue; return ret; } /* OK check attribute and store it's value. */ switch (type) { case BGP_ATTR_ORIGIN: ret = bgp_attr_origin(&attr_args); break; case BGP_ATTR_AS_PATH: ret = bgp_attr_aspath(&attr_args); break; case BGP_ATTR_AS4_PATH: ret = bgp_attr_as4_path(&attr_args, &as4_path); break; case BGP_ATTR_NEXT_HOP: ret = bgp_attr_nexthop(&attr_args); break; case BGP_ATTR_MULTI_EXIT_DISC: ret = bgp_attr_med(&attr_args); break; case BGP_ATTR_LOCAL_PREF: ret = bgp_attr_local_pref(&attr_args); break; case BGP_ATTR_ATOMIC_AGGREGATE: ret = bgp_attr_atomic(&attr_args); break; case BGP_ATTR_AGGREGATOR: ret = bgp_attr_aggregator(&attr_args); break; case BGP_ATTR_AS4_AGGREGATOR: ret = bgp_attr_as4_aggregator(&attr_args, &as4_aggregator, &as4_aggregator_addr); break; case BGP_ATTR_COMMUNITIES: ret = bgp_attr_community(&attr_args); break; case BGP_ATTR_LARGE_COMMUNITIES: ret = bgp_attr_large_community(&attr_args); break; case BGP_ATTR_ORIGINATOR_ID: ret = bgp_attr_originator_id(&attr_args); break; case BGP_ATTR_CLUSTER_LIST: ret = bgp_attr_cluster_list(&attr_args); break; case BGP_ATTR_MP_REACH_NLRI: ret = bgp_mp_reach_parse(&attr_args, mp_update); break; case BGP_ATTR_MP_UNREACH_NLRI: ret = bgp_mp_unreach_parse(&attr_args, mp_withdraw); break; case BGP_ATTR_EXT_COMMUNITIES: ret = bgp_attr_ext_communities(&attr_args); break; #if ENABLE_BGP_VNC_ATTR case BGP_ATTR_VNC: #endif case BGP_ATTR_ENCAP: ret = bgp_attr_encap(type, peer, length, attr, flag, startp); break; case BGP_ATTR_PREFIX_SID: ret = bgp_attr_prefix_sid(length, &attr_args, mp_update); break; case BGP_ATTR_PMSI_TUNNEL: ret = bgp_attr_pmsi_tunnel(&attr_args); break; default: ret = bgp_attr_unknown(&attr_args); break; } if (ret == BGP_ATTR_PARSE_ERROR_NOTIFYPLS) { bgp_notify_send(peer, BGP_NOTIFY_UPDATE_ERR, BGP_NOTIFY_UPDATE_MAL_ATTR); ret = BGP_ATTR_PARSE_ERROR; } if (ret == BGP_ATTR_PARSE_EOR) { if (as4_path) aspath_unintern(&as4_path); return ret; } /* If hard error occurred immediately return to the caller. */ if (ret == BGP_ATTR_PARSE_ERROR) { flog_warn(EC_BGP_ATTRIBUTE_PARSE_ERROR, "%s: Attribute %s, parse error", peer->host, lookup_msg(attr_str, type, NULL)); if (as4_path) aspath_unintern(&as4_path); return ret; } if (ret == BGP_ATTR_PARSE_WITHDRAW) { flog_warn( EC_BGP_ATTRIBUTE_PARSE_WITHDRAW, "%s: Attribute %s, parse error - treating as withdrawal", peer->host, lookup_msg(attr_str, type, NULL)); if (as4_path) aspath_unintern(&as4_path); return ret; } /* Check the fetched length. */ if (BGP_INPUT_PNT(peer) != attr_endp) { flog_warn(EC_BGP_ATTRIBUTE_FETCH_ERROR, "%s: BGP attribute %s, fetch error", peer->host, lookup_msg(attr_str, type, NULL)); bgp_notify_send(peer, BGP_NOTIFY_UPDATE_ERR, BGP_NOTIFY_UPDATE_ATTR_LENG_ERR); if (as4_path) aspath_unintern(&as4_path); return BGP_ATTR_PARSE_ERROR; } } /* Check final read pointer is same as end pointer. */ if (BGP_INPUT_PNT(peer) != endp) { flog_warn(EC_BGP_ATTRIBUTES_MISMATCH, "%s: BGP attribute %s, length mismatch", peer->host, lookup_msg(attr_str, type, NULL)); bgp_notify_send(peer, BGP_NOTIFY_UPDATE_ERR, BGP_NOTIFY_UPDATE_ATTR_LENG_ERR); if (as4_path) aspath_unintern(&as4_path); return BGP_ATTR_PARSE_ERROR; } /* Check all mandatory well-known attributes are present */ if ((ret = bgp_attr_check(peer, attr)) < 0) { if (as4_path) aspath_unintern(&as4_path); return ret; } /* * At this place we can see whether we got AS4_PATH and/or * AS4_AGGREGATOR from a 16Bit peer and act accordingly. * We can not do this before we've read all attributes because * the as4 handling does not say whether AS4_PATH has to be sent * after AS_PATH or not - and when AS4_AGGREGATOR will be send * in relationship to AGGREGATOR. * So, to be defensive, we are not relying on any order and read * all attributes first, including these 32bit ones, and now, * afterwards, we look what and if something is to be done for as4. * * It is possible to not have AS_PATH, e.g. GR EoR and sole * MP_UNREACH_NLRI. */ /* actually... this doesn't ever return failure currently, but * better safe than sorry */ if (CHECK_FLAG(attr->flag, ATTR_FLAG_BIT(BGP_ATTR_AS_PATH)) && bgp_attr_munge_as4_attrs(peer, attr, as4_path, as4_aggregator, &as4_aggregator_addr)) { bgp_notify_send(peer, BGP_NOTIFY_UPDATE_ERR, BGP_NOTIFY_UPDATE_MAL_ATTR); if (as4_path) aspath_unintern(&as4_path); return BGP_ATTR_PARSE_ERROR; } /* At this stage, we have done all fiddling with as4, and the * resulting info is in attr->aggregator resp. attr->aspath * so we can chuck as4_aggregator and as4_path alltogether in * order to save memory */ if (as4_path) { aspath_unintern(&as4_path); /* unintern - it is in the hash */ /* The flag that we got this is still there, but that does not * do any trouble */ } /* * The "rest" of the code does nothing with as4_aggregator. * there is no memory attached specifically which is not part * of the attr. * so ignoring just means do nothing. */ /* * Finally do the checks on the aspath we did not do yet * because we waited for a potentially synthesized aspath. */ if (attr->flag & (ATTR_FLAG_BIT(BGP_ATTR_AS_PATH))) { ret = bgp_attr_aspath_check(peer, attr); if (ret != BGP_ATTR_PARSE_PROCEED) return ret; } /* Finally intern unknown attribute. */ if (attr->transit) attr->transit = transit_intern(attr->transit); if (attr->encap_subtlvs) attr->encap_subtlvs = encap_intern(attr->encap_subtlvs, ENCAP_SUBTLV_TYPE); #if ENABLE_BGP_VNC if (attr->vnc_subtlvs) attr->vnc_subtlvs = encap_intern(attr->vnc_subtlvs, VNC_SUBTLV_TYPE); #endif return BGP_ATTR_PARSE_PROCEED; } size_t bgp_packet_mpattr_start(struct stream *s, struct peer *peer, afi_t afi, safi_t safi, struct bpacket_attr_vec_arr *vecarr, struct attr *attr) { size_t sizep; iana_afi_t pkt_afi; iana_safi_t pkt_safi; afi_t nh_afi; /* Set extended bit always to encode the attribute length as 2 bytes */ stream_putc(s, BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_EXTLEN); stream_putc(s, BGP_ATTR_MP_REACH_NLRI); sizep = stream_get_endp(s); stream_putw(s, 0); /* Marker: Attribute length. */ /* Convert AFI, SAFI to values for packet. */ bgp_map_afi_safi_int2iana(afi, safi, &pkt_afi, &pkt_safi); stream_putw(s, pkt_afi); /* AFI */ stream_putc(s, pkt_safi); /* SAFI */ /* Nexthop AFI */ if (afi == AFI_IP && (safi == SAFI_UNICAST || safi == SAFI_LABELED_UNICAST)) nh_afi = peer_cap_enhe(peer, afi, safi) ? AFI_IP6 : AFI_IP; else nh_afi = BGP_NEXTHOP_AFI_FROM_NHLEN(attr->mp_nexthop_len); /* Nexthop */ bpacket_attr_vec_arr_set_vec(vecarr, BGP_ATTR_VEC_NH, s, attr); switch (nh_afi) { case AFI_IP: switch (safi) { case SAFI_UNICAST: case SAFI_MULTICAST: case SAFI_LABELED_UNICAST: stream_putc(s, 4); stream_put_ipv4(s, attr->nexthop.s_addr); break; case SAFI_MPLS_VPN: stream_putc(s, 12); stream_putl(s, 0); /* RD = 0, per RFC */ stream_putl(s, 0); stream_put(s, &attr->mp_nexthop_global_in, 4); break; case SAFI_ENCAP: case SAFI_EVPN: stream_putc(s, 4); stream_put(s, &attr->mp_nexthop_global_in, 4); break; case SAFI_FLOWSPEC: stream_putc(s, 0); /* no nexthop for flowspec */ default: break; } break; case AFI_IP6: switch (safi) { case SAFI_UNICAST: case SAFI_MULTICAST: case SAFI_LABELED_UNICAST: case SAFI_EVPN: { if (attr->mp_nexthop_len == BGP_ATTR_NHLEN_IPV6_GLOBAL_AND_LL) { stream_putc(s, BGP_ATTR_NHLEN_IPV6_GLOBAL_AND_LL); stream_put(s, &attr->mp_nexthop_global, IPV6_MAX_BYTELEN); stream_put(s, &attr->mp_nexthop_local, IPV6_MAX_BYTELEN); } else { stream_putc(s, IPV6_MAX_BYTELEN); stream_put(s, &attr->mp_nexthop_global, IPV6_MAX_BYTELEN); } } break; case SAFI_MPLS_VPN: { if (attr->mp_nexthop_len == BGP_ATTR_NHLEN_IPV6_GLOBAL) { stream_putc(s, 24); stream_putl(s, 0); /* RD = 0, per RFC */ stream_putl(s, 0); stream_put(s, &attr->mp_nexthop_global, IPV6_MAX_BYTELEN); } else if (attr->mp_nexthop_len == BGP_ATTR_NHLEN_IPV6_GLOBAL_AND_LL) { stream_putc(s, 48); stream_putl(s, 0); /* RD = 0, per RFC */ stream_putl(s, 0); stream_put(s, &attr->mp_nexthop_global, IPV6_MAX_BYTELEN); stream_putl(s, 0); /* RD = 0, per RFC */ stream_putl(s, 0); stream_put(s, &attr->mp_nexthop_local, IPV6_MAX_BYTELEN); } } break; case SAFI_ENCAP: stream_putc(s, IPV6_MAX_BYTELEN); stream_put(s, &attr->mp_nexthop_global, IPV6_MAX_BYTELEN); break; case SAFI_FLOWSPEC: stream_putc(s, 0); /* no nexthop for flowspec */ default: break; } break; default: if (safi != SAFI_FLOWSPEC) flog_err( EC_BGP_ATTR_NH_SEND_LEN, "Bad nexthop when sending to %s, AFI %u SAFI %u nhlen %d", peer->host, afi, safi, attr->mp_nexthop_len); break; } /* SNPA */ stream_putc(s, 0); return sizep; } void bgp_packet_mpattr_prefix(struct stream *s, afi_t afi, safi_t safi, struct prefix *p, struct prefix_rd *prd, mpls_label_t *label, uint32_t num_labels, int addpath_encode, uint32_t addpath_tx_id, struct attr *attr) { if (safi == SAFI_MPLS_VPN) { if (addpath_encode) stream_putl(s, addpath_tx_id); /* Label, RD, Prefix write. */ stream_putc(s, p->prefixlen + 88); stream_put(s, label, BGP_LABEL_BYTES); stream_put(s, prd->val, 8); stream_put(s, &p->u.prefix, PSIZE(p->prefixlen)); } else if (afi == AFI_L2VPN && safi == SAFI_EVPN) { /* EVPN prefix - contents depend on type */ bgp_evpn_encode_prefix(s, p, prd, label, num_labels, attr, addpath_encode, addpath_tx_id); } else if (safi == SAFI_LABELED_UNICAST) { /* Prefix write with label. */ stream_put_labeled_prefix(s, p, label); } else if (safi == SAFI_FLOWSPEC) { if (PSIZE (p->prefixlen)+2 < FLOWSPEC_NLRI_SIZELIMIT) stream_putc(s, PSIZE (p->prefixlen)+2); else stream_putw(s, (PSIZE (p->prefixlen)+2)|(0xf<<12)); stream_putc(s, 2);/* Filter type */ stream_putc(s, p->prefixlen);/* Prefix length */ stream_put(s, &p->u.prefix, PSIZE (p->prefixlen)); } else stream_put_prefix_addpath(s, p, addpath_encode, addpath_tx_id); } size_t bgp_packet_mpattr_prefix_size(afi_t afi, safi_t safi, struct prefix *p) { int size = PSIZE(p->prefixlen); if (safi == SAFI_MPLS_VPN) size += 88; else if (afi == AFI_L2VPN && safi == SAFI_EVPN) size += 232; // TODO: Maximum possible for type-2, type-3 and // type-5 return size; } /* * Encodes the tunnel encapsulation attribute, * and with ENABLE_BGP_VNC the VNC attribute which uses * almost the same TLV format */ static void bgp_packet_mpattr_tea(struct bgp *bgp, struct peer *peer, struct stream *s, struct attr *attr, uint8_t attrtype) { unsigned int attrlenfield = 0; unsigned int attrhdrlen = 0; struct bgp_attr_encap_subtlv *subtlvs; struct bgp_attr_encap_subtlv *st; const char *attrname; if (!attr || (attrtype == BGP_ATTR_ENCAP && (!attr->encap_tunneltype || attr->encap_tunneltype == BGP_ENCAP_TYPE_MPLS))) return; switch (attrtype) { case BGP_ATTR_ENCAP: attrname = "Tunnel Encap"; subtlvs = attr->encap_subtlvs; if (subtlvs == NULL) /* nothing to do */ return; /* * The tunnel encap attr has an "outer" tlv. * T = tunneltype, * L = total length of subtlvs, * V = concatenated subtlvs. */ attrlenfield = 2 + 2; /* T + L */ attrhdrlen = 1 + 1; /* subTLV T + L */ break; #if ENABLE_BGP_VNC_ATTR case BGP_ATTR_VNC: attrname = "VNC"; subtlvs = attr->vnc_subtlvs; if (subtlvs == NULL) /* nothing to do */ return; attrlenfield = 0; /* no outer T + L */ attrhdrlen = 2 + 2; /* subTLV T + L */ break; #endif default: assert(0); } /* compute attr length */ for (st = subtlvs; st; st = st->next) { attrlenfield += (attrhdrlen + st->length); } if (attrlenfield > 0xffff) { zlog_info("%s attribute is too long (length=%d), can't send it", attrname, attrlenfield); return; } if (attrlenfield > 0xff) { /* 2-octet length field */ stream_putc(s, BGP_ATTR_FLAG_TRANS | BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_EXTLEN); stream_putc(s, attrtype); stream_putw(s, attrlenfield & 0xffff); } else { /* 1-octet length field */ stream_putc(s, BGP_ATTR_FLAG_TRANS | BGP_ATTR_FLAG_OPTIONAL); stream_putc(s, attrtype); stream_putc(s, attrlenfield & 0xff); } if (attrtype == BGP_ATTR_ENCAP) { /* write outer T+L */ stream_putw(s, attr->encap_tunneltype); stream_putw(s, attrlenfield - 4); } /* write each sub-tlv */ for (st = subtlvs; st; st = st->next) { if (attrtype == BGP_ATTR_ENCAP) { stream_putc(s, st->type); stream_putc(s, st->length); #if ENABLE_BGP_VNC } else { stream_putw(s, st->type); stream_putw(s, st->length); #endif } stream_put(s, st->value, st->length); } } void bgp_packet_mpattr_end(struct stream *s, size_t sizep) { /* Set MP attribute length. Don't count the (2) bytes used to encode the attr length */ stream_putw_at(s, sizep, (stream_get_endp(s) - sizep) - 2); } /* Make attribute packet. */ bgp_size_t bgp_packet_attribute(struct bgp *bgp, struct peer *peer, struct stream *s, struct attr *attr, struct bpacket_attr_vec_arr *vecarr, struct prefix *p, afi_t afi, safi_t safi, struct peer *from, struct prefix_rd *prd, mpls_label_t *label, uint32_t num_labels, int addpath_encode, uint32_t addpath_tx_id) { size_t cp; size_t aspath_sizep; struct aspath *aspath; int send_as4_path = 0; int send_as4_aggregator = 0; int use32bit = (CHECK_FLAG(peer->cap, PEER_CAP_AS4_RCV)) ? 1 : 0; if (!bgp) bgp = peer->bgp; /* Remember current pointer. */ cp = stream_get_endp(s); if (p && !((afi == AFI_IP && safi == SAFI_UNICAST) && !peer_cap_enhe(peer, afi, safi))) { size_t mpattrlen_pos = 0; mpattrlen_pos = bgp_packet_mpattr_start(s, peer, afi, safi, vecarr, attr); bgp_packet_mpattr_prefix(s, afi, safi, p, prd, label, num_labels, addpath_encode, addpath_tx_id, attr); bgp_packet_mpattr_end(s, mpattrlen_pos); } /* Origin attribute. */ stream_putc(s, BGP_ATTR_FLAG_TRANS); stream_putc(s, BGP_ATTR_ORIGIN); stream_putc(s, 1); stream_putc(s, attr->origin); /* AS path attribute. */ /* If remote-peer is EBGP */ if (peer->sort == BGP_PEER_EBGP && (!CHECK_FLAG(peer->af_flags[afi][safi], PEER_FLAG_AS_PATH_UNCHANGED) || attr->aspath->segments == NULL) && (!CHECK_FLAG(peer->af_flags[afi][safi], PEER_FLAG_RSERVER_CLIENT))) { aspath = aspath_dup(attr->aspath); /* Even though we may not be configured for confederations we * may have * RXed an AS_PATH with AS_CONFED_SEQUENCE or AS_CONFED_SET */ aspath = aspath_delete_confed_seq(aspath); if (CHECK_FLAG(bgp->config, BGP_CONFIG_CONFEDERATION)) { /* Stuff our path CONFED_ID on the front */ aspath = aspath_add_seq(aspath, bgp->confed_id); } else { if (peer->change_local_as) { /* If replace-as is specified, we only use the change_local_as when advertising routes. */ if (!CHECK_FLAG( peer->flags, PEER_FLAG_LOCAL_AS_REPLACE_AS)) { aspath = aspath_add_seq(aspath, peer->local_as); } aspath = aspath_add_seq(aspath, peer->change_local_as); } else { aspath = aspath_add_seq(aspath, peer->local_as); } } } else if (peer->sort == BGP_PEER_CONFED) { /* A confed member, so we need to do the AS_CONFED_SEQUENCE * thing */ aspath = aspath_dup(attr->aspath); aspath = aspath_add_confed_seq(aspath, peer->local_as); } else aspath = attr->aspath; /* If peer is not AS4 capable, then: * - send the created AS_PATH out as AS4_PATH (optional, transitive), * but ensure that no AS_CONFED_SEQUENCE and AS_CONFED_SET path * segment * types are in it (i.e. exclude them if they are there) * AND do this only if there is at least one asnum > 65535 in the * path! * - send an AS_PATH out, but put 16Bit ASnums in it, not 32bit, and * change * all ASnums > 65535 to BGP_AS_TRANS */ stream_putc(s, BGP_ATTR_FLAG_TRANS | BGP_ATTR_FLAG_EXTLEN); stream_putc(s, BGP_ATTR_AS_PATH); aspath_sizep = stream_get_endp(s); stream_putw(s, 0); stream_putw_at(s, aspath_sizep, aspath_put(s, aspath, use32bit)); /* OLD session may need NEW_AS_PATH sent, if there are 4-byte ASNs * in the path */ if (!use32bit && aspath_has_as4(aspath)) send_as4_path = 1; /* we'll do this later, at the correct place */ /* Nexthop attribute. */ if (afi == AFI_IP && safi == SAFI_UNICAST && !peer_cap_enhe(peer, afi, safi)) { if (attr->flag & ATTR_FLAG_BIT(BGP_ATTR_NEXT_HOP)) { stream_putc(s, BGP_ATTR_FLAG_TRANS); stream_putc(s, BGP_ATTR_NEXT_HOP); bpacket_attr_vec_arr_set_vec(vecarr, BGP_ATTR_VEC_NH, s, attr); stream_putc(s, 4); stream_put_ipv4(s, attr->nexthop.s_addr); } else if (peer_cap_enhe(from, afi, safi)) { /* * Likely this is the case when an IPv4 prefix was * received with * Extended Next-hop capability and now being advertised * to * non-ENHE peers. * Setting the mandatory (ipv4) next-hop attribute here * to enable * implicit next-hop self with correct (ipv4 address * family). */ stream_putc(s, BGP_ATTR_FLAG_TRANS); stream_putc(s, BGP_ATTR_NEXT_HOP); bpacket_attr_vec_arr_set_vec(vecarr, BGP_ATTR_VEC_NH, s, NULL); stream_putc(s, 4); stream_put_ipv4(s, 0); } } /* MED attribute. */ if (attr->flag & ATTR_FLAG_BIT(BGP_ATTR_MULTI_EXIT_DISC) || bgp->maxmed_active) { stream_putc(s, BGP_ATTR_FLAG_OPTIONAL); stream_putc(s, BGP_ATTR_MULTI_EXIT_DISC); stream_putc(s, 4); stream_putl(s, (bgp->maxmed_active ? bgp->maxmed_value : attr->med)); } /* Local preference. */ if (peer->sort == BGP_PEER_IBGP || peer->sort == BGP_PEER_CONFED) { stream_putc(s, BGP_ATTR_FLAG_TRANS); stream_putc(s, BGP_ATTR_LOCAL_PREF); stream_putc(s, 4); stream_putl(s, attr->local_pref); } /* Atomic aggregate. */ if (attr->flag & ATTR_FLAG_BIT(BGP_ATTR_ATOMIC_AGGREGATE)) { stream_putc(s, BGP_ATTR_FLAG_TRANS); stream_putc(s, BGP_ATTR_ATOMIC_AGGREGATE); stream_putc(s, 0); } /* Aggregator. */ if (attr->flag & ATTR_FLAG_BIT(BGP_ATTR_AGGREGATOR)) { /* Common to BGP_ATTR_AGGREGATOR, regardless of ASN size */ stream_putc(s, BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_TRANS); stream_putc(s, BGP_ATTR_AGGREGATOR); if (use32bit) { /* AS4 capable peer */ stream_putc(s, 8); stream_putl(s, attr->aggregator_as); } else { /* 2-byte AS peer */ stream_putc(s, 6); /* Is ASN representable in 2-bytes? Or must AS_TRANS be * used? */ if (attr->aggregator_as > 65535) { stream_putw(s, BGP_AS_TRANS); /* we have to send AS4_AGGREGATOR, too. * we'll do that later in order to send * attributes in ascending * order. */ send_as4_aggregator = 1; } else stream_putw(s, (uint16_t)attr->aggregator_as); } stream_put_ipv4(s, attr->aggregator_addr.s_addr); } /* Community attribute. */ if (CHECK_FLAG(peer->af_flags[afi][safi], PEER_FLAG_SEND_COMMUNITY) && (attr->flag & ATTR_FLAG_BIT(BGP_ATTR_COMMUNITIES))) { if (attr->community->size * 4 > 255) { stream_putc(s, BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_TRANS | BGP_ATTR_FLAG_EXTLEN); stream_putc(s, BGP_ATTR_COMMUNITIES); stream_putw(s, attr->community->size * 4); } else { stream_putc(s, BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_TRANS); stream_putc(s, BGP_ATTR_COMMUNITIES); stream_putc(s, attr->community->size * 4); } stream_put(s, attr->community->val, attr->community->size * 4); } /* * Large Community attribute. */ if (CHECK_FLAG(peer->af_flags[afi][safi], PEER_FLAG_SEND_LARGE_COMMUNITY) && (attr->flag & ATTR_FLAG_BIT(BGP_ATTR_LARGE_COMMUNITIES))) { if (lcom_length(attr->lcommunity) > 255) { stream_putc(s, BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_TRANS | BGP_ATTR_FLAG_EXTLEN); stream_putc(s, BGP_ATTR_LARGE_COMMUNITIES); stream_putw(s, lcom_length(attr->lcommunity)); } else { stream_putc(s, BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_TRANS); stream_putc(s, BGP_ATTR_LARGE_COMMUNITIES); stream_putc(s, lcom_length(attr->lcommunity)); } stream_put(s, attr->lcommunity->val, lcom_length(attr->lcommunity)); } /* Route Reflector. */ if (peer->sort == BGP_PEER_IBGP && from && from->sort == BGP_PEER_IBGP) { /* Originator ID. */ stream_putc(s, BGP_ATTR_FLAG_OPTIONAL); stream_putc(s, BGP_ATTR_ORIGINATOR_ID); stream_putc(s, 4); if (attr->flag & ATTR_FLAG_BIT(BGP_ATTR_ORIGINATOR_ID)) stream_put_in_addr(s, &attr->originator_id); else stream_put_in_addr(s, &from->remote_id); /* Cluster list. */ stream_putc(s, BGP_ATTR_FLAG_OPTIONAL); stream_putc(s, BGP_ATTR_CLUSTER_LIST); if (attr->cluster) { stream_putc(s, attr->cluster->length + 4); /* If this peer configuration's parent BGP has * cluster_id. */ if (bgp->config & BGP_CONFIG_CLUSTER_ID) stream_put_in_addr(s, &bgp->cluster_id); else stream_put_in_addr(s, &bgp->router_id); stream_put(s, attr->cluster->list, attr->cluster->length); } else { stream_putc(s, 4); /* If this peer configuration's parent BGP has * cluster_id. */ if (bgp->config & BGP_CONFIG_CLUSTER_ID) stream_put_in_addr(s, &bgp->cluster_id); else stream_put_in_addr(s, &bgp->router_id); } } /* Extended Communities attribute. */ if (CHECK_FLAG(peer->af_flags[afi][safi], PEER_FLAG_SEND_EXT_COMMUNITY) && (attr->flag & ATTR_FLAG_BIT(BGP_ATTR_EXT_COMMUNITIES))) { if (peer->sort == BGP_PEER_IBGP || peer->sort == BGP_PEER_CONFED) { if (attr->ecommunity->size * 8 > 255) { stream_putc(s, BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_TRANS | BGP_ATTR_FLAG_EXTLEN); stream_putc(s, BGP_ATTR_EXT_COMMUNITIES); stream_putw(s, attr->ecommunity->size * 8); } else { stream_putc(s, BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_TRANS); stream_putc(s, BGP_ATTR_EXT_COMMUNITIES); stream_putc(s, attr->ecommunity->size * 8); } stream_put(s, attr->ecommunity->val, attr->ecommunity->size * 8); } else { uint8_t *pnt; int tbit; int ecom_tr_size = 0; int i; for (i = 0; i < attr->ecommunity->size; i++) { pnt = attr->ecommunity->val + (i * 8); tbit = *pnt; if (CHECK_FLAG(tbit, ECOMMUNITY_FLAG_NON_TRANSITIVE)) continue; ecom_tr_size++; } if (ecom_tr_size) { if (ecom_tr_size * 8 > 255) { stream_putc( s, BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_TRANS | BGP_ATTR_FLAG_EXTLEN); stream_putc(s, BGP_ATTR_EXT_COMMUNITIES); stream_putw(s, ecom_tr_size * 8); } else { stream_putc( s, BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_TRANS); stream_putc(s, BGP_ATTR_EXT_COMMUNITIES); stream_putc(s, ecom_tr_size * 8); } for (i = 0; i < attr->ecommunity->size; i++) { pnt = attr->ecommunity->val + (i * 8); tbit = *pnt; if (CHECK_FLAG( tbit, ECOMMUNITY_FLAG_NON_TRANSITIVE)) continue; stream_put(s, pnt, 8); } } } } /* Label index attribute. */ if (safi == SAFI_LABELED_UNICAST) { if (attr->flag & ATTR_FLAG_BIT(BGP_ATTR_PREFIX_SID)) { uint32_t label_index; label_index = attr->label_index; if (label_index != BGP_INVALID_LABEL_INDEX) { stream_putc(s, BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_TRANS); stream_putc(s, BGP_ATTR_PREFIX_SID); stream_putc(s, 10); stream_putc(s, BGP_PREFIX_SID_LABEL_INDEX); stream_putw(s, BGP_PREFIX_SID_LABEL_INDEX_LENGTH); stream_putc(s, 0); // reserved stream_putw(s, 0); // flags stream_putl(s, label_index); } } } if (send_as4_path) { /* If the peer is NOT As4 capable, AND */ /* there are ASnums > 65535 in path THEN * give out AS4_PATH */ /* Get rid of all AS_CONFED_SEQUENCE and AS_CONFED_SET * path segments! * Hm, I wonder... confederation things *should* only be at * the beginning of an aspath, right? Then we should use * aspath_delete_confed_seq for this, because it is already * there! (JK) * Folks, talk to me: what is reasonable here!? */ aspath = aspath_delete_confed_seq(aspath); stream_putc(s, BGP_ATTR_FLAG_TRANS | BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_EXTLEN); stream_putc(s, BGP_ATTR_AS4_PATH); aspath_sizep = stream_get_endp(s); stream_putw(s, 0); stream_putw_at(s, aspath_sizep, aspath_put(s, aspath, 1)); } if (aspath != attr->aspath) aspath_free(aspath); if (send_as4_aggregator) { /* send AS4_AGGREGATOR, at this place */ /* this section of code moved here in order to ensure the * correct * *ascending* order of attributes */ stream_putc(s, BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_TRANS); stream_putc(s, BGP_ATTR_AS4_AGGREGATOR); stream_putc(s, 8); stream_putl(s, attr->aggregator_as); stream_put_ipv4(s, attr->aggregator_addr.s_addr); } if (((afi == AFI_IP || afi == AFI_IP6) && (safi == SAFI_ENCAP || safi == SAFI_MPLS_VPN)) || (afi == AFI_L2VPN && safi == SAFI_EVPN)) { /* Tunnel Encap attribute */ bgp_packet_mpattr_tea(bgp, peer, s, attr, BGP_ATTR_ENCAP); #if ENABLE_BGP_VNC_ATTR /* VNC attribute */ bgp_packet_mpattr_tea(bgp, peer, s, attr, BGP_ATTR_VNC); #endif } /* PMSI Tunnel */ if (attr->flag & ATTR_FLAG_BIT(BGP_ATTR_PMSI_TUNNEL)) { stream_putc(s, BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_TRANS); stream_putc(s, BGP_ATTR_PMSI_TUNNEL); stream_putc(s, 9); // Length stream_putc(s, 0); // Flags stream_putc(s, PMSI_TNLTYPE_INGR_REPL); // IR (6) stream_put(s, &(attr->label), BGP_LABEL_BYTES); // MPLS Label / VXLAN VNI stream_put_ipv4(s, attr->nexthop.s_addr); // Unicast tunnel endpoint IP address } /* Unknown transit attribute. */ if (attr->transit) stream_put(s, attr->transit->val, attr->transit->length); /* Return total size of attribute. */ return stream_get_endp(s) - cp; } size_t bgp_packet_mpunreach_start(struct stream *s, afi_t afi, safi_t safi) { unsigned long attrlen_pnt; iana_afi_t pkt_afi; iana_safi_t pkt_safi; /* Set extended bit always to encode the attribute length as 2 bytes */ stream_putc(s, BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_EXTLEN); stream_putc(s, BGP_ATTR_MP_UNREACH_NLRI); attrlen_pnt = stream_get_endp(s); stream_putw(s, 0); /* Length of this attribute. */ /* Convert AFI, SAFI to values for packet. */ bgp_map_afi_safi_int2iana(afi, safi, &pkt_afi, &pkt_safi); stream_putw(s, pkt_afi); stream_putc(s, pkt_safi); return attrlen_pnt; } void bgp_packet_mpunreach_prefix(struct stream *s, struct prefix *p, afi_t afi, safi_t safi, struct prefix_rd *prd, mpls_label_t *label, uint32_t num_labels, int addpath_encode, uint32_t addpath_tx_id, struct attr *attr) { uint8_t wlabel[3] = {0x80, 0x00, 0x00}; if (safi == SAFI_LABELED_UNICAST) { label = (mpls_label_t *)wlabel; num_labels = 1; } bgp_packet_mpattr_prefix(s, afi, safi, p, prd, label, num_labels, addpath_encode, addpath_tx_id, attr); } void bgp_packet_mpunreach_end(struct stream *s, size_t attrlen_pnt) { bgp_packet_mpattr_end(s, attrlen_pnt); } /* Initialization of attribute. */ void bgp_attr_init(void) { aspath_init(); attrhash_init(); community_init(); ecommunity_init(); lcommunity_init(); cluster_init(); transit_init(); encap_init(); } void bgp_attr_finish(void) { aspath_finish(); attrhash_finish(); community_finish(); ecommunity_finish(); lcommunity_finish(); cluster_finish(); transit_finish(); encap_finish(); } /* Make attribute packet. */ void bgp_dump_routes_attr(struct stream *s, struct attr *attr, struct prefix *prefix) { unsigned long cp; unsigned long len; size_t aspath_lenp; struct aspath *aspath; int addpath_encode = 0; uint32_t addpath_tx_id = 0; /* Remember current pointer. */ cp = stream_get_endp(s); /* Place holder of length. */ stream_putw(s, 0); /* Origin attribute. */ stream_putc(s, BGP_ATTR_FLAG_TRANS); stream_putc(s, BGP_ATTR_ORIGIN); stream_putc(s, 1); stream_putc(s, attr->origin); aspath = attr->aspath; stream_putc(s, BGP_ATTR_FLAG_TRANS | BGP_ATTR_FLAG_EXTLEN); stream_putc(s, BGP_ATTR_AS_PATH); aspath_lenp = stream_get_endp(s); stream_putw(s, 0); stream_putw_at(s, aspath_lenp, aspath_put(s, aspath, 1)); /* Nexthop attribute. */ /* If it's an IPv6 prefix, don't dump the IPv4 nexthop to save space */ if (prefix != NULL && prefix->family != AF_INET6) { stream_putc(s, BGP_ATTR_FLAG_TRANS); stream_putc(s, BGP_ATTR_NEXT_HOP); stream_putc(s, 4); stream_put_ipv4(s, attr->nexthop.s_addr); } /* MED attribute. */ if (attr->flag & ATTR_FLAG_BIT(BGP_ATTR_MULTI_EXIT_DISC)) { stream_putc(s, BGP_ATTR_FLAG_OPTIONAL); stream_putc(s, BGP_ATTR_MULTI_EXIT_DISC); stream_putc(s, 4); stream_putl(s, attr->med); } /* Local preference. */ if (attr->flag & ATTR_FLAG_BIT(BGP_ATTR_LOCAL_PREF)) { stream_putc(s, BGP_ATTR_FLAG_TRANS); stream_putc(s, BGP_ATTR_LOCAL_PREF); stream_putc(s, 4); stream_putl(s, attr->local_pref); } /* Atomic aggregate. */ if (attr->flag & ATTR_FLAG_BIT(BGP_ATTR_ATOMIC_AGGREGATE)) { stream_putc(s, BGP_ATTR_FLAG_TRANS); stream_putc(s, BGP_ATTR_ATOMIC_AGGREGATE); stream_putc(s, 0); } /* Aggregator. */ if (attr->flag & ATTR_FLAG_BIT(BGP_ATTR_AGGREGATOR)) { stream_putc(s, BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_TRANS); stream_putc(s, BGP_ATTR_AGGREGATOR); stream_putc(s, 8); stream_putl(s, attr->aggregator_as); stream_put_ipv4(s, attr->aggregator_addr.s_addr); } /* Community attribute. */ if (attr->flag & ATTR_FLAG_BIT(BGP_ATTR_COMMUNITIES)) { if (attr->community->size * 4 > 255) { stream_putc(s, BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_TRANS | BGP_ATTR_FLAG_EXTLEN); stream_putc(s, BGP_ATTR_COMMUNITIES); stream_putw(s, attr->community->size * 4); } else { stream_putc(s, BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_TRANS); stream_putc(s, BGP_ATTR_COMMUNITIES); stream_putc(s, attr->community->size * 4); } stream_put(s, attr->community->val, attr->community->size * 4); } /* Large Community attribute. */ if (attr->flag & ATTR_FLAG_BIT(BGP_ATTR_LARGE_COMMUNITIES)) { if (lcom_length(attr->lcommunity) > 255) { stream_putc(s, BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_TRANS | BGP_ATTR_FLAG_EXTLEN); stream_putc(s, BGP_ATTR_LARGE_COMMUNITIES); stream_putw(s, lcom_length(attr->lcommunity)); } else { stream_putc(s, BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_TRANS); stream_putc(s, BGP_ATTR_LARGE_COMMUNITIES); stream_putc(s, lcom_length(attr->lcommunity)); } stream_put(s, attr->lcommunity->val, lcom_length(attr->lcommunity)); } /* Add a MP_NLRI attribute to dump the IPv6 next hop */ if (prefix != NULL && prefix->family == AF_INET6 && (attr->mp_nexthop_len == BGP_ATTR_NHLEN_IPV6_GLOBAL || attr->mp_nexthop_len == BGP_ATTR_NHLEN_IPV6_GLOBAL_AND_LL)) { int sizep; stream_putc(s, BGP_ATTR_FLAG_OPTIONAL); stream_putc(s, BGP_ATTR_MP_REACH_NLRI); sizep = stream_get_endp(s); /* MP header */ stream_putc(s, 0); /* Marker: Attribute length. */ stream_putw(s, AFI_IP6); /* AFI */ stream_putc(s, SAFI_UNICAST); /* SAFI */ /* Next hop */ stream_putc(s, attr->mp_nexthop_len); stream_put(s, &attr->mp_nexthop_global, IPV6_MAX_BYTELEN); if (attr->mp_nexthop_len == BGP_ATTR_NHLEN_IPV6_GLOBAL_AND_LL) stream_put(s, &attr->mp_nexthop_local, IPV6_MAX_BYTELEN); /* SNPA */ stream_putc(s, 0); /* Prefix */ stream_put_prefix_addpath(s, prefix, addpath_encode, addpath_tx_id); /* Set MP attribute length. */ stream_putc_at(s, sizep, (stream_get_endp(s) - sizep) - 1); } /* Prefix SID */ if (attr->flag & ATTR_FLAG_BIT(BGP_ATTR_PREFIX_SID)) { if (attr->label_index != BGP_INVALID_LABEL_INDEX) { stream_putc(s, BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_TRANS); stream_putc(s, BGP_ATTR_PREFIX_SID); stream_putc(s, 10); stream_putc(s, BGP_PREFIX_SID_LABEL_INDEX); stream_putc(s, BGP_PREFIX_SID_LABEL_INDEX_LENGTH); stream_putc(s, 0); // reserved stream_putw(s, 0); // flags stream_putl(s, attr->label_index); } } /* Return total size of attribute. */ len = stream_get_endp(s) - cp - 2; stream_putw_at(s, cp, len); }
./CrossVul/dataset_final_sorted/CWE-20/c/good_1399_0
crossvul-cpp_data_good_5604_0
/* * linux/fs/ext3/super.c * * Copyright (C) 1992, 1993, 1994, 1995 * Remy Card (card@masi.ibp.fr) * Laboratoire MASI - Institut Blaise Pascal * Universite Pierre et Marie Curie (Paris VI) * * from * * linux/fs/minix/inode.c * * Copyright (C) 1991, 1992 Linus Torvalds * * Big-endian to little-endian byte-swapping/bitmaps by * David S. Miller (davem@caip.rutgers.edu), 1995 */ #include <linux/module.h> #include <linux/blkdev.h> #include <linux/parser.h> #include <linux/exportfs.h> #include <linux/statfs.h> #include <linux/random.h> #include <linux/mount.h> #include <linux/quotaops.h> #include <linux/seq_file.h> #include <linux/log2.h> #include <linux/cleancache.h> #include <asm/uaccess.h> #define CREATE_TRACE_POINTS #include "ext3.h" #include "xattr.h" #include "acl.h" #include "namei.h" #ifdef CONFIG_EXT3_DEFAULTS_TO_ORDERED #define EXT3_MOUNT_DEFAULT_DATA_MODE EXT3_MOUNT_ORDERED_DATA #else #define EXT3_MOUNT_DEFAULT_DATA_MODE EXT3_MOUNT_WRITEBACK_DATA #endif static int ext3_load_journal(struct super_block *, struct ext3_super_block *, unsigned long journal_devnum); static int ext3_create_journal(struct super_block *, struct ext3_super_block *, unsigned int); static int ext3_commit_super(struct super_block *sb, struct ext3_super_block *es, int sync); static void ext3_mark_recovery_complete(struct super_block * sb, struct ext3_super_block * es); static void ext3_clear_journal_err(struct super_block * sb, struct ext3_super_block * es); static int ext3_sync_fs(struct super_block *sb, int wait); static const char *ext3_decode_error(struct super_block * sb, int errno, char nbuf[16]); static int ext3_remount (struct super_block * sb, int * flags, char * data); static int ext3_statfs (struct dentry * dentry, struct kstatfs * buf); static int ext3_unfreeze(struct super_block *sb); static int ext3_freeze(struct super_block *sb); /* * Wrappers for journal_start/end. */ handle_t *ext3_journal_start_sb(struct super_block *sb, int nblocks) { journal_t *journal; if (sb->s_flags & MS_RDONLY) return ERR_PTR(-EROFS); /* Special case here: if the journal has aborted behind our * backs (eg. EIO in the commit thread), then we still need to * take the FS itself readonly cleanly. */ journal = EXT3_SB(sb)->s_journal; if (is_journal_aborted(journal)) { ext3_abort(sb, __func__, "Detected aborted journal"); return ERR_PTR(-EROFS); } return journal_start(journal, nblocks); } int __ext3_journal_stop(const char *where, handle_t *handle) { struct super_block *sb; int err; int rc; sb = handle->h_transaction->t_journal->j_private; err = handle->h_err; rc = journal_stop(handle); if (!err) err = rc; if (err) __ext3_std_error(sb, where, err); return err; } void ext3_journal_abort_handle(const char *caller, const char *err_fn, struct buffer_head *bh, handle_t *handle, int err) { char nbuf[16]; const char *errstr = ext3_decode_error(NULL, err, nbuf); if (bh) BUFFER_TRACE(bh, "abort"); if (!handle->h_err) handle->h_err = err; if (is_handle_aborted(handle)) return; printk(KERN_ERR "EXT3-fs: %s: aborting transaction: %s in %s\n", caller, errstr, err_fn); journal_abort_handle(handle); } void ext3_msg(struct super_block *sb, const char *prefix, const char *fmt, ...) { struct va_format vaf; va_list args; va_start(args, fmt); vaf.fmt = fmt; vaf.va = &args; printk("%sEXT3-fs (%s): %pV\n", prefix, sb->s_id, &vaf); va_end(args); } /* Deal with the reporting of failure conditions on a filesystem such as * inconsistencies detected or read IO failures. * * On ext2, we can store the error state of the filesystem in the * superblock. That is not possible on ext3, because we may have other * write ordering constraints on the superblock which prevent us from * writing it out straight away; and given that the journal is about to * be aborted, we can't rely on the current, or future, transactions to * write out the superblock safely. * * We'll just use the journal_abort() error code to record an error in * the journal instead. On recovery, the journal will complain about * that error until we've noted it down and cleared it. */ static void ext3_handle_error(struct super_block *sb) { struct ext3_super_block *es = EXT3_SB(sb)->s_es; EXT3_SB(sb)->s_mount_state |= EXT3_ERROR_FS; es->s_state |= cpu_to_le16(EXT3_ERROR_FS); if (sb->s_flags & MS_RDONLY) return; if (!test_opt (sb, ERRORS_CONT)) { journal_t *journal = EXT3_SB(sb)->s_journal; set_opt(EXT3_SB(sb)->s_mount_opt, ABORT); if (journal) journal_abort(journal, -EIO); } if (test_opt (sb, ERRORS_RO)) { ext3_msg(sb, KERN_CRIT, "error: remounting filesystem read-only"); sb->s_flags |= MS_RDONLY; } ext3_commit_super(sb, es, 1); if (test_opt(sb, ERRORS_PANIC)) panic("EXT3-fs (%s): panic forced after error\n", sb->s_id); } void ext3_error(struct super_block *sb, const char *function, const char *fmt, ...) { struct va_format vaf; va_list args; va_start(args, fmt); vaf.fmt = fmt; vaf.va = &args; printk(KERN_CRIT "EXT3-fs error (device %s): %s: %pV\n", sb->s_id, function, &vaf); va_end(args); ext3_handle_error(sb); } static const char *ext3_decode_error(struct super_block * sb, int errno, char nbuf[16]) { char *errstr = NULL; switch (errno) { case -EIO: errstr = "IO failure"; break; case -ENOMEM: errstr = "Out of memory"; break; case -EROFS: if (!sb || EXT3_SB(sb)->s_journal->j_flags & JFS_ABORT) errstr = "Journal has aborted"; else errstr = "Readonly filesystem"; break; default: /* If the caller passed in an extra buffer for unknown * errors, textualise them now. Else we just return * NULL. */ if (nbuf) { /* Check for truncated error codes... */ if (snprintf(nbuf, 16, "error %d", -errno) >= 0) errstr = nbuf; } break; } return errstr; } /* __ext3_std_error decodes expected errors from journaling functions * automatically and invokes the appropriate error response. */ void __ext3_std_error (struct super_block * sb, const char * function, int errno) { char nbuf[16]; const char *errstr; /* Special case: if the error is EROFS, and we're not already * inside a transaction, then there's really no point in logging * an error. */ if (errno == -EROFS && journal_current_handle() == NULL && (sb->s_flags & MS_RDONLY)) return; errstr = ext3_decode_error(sb, errno, nbuf); ext3_msg(sb, KERN_CRIT, "error in %s: %s", function, errstr); ext3_handle_error(sb); } /* * ext3_abort is a much stronger failure handler than ext3_error. The * abort function may be used to deal with unrecoverable failures such * as journal IO errors or ENOMEM at a critical moment in log management. * * We unconditionally force the filesystem into an ABORT|READONLY state, * unless the error response on the fs has been set to panic in which * case we take the easy way out and panic immediately. */ void ext3_abort(struct super_block *sb, const char *function, const char *fmt, ...) { struct va_format vaf; va_list args; va_start(args, fmt); vaf.fmt = fmt; vaf.va = &args; printk(KERN_CRIT "EXT3-fs (%s): error: %s: %pV\n", sb->s_id, function, &vaf); va_end(args); if (test_opt(sb, ERRORS_PANIC)) panic("EXT3-fs: panic from previous error\n"); if (sb->s_flags & MS_RDONLY) return; ext3_msg(sb, KERN_CRIT, "error: remounting filesystem read-only"); EXT3_SB(sb)->s_mount_state |= EXT3_ERROR_FS; sb->s_flags |= MS_RDONLY; set_opt(EXT3_SB(sb)->s_mount_opt, ABORT); if (EXT3_SB(sb)->s_journal) journal_abort(EXT3_SB(sb)->s_journal, -EIO); } void ext3_warning(struct super_block *sb, const char *function, const char *fmt, ...) { struct va_format vaf; va_list args; va_start(args, fmt); vaf.fmt = fmt; vaf.va = &args; printk(KERN_WARNING "EXT3-fs (%s): warning: %s: %pV\n", sb->s_id, function, &vaf); va_end(args); } void ext3_update_dynamic_rev(struct super_block *sb) { struct ext3_super_block *es = EXT3_SB(sb)->s_es; if (le32_to_cpu(es->s_rev_level) > EXT3_GOOD_OLD_REV) return; ext3_msg(sb, KERN_WARNING, "warning: updating to rev %d because of " "new feature flag, running e2fsck is recommended", EXT3_DYNAMIC_REV); es->s_first_ino = cpu_to_le32(EXT3_GOOD_OLD_FIRST_INO); es->s_inode_size = cpu_to_le16(EXT3_GOOD_OLD_INODE_SIZE); es->s_rev_level = cpu_to_le32(EXT3_DYNAMIC_REV); /* leave es->s_feature_*compat flags alone */ /* es->s_uuid will be set by e2fsck if empty */ /* * The rest of the superblock fields should be zero, and if not it * means they are likely already in use, so leave them alone. We * can leave it up to e2fsck to clean up any inconsistencies there. */ } /* * Open the external journal device */ static struct block_device *ext3_blkdev_get(dev_t dev, struct super_block *sb) { struct block_device *bdev; char b[BDEVNAME_SIZE]; bdev = blkdev_get_by_dev(dev, FMODE_READ|FMODE_WRITE|FMODE_EXCL, sb); if (IS_ERR(bdev)) goto fail; return bdev; fail: ext3_msg(sb, KERN_ERR, "error: failed to open journal device %s: %ld", __bdevname(dev, b), PTR_ERR(bdev)); return NULL; } /* * Release the journal device */ static int ext3_blkdev_put(struct block_device *bdev) { return blkdev_put(bdev, FMODE_READ|FMODE_WRITE|FMODE_EXCL); } static int ext3_blkdev_remove(struct ext3_sb_info *sbi) { struct block_device *bdev; int ret = -ENODEV; bdev = sbi->journal_bdev; if (bdev) { ret = ext3_blkdev_put(bdev); sbi->journal_bdev = NULL; } return ret; } static inline struct inode *orphan_list_entry(struct list_head *l) { return &list_entry(l, struct ext3_inode_info, i_orphan)->vfs_inode; } static void dump_orphan_list(struct super_block *sb, struct ext3_sb_info *sbi) { struct list_head *l; ext3_msg(sb, KERN_ERR, "error: sb orphan head is %d", le32_to_cpu(sbi->s_es->s_last_orphan)); ext3_msg(sb, KERN_ERR, "sb_info orphan list:"); list_for_each(l, &sbi->s_orphan) { struct inode *inode = orphan_list_entry(l); ext3_msg(sb, KERN_ERR, " " "inode %s:%lu at %p: mode %o, nlink %d, next %d\n", inode->i_sb->s_id, inode->i_ino, inode, inode->i_mode, inode->i_nlink, NEXT_ORPHAN(inode)); } } static void ext3_put_super (struct super_block * sb) { struct ext3_sb_info *sbi = EXT3_SB(sb); struct ext3_super_block *es = sbi->s_es; int i, err; dquot_disable(sb, -1, DQUOT_USAGE_ENABLED | DQUOT_LIMITS_ENABLED); ext3_xattr_put_super(sb); err = journal_destroy(sbi->s_journal); sbi->s_journal = NULL; if (err < 0) ext3_abort(sb, __func__, "Couldn't clean up the journal"); if (!(sb->s_flags & MS_RDONLY)) { EXT3_CLEAR_INCOMPAT_FEATURE(sb, EXT3_FEATURE_INCOMPAT_RECOVER); es->s_state = cpu_to_le16(sbi->s_mount_state); BUFFER_TRACE(sbi->s_sbh, "marking dirty"); mark_buffer_dirty(sbi->s_sbh); ext3_commit_super(sb, es, 1); } for (i = 0; i < sbi->s_gdb_count; i++) brelse(sbi->s_group_desc[i]); kfree(sbi->s_group_desc); percpu_counter_destroy(&sbi->s_freeblocks_counter); percpu_counter_destroy(&sbi->s_freeinodes_counter); percpu_counter_destroy(&sbi->s_dirs_counter); brelse(sbi->s_sbh); #ifdef CONFIG_QUOTA for (i = 0; i < MAXQUOTAS; i++) kfree(sbi->s_qf_names[i]); #endif /* Debugging code just in case the in-memory inode orphan list * isn't empty. The on-disk one can be non-empty if we've * detected an error and taken the fs readonly, but the * in-memory list had better be clean by this point. */ if (!list_empty(&sbi->s_orphan)) dump_orphan_list(sb, sbi); J_ASSERT(list_empty(&sbi->s_orphan)); invalidate_bdev(sb->s_bdev); if (sbi->journal_bdev && sbi->journal_bdev != sb->s_bdev) { /* * Invalidate the journal device's buffers. We don't want them * floating about in memory - the physical journal device may * hotswapped, and it breaks the `ro-after' testing code. */ sync_blockdev(sbi->journal_bdev); invalidate_bdev(sbi->journal_bdev); ext3_blkdev_remove(sbi); } sb->s_fs_info = NULL; kfree(sbi->s_blockgroup_lock); kfree(sbi); } static struct kmem_cache *ext3_inode_cachep; /* * Called inside transaction, so use GFP_NOFS */ static struct inode *ext3_alloc_inode(struct super_block *sb) { struct ext3_inode_info *ei; ei = kmem_cache_alloc(ext3_inode_cachep, GFP_NOFS); if (!ei) return NULL; ei->i_block_alloc_info = NULL; ei->vfs_inode.i_version = 1; atomic_set(&ei->i_datasync_tid, 0); atomic_set(&ei->i_sync_tid, 0); return &ei->vfs_inode; } static int ext3_drop_inode(struct inode *inode) { int drop = generic_drop_inode(inode); trace_ext3_drop_inode(inode, drop); return drop; } static void ext3_i_callback(struct rcu_head *head) { struct inode *inode = container_of(head, struct inode, i_rcu); kmem_cache_free(ext3_inode_cachep, EXT3_I(inode)); } static void ext3_destroy_inode(struct inode *inode) { if (!list_empty(&(EXT3_I(inode)->i_orphan))) { printk("EXT3 Inode %p: orphan list check failed!\n", EXT3_I(inode)); print_hex_dump(KERN_INFO, "", DUMP_PREFIX_ADDRESS, 16, 4, EXT3_I(inode), sizeof(struct ext3_inode_info), false); dump_stack(); } call_rcu(&inode->i_rcu, ext3_i_callback); } static void init_once(void *foo) { struct ext3_inode_info *ei = (struct ext3_inode_info *) foo; INIT_LIST_HEAD(&ei->i_orphan); #ifdef CONFIG_EXT3_FS_XATTR init_rwsem(&ei->xattr_sem); #endif mutex_init(&ei->truncate_mutex); inode_init_once(&ei->vfs_inode); } static int init_inodecache(void) { ext3_inode_cachep = kmem_cache_create("ext3_inode_cache", sizeof(struct ext3_inode_info), 0, (SLAB_RECLAIM_ACCOUNT| SLAB_MEM_SPREAD), init_once); if (ext3_inode_cachep == NULL) return -ENOMEM; return 0; } static void destroy_inodecache(void) { /* * Make sure all delayed rcu free inodes are flushed before we * destroy cache. */ rcu_barrier(); kmem_cache_destroy(ext3_inode_cachep); } static inline void ext3_show_quota_options(struct seq_file *seq, struct super_block *sb) { #if defined(CONFIG_QUOTA) struct ext3_sb_info *sbi = EXT3_SB(sb); if (sbi->s_jquota_fmt) { char *fmtname = ""; switch (sbi->s_jquota_fmt) { case QFMT_VFS_OLD: fmtname = "vfsold"; break; case QFMT_VFS_V0: fmtname = "vfsv0"; break; case QFMT_VFS_V1: fmtname = "vfsv1"; break; } seq_printf(seq, ",jqfmt=%s", fmtname); } if (sbi->s_qf_names[USRQUOTA]) seq_printf(seq, ",usrjquota=%s", sbi->s_qf_names[USRQUOTA]); if (sbi->s_qf_names[GRPQUOTA]) seq_printf(seq, ",grpjquota=%s", sbi->s_qf_names[GRPQUOTA]); if (test_opt(sb, USRQUOTA)) seq_puts(seq, ",usrquota"); if (test_opt(sb, GRPQUOTA)) seq_puts(seq, ",grpquota"); #endif } static char *data_mode_string(unsigned long mode) { switch (mode) { case EXT3_MOUNT_JOURNAL_DATA: return "journal"; case EXT3_MOUNT_ORDERED_DATA: return "ordered"; case EXT3_MOUNT_WRITEBACK_DATA: return "writeback"; } return "unknown"; } /* * Show an option if * - it's set to a non-default value OR * - if the per-sb default is different from the global default */ static int ext3_show_options(struct seq_file *seq, struct dentry *root) { struct super_block *sb = root->d_sb; struct ext3_sb_info *sbi = EXT3_SB(sb); struct ext3_super_block *es = sbi->s_es; unsigned long def_mount_opts; def_mount_opts = le32_to_cpu(es->s_default_mount_opts); if (sbi->s_sb_block != 1) seq_printf(seq, ",sb=%lu", sbi->s_sb_block); if (test_opt(sb, MINIX_DF)) seq_puts(seq, ",minixdf"); if (test_opt(sb, GRPID)) seq_puts(seq, ",grpid"); if (!test_opt(sb, GRPID) && (def_mount_opts & EXT3_DEFM_BSDGROUPS)) seq_puts(seq, ",nogrpid"); if (!uid_eq(sbi->s_resuid, make_kuid(&init_user_ns, EXT3_DEF_RESUID)) || le16_to_cpu(es->s_def_resuid) != EXT3_DEF_RESUID) { seq_printf(seq, ",resuid=%u", from_kuid_munged(&init_user_ns, sbi->s_resuid)); } if (!gid_eq(sbi->s_resgid, make_kgid(&init_user_ns, EXT3_DEF_RESGID)) || le16_to_cpu(es->s_def_resgid) != EXT3_DEF_RESGID) { seq_printf(seq, ",resgid=%u", from_kgid_munged(&init_user_ns, sbi->s_resgid)); } if (test_opt(sb, ERRORS_RO)) { int def_errors = le16_to_cpu(es->s_errors); if (def_errors == EXT3_ERRORS_PANIC || def_errors == EXT3_ERRORS_CONTINUE) { seq_puts(seq, ",errors=remount-ro"); } } if (test_opt(sb, ERRORS_CONT)) seq_puts(seq, ",errors=continue"); if (test_opt(sb, ERRORS_PANIC)) seq_puts(seq, ",errors=panic"); if (test_opt(sb, NO_UID32)) seq_puts(seq, ",nouid32"); if (test_opt(sb, DEBUG)) seq_puts(seq, ",debug"); #ifdef CONFIG_EXT3_FS_XATTR if (test_opt(sb, XATTR_USER)) seq_puts(seq, ",user_xattr"); if (!test_opt(sb, XATTR_USER) && (def_mount_opts & EXT3_DEFM_XATTR_USER)) { seq_puts(seq, ",nouser_xattr"); } #endif #ifdef CONFIG_EXT3_FS_POSIX_ACL if (test_opt(sb, POSIX_ACL)) seq_puts(seq, ",acl"); if (!test_opt(sb, POSIX_ACL) && (def_mount_opts & EXT3_DEFM_ACL)) seq_puts(seq, ",noacl"); #endif if (!test_opt(sb, RESERVATION)) seq_puts(seq, ",noreservation"); if (sbi->s_commit_interval) { seq_printf(seq, ",commit=%u", (unsigned) (sbi->s_commit_interval / HZ)); } /* * Always display barrier state so it's clear what the status is. */ seq_puts(seq, ",barrier="); seq_puts(seq, test_opt(sb, BARRIER) ? "1" : "0"); seq_printf(seq, ",data=%s", data_mode_string(test_opt(sb, DATA_FLAGS))); if (test_opt(sb, DATA_ERR_ABORT)) seq_puts(seq, ",data_err=abort"); if (test_opt(sb, NOLOAD)) seq_puts(seq, ",norecovery"); ext3_show_quota_options(seq, sb); return 0; } static struct inode *ext3_nfs_get_inode(struct super_block *sb, u64 ino, u32 generation) { struct inode *inode; if (ino < EXT3_FIRST_INO(sb) && ino != EXT3_ROOT_INO) return ERR_PTR(-ESTALE); if (ino > le32_to_cpu(EXT3_SB(sb)->s_es->s_inodes_count)) return ERR_PTR(-ESTALE); /* iget isn't really right if the inode is currently unallocated!! * * ext3_read_inode will return a bad_inode if the inode had been * deleted, so we should be safe. * * Currently we don't know the generation for parent directory, so * a generation of 0 means "accept any" */ inode = ext3_iget(sb, ino); if (IS_ERR(inode)) return ERR_CAST(inode); if (generation && inode->i_generation != generation) { iput(inode); return ERR_PTR(-ESTALE); } return inode; } static struct dentry *ext3_fh_to_dentry(struct super_block *sb, struct fid *fid, int fh_len, int fh_type) { return generic_fh_to_dentry(sb, fid, fh_len, fh_type, ext3_nfs_get_inode); } static struct dentry *ext3_fh_to_parent(struct super_block *sb, struct fid *fid, int fh_len, int fh_type) { return generic_fh_to_parent(sb, fid, fh_len, fh_type, ext3_nfs_get_inode); } /* * Try to release metadata pages (indirect blocks, directories) which are * mapped via the block device. Since these pages could have journal heads * which would prevent try_to_free_buffers() from freeing them, we must use * jbd layer's try_to_free_buffers() function to release them. */ static int bdev_try_to_free_page(struct super_block *sb, struct page *page, gfp_t wait) { journal_t *journal = EXT3_SB(sb)->s_journal; WARN_ON(PageChecked(page)); if (!page_has_buffers(page)) return 0; if (journal) return journal_try_to_free_buffers(journal, page, wait & ~__GFP_WAIT); return try_to_free_buffers(page); } #ifdef CONFIG_QUOTA #define QTYPE2NAME(t) ((t)==USRQUOTA?"user":"group") #define QTYPE2MOPT(on, t) ((t)==USRQUOTA?((on)##USRJQUOTA):((on)##GRPJQUOTA)) static int ext3_write_dquot(struct dquot *dquot); static int ext3_acquire_dquot(struct dquot *dquot); static int ext3_release_dquot(struct dquot *dquot); static int ext3_mark_dquot_dirty(struct dquot *dquot); static int ext3_write_info(struct super_block *sb, int type); static int ext3_quota_on(struct super_block *sb, int type, int format_id, struct path *path); static int ext3_quota_on_mount(struct super_block *sb, int type); static ssize_t ext3_quota_read(struct super_block *sb, int type, char *data, size_t len, loff_t off); static ssize_t ext3_quota_write(struct super_block *sb, int type, const char *data, size_t len, loff_t off); static const struct dquot_operations ext3_quota_operations = { .write_dquot = ext3_write_dquot, .acquire_dquot = ext3_acquire_dquot, .release_dquot = ext3_release_dquot, .mark_dirty = ext3_mark_dquot_dirty, .write_info = ext3_write_info, .alloc_dquot = dquot_alloc, .destroy_dquot = dquot_destroy, }; static const struct quotactl_ops ext3_qctl_operations = { .quota_on = ext3_quota_on, .quota_off = dquot_quota_off, .quota_sync = dquot_quota_sync, .get_info = dquot_get_dqinfo, .set_info = dquot_set_dqinfo, .get_dqblk = dquot_get_dqblk, .set_dqblk = dquot_set_dqblk }; #endif static const struct super_operations ext3_sops = { .alloc_inode = ext3_alloc_inode, .destroy_inode = ext3_destroy_inode, .write_inode = ext3_write_inode, .dirty_inode = ext3_dirty_inode, .drop_inode = ext3_drop_inode, .evict_inode = ext3_evict_inode, .put_super = ext3_put_super, .sync_fs = ext3_sync_fs, .freeze_fs = ext3_freeze, .unfreeze_fs = ext3_unfreeze, .statfs = ext3_statfs, .remount_fs = ext3_remount, .show_options = ext3_show_options, #ifdef CONFIG_QUOTA .quota_read = ext3_quota_read, .quota_write = ext3_quota_write, #endif .bdev_try_to_free_page = bdev_try_to_free_page, }; static const struct export_operations ext3_export_ops = { .fh_to_dentry = ext3_fh_to_dentry, .fh_to_parent = ext3_fh_to_parent, .get_parent = ext3_get_parent, }; enum { Opt_bsd_df, Opt_minix_df, Opt_grpid, Opt_nogrpid, Opt_resgid, Opt_resuid, Opt_sb, Opt_err_cont, Opt_err_panic, Opt_err_ro, Opt_nouid32, Opt_nocheck, Opt_debug, Opt_oldalloc, Opt_orlov, Opt_user_xattr, Opt_nouser_xattr, Opt_acl, Opt_noacl, Opt_reservation, Opt_noreservation, Opt_noload, Opt_nobh, Opt_bh, Opt_commit, Opt_journal_update, Opt_journal_inum, Opt_journal_dev, Opt_abort, Opt_data_journal, Opt_data_ordered, Opt_data_writeback, Opt_data_err_abort, Opt_data_err_ignore, Opt_usrjquota, Opt_grpjquota, Opt_offusrjquota, Opt_offgrpjquota, Opt_jqfmt_vfsold, Opt_jqfmt_vfsv0, Opt_jqfmt_vfsv1, Opt_quota, Opt_noquota, Opt_ignore, Opt_barrier, Opt_nobarrier, Opt_err, Opt_resize, Opt_usrquota, Opt_grpquota }; static const match_table_t tokens = { {Opt_bsd_df, "bsddf"}, {Opt_minix_df, "minixdf"}, {Opt_grpid, "grpid"}, {Opt_grpid, "bsdgroups"}, {Opt_nogrpid, "nogrpid"}, {Opt_nogrpid, "sysvgroups"}, {Opt_resgid, "resgid=%u"}, {Opt_resuid, "resuid=%u"}, {Opt_sb, "sb=%u"}, {Opt_err_cont, "errors=continue"}, {Opt_err_panic, "errors=panic"}, {Opt_err_ro, "errors=remount-ro"}, {Opt_nouid32, "nouid32"}, {Opt_nocheck, "nocheck"}, {Opt_nocheck, "check=none"}, {Opt_debug, "debug"}, {Opt_oldalloc, "oldalloc"}, {Opt_orlov, "orlov"}, {Opt_user_xattr, "user_xattr"}, {Opt_nouser_xattr, "nouser_xattr"}, {Opt_acl, "acl"}, {Opt_noacl, "noacl"}, {Opt_reservation, "reservation"}, {Opt_noreservation, "noreservation"}, {Opt_noload, "noload"}, {Opt_noload, "norecovery"}, {Opt_nobh, "nobh"}, {Opt_bh, "bh"}, {Opt_commit, "commit=%u"}, {Opt_journal_update, "journal=update"}, {Opt_journal_inum, "journal=%u"}, {Opt_journal_dev, "journal_dev=%u"}, {Opt_abort, "abort"}, {Opt_data_journal, "data=journal"}, {Opt_data_ordered, "data=ordered"}, {Opt_data_writeback, "data=writeback"}, {Opt_data_err_abort, "data_err=abort"}, {Opt_data_err_ignore, "data_err=ignore"}, {Opt_offusrjquota, "usrjquota="}, {Opt_usrjquota, "usrjquota=%s"}, {Opt_offgrpjquota, "grpjquota="}, {Opt_grpjquota, "grpjquota=%s"}, {Opt_jqfmt_vfsold, "jqfmt=vfsold"}, {Opt_jqfmt_vfsv0, "jqfmt=vfsv0"}, {Opt_jqfmt_vfsv1, "jqfmt=vfsv1"}, {Opt_grpquota, "grpquota"}, {Opt_noquota, "noquota"}, {Opt_quota, "quota"}, {Opt_usrquota, "usrquota"}, {Opt_barrier, "barrier=%u"}, {Opt_barrier, "barrier"}, {Opt_nobarrier, "nobarrier"}, {Opt_resize, "resize"}, {Opt_err, NULL}, }; static ext3_fsblk_t get_sb_block(void **data, struct super_block *sb) { ext3_fsblk_t sb_block; char *options = (char *) *data; if (!options || strncmp(options, "sb=", 3) != 0) return 1; /* Default location */ options += 3; /*todo: use simple_strtoll with >32bit ext3 */ sb_block = simple_strtoul(options, &options, 0); if (*options && *options != ',') { ext3_msg(sb, KERN_ERR, "error: invalid sb specification: %s", (char *) *data); return 1; } if (*options == ',') options++; *data = (void *) options; return sb_block; } #ifdef CONFIG_QUOTA static int set_qf_name(struct super_block *sb, int qtype, substring_t *args) { struct ext3_sb_info *sbi = EXT3_SB(sb); char *qname; if (sb_any_quota_loaded(sb) && !sbi->s_qf_names[qtype]) { ext3_msg(sb, KERN_ERR, "Cannot change journaled " "quota options when quota turned on"); return 0; } qname = match_strdup(args); if (!qname) { ext3_msg(sb, KERN_ERR, "Not enough memory for storing quotafile name"); return 0; } if (sbi->s_qf_names[qtype]) { int same = !strcmp(sbi->s_qf_names[qtype], qname); kfree(qname); if (!same) { ext3_msg(sb, KERN_ERR, "%s quota file already specified", QTYPE2NAME(qtype)); } return same; } if (strchr(qname, '/')) { ext3_msg(sb, KERN_ERR, "quotafile must be on filesystem root"); kfree(qname); return 0; } sbi->s_qf_names[qtype] = qname; set_opt(sbi->s_mount_opt, QUOTA); return 1; } static int clear_qf_name(struct super_block *sb, int qtype) { struct ext3_sb_info *sbi = EXT3_SB(sb); if (sb_any_quota_loaded(sb) && sbi->s_qf_names[qtype]) { ext3_msg(sb, KERN_ERR, "Cannot change journaled quota options" " when quota turned on"); return 0; } if (sbi->s_qf_names[qtype]) { kfree(sbi->s_qf_names[qtype]); sbi->s_qf_names[qtype] = NULL; } return 1; } #endif static int parse_options (char *options, struct super_block *sb, unsigned int *inum, unsigned long *journal_devnum, ext3_fsblk_t *n_blocks_count, int is_remount) { struct ext3_sb_info *sbi = EXT3_SB(sb); char * p; substring_t args[MAX_OPT_ARGS]; int data_opt = 0; int option; kuid_t uid; kgid_t gid; #ifdef CONFIG_QUOTA int qfmt; #endif if (!options) return 1; while ((p = strsep (&options, ",")) != NULL) { int token; if (!*p) continue; /* * Initialize args struct so we know whether arg was * found; some options take optional arguments. */ args[0].to = args[0].from = NULL; token = match_token(p, tokens, args); switch (token) { case Opt_bsd_df: clear_opt (sbi->s_mount_opt, MINIX_DF); break; case Opt_minix_df: set_opt (sbi->s_mount_opt, MINIX_DF); break; case Opt_grpid: set_opt (sbi->s_mount_opt, GRPID); break; case Opt_nogrpid: clear_opt (sbi->s_mount_opt, GRPID); break; case Opt_resuid: if (match_int(&args[0], &option)) return 0; uid = make_kuid(current_user_ns(), option); if (!uid_valid(uid)) { ext3_msg(sb, KERN_ERR, "Invalid uid value %d", option); return 0; } sbi->s_resuid = uid; break; case Opt_resgid: if (match_int(&args[0], &option)) return 0; gid = make_kgid(current_user_ns(), option); if (!gid_valid(gid)) { ext3_msg(sb, KERN_ERR, "Invalid gid value %d", option); return 0; } sbi->s_resgid = gid; break; case Opt_sb: /* handled by get_sb_block() instead of here */ /* *sb_block = match_int(&args[0]); */ break; case Opt_err_panic: clear_opt (sbi->s_mount_opt, ERRORS_CONT); clear_opt (sbi->s_mount_opt, ERRORS_RO); set_opt (sbi->s_mount_opt, ERRORS_PANIC); break; case Opt_err_ro: clear_opt (sbi->s_mount_opt, ERRORS_CONT); clear_opt (sbi->s_mount_opt, ERRORS_PANIC); set_opt (sbi->s_mount_opt, ERRORS_RO); break; case Opt_err_cont: clear_opt (sbi->s_mount_opt, ERRORS_RO); clear_opt (sbi->s_mount_opt, ERRORS_PANIC); set_opt (sbi->s_mount_opt, ERRORS_CONT); break; case Opt_nouid32: set_opt (sbi->s_mount_opt, NO_UID32); break; case Opt_nocheck: clear_opt (sbi->s_mount_opt, CHECK); break; case Opt_debug: set_opt (sbi->s_mount_opt, DEBUG); break; case Opt_oldalloc: ext3_msg(sb, KERN_WARNING, "Ignoring deprecated oldalloc option"); break; case Opt_orlov: ext3_msg(sb, KERN_WARNING, "Ignoring deprecated orlov option"); break; #ifdef CONFIG_EXT3_FS_XATTR case Opt_user_xattr: set_opt (sbi->s_mount_opt, XATTR_USER); break; case Opt_nouser_xattr: clear_opt (sbi->s_mount_opt, XATTR_USER); break; #else case Opt_user_xattr: case Opt_nouser_xattr: ext3_msg(sb, KERN_INFO, "(no)user_xattr options not supported"); break; #endif #ifdef CONFIG_EXT3_FS_POSIX_ACL case Opt_acl: set_opt(sbi->s_mount_opt, POSIX_ACL); break; case Opt_noacl: clear_opt(sbi->s_mount_opt, POSIX_ACL); break; #else case Opt_acl: case Opt_noacl: ext3_msg(sb, KERN_INFO, "(no)acl options not supported"); break; #endif case Opt_reservation: set_opt(sbi->s_mount_opt, RESERVATION); break; case Opt_noreservation: clear_opt(sbi->s_mount_opt, RESERVATION); break; case Opt_journal_update: /* @@@ FIXME */ /* Eventually we will want to be able to create a journal file here. For now, only allow the user to specify an existing inode to be the journal file. */ if (is_remount) { ext3_msg(sb, KERN_ERR, "error: cannot specify " "journal on remount"); return 0; } set_opt (sbi->s_mount_opt, UPDATE_JOURNAL); break; case Opt_journal_inum: if (is_remount) { ext3_msg(sb, KERN_ERR, "error: cannot specify " "journal on remount"); return 0; } if (match_int(&args[0], &option)) return 0; *inum = option; break; case Opt_journal_dev: if (is_remount) { ext3_msg(sb, KERN_ERR, "error: cannot specify " "journal on remount"); return 0; } if (match_int(&args[0], &option)) return 0; *journal_devnum = option; break; case Opt_noload: set_opt (sbi->s_mount_opt, NOLOAD); break; case Opt_commit: if (match_int(&args[0], &option)) return 0; if (option < 0) return 0; if (option == 0) option = JBD_DEFAULT_MAX_COMMIT_AGE; sbi->s_commit_interval = HZ * option; break; case Opt_data_journal: data_opt = EXT3_MOUNT_JOURNAL_DATA; goto datacheck; case Opt_data_ordered: data_opt = EXT3_MOUNT_ORDERED_DATA; goto datacheck; case Opt_data_writeback: data_opt = EXT3_MOUNT_WRITEBACK_DATA; datacheck: if (is_remount) { if (test_opt(sb, DATA_FLAGS) == data_opt) break; ext3_msg(sb, KERN_ERR, "error: cannot change " "data mode on remount. The filesystem " "is mounted in data=%s mode and you " "try to remount it in data=%s mode.", data_mode_string(test_opt(sb, DATA_FLAGS)), data_mode_string(data_opt)); return 0; } else { clear_opt(sbi->s_mount_opt, DATA_FLAGS); sbi->s_mount_opt |= data_opt; } break; case Opt_data_err_abort: set_opt(sbi->s_mount_opt, DATA_ERR_ABORT); break; case Opt_data_err_ignore: clear_opt(sbi->s_mount_opt, DATA_ERR_ABORT); break; #ifdef CONFIG_QUOTA case Opt_usrjquota: if (!set_qf_name(sb, USRQUOTA, &args[0])) return 0; break; case Opt_grpjquota: if (!set_qf_name(sb, GRPQUOTA, &args[0])) return 0; break; case Opt_offusrjquota: if (!clear_qf_name(sb, USRQUOTA)) return 0; break; case Opt_offgrpjquota: if (!clear_qf_name(sb, GRPQUOTA)) return 0; break; case Opt_jqfmt_vfsold: qfmt = QFMT_VFS_OLD; goto set_qf_format; case Opt_jqfmt_vfsv0: qfmt = QFMT_VFS_V0; goto set_qf_format; case Opt_jqfmt_vfsv1: qfmt = QFMT_VFS_V1; set_qf_format: if (sb_any_quota_loaded(sb) && sbi->s_jquota_fmt != qfmt) { ext3_msg(sb, KERN_ERR, "error: cannot change " "journaled quota options when " "quota turned on."); return 0; } sbi->s_jquota_fmt = qfmt; break; case Opt_quota: case Opt_usrquota: set_opt(sbi->s_mount_opt, QUOTA); set_opt(sbi->s_mount_opt, USRQUOTA); break; case Opt_grpquota: set_opt(sbi->s_mount_opt, QUOTA); set_opt(sbi->s_mount_opt, GRPQUOTA); break; case Opt_noquota: if (sb_any_quota_loaded(sb)) { ext3_msg(sb, KERN_ERR, "error: cannot change " "quota options when quota turned on."); return 0; } clear_opt(sbi->s_mount_opt, QUOTA); clear_opt(sbi->s_mount_opt, USRQUOTA); clear_opt(sbi->s_mount_opt, GRPQUOTA); break; #else case Opt_quota: case Opt_usrquota: case Opt_grpquota: ext3_msg(sb, KERN_ERR, "error: quota options not supported."); break; case Opt_usrjquota: case Opt_grpjquota: case Opt_offusrjquota: case Opt_offgrpjquota: case Opt_jqfmt_vfsold: case Opt_jqfmt_vfsv0: case Opt_jqfmt_vfsv1: ext3_msg(sb, KERN_ERR, "error: journaled quota options not " "supported."); break; case Opt_noquota: break; #endif case Opt_abort: set_opt(sbi->s_mount_opt, ABORT); break; case Opt_nobarrier: clear_opt(sbi->s_mount_opt, BARRIER); break; case Opt_barrier: if (args[0].from) { if (match_int(&args[0], &option)) return 0; } else option = 1; /* No argument, default to 1 */ if (option) set_opt(sbi->s_mount_opt, BARRIER); else clear_opt(sbi->s_mount_opt, BARRIER); break; case Opt_ignore: break; case Opt_resize: if (!is_remount) { ext3_msg(sb, KERN_ERR, "error: resize option only available " "for remount"); return 0; } if (match_int(&args[0], &option) != 0) return 0; *n_blocks_count = option; break; case Opt_nobh: ext3_msg(sb, KERN_WARNING, "warning: ignoring deprecated nobh option"); break; case Opt_bh: ext3_msg(sb, KERN_WARNING, "warning: ignoring deprecated bh option"); break; default: ext3_msg(sb, KERN_ERR, "error: unrecognized mount option \"%s\" " "or missing value", p); return 0; } } #ifdef CONFIG_QUOTA if (sbi->s_qf_names[USRQUOTA] || sbi->s_qf_names[GRPQUOTA]) { if (test_opt(sb, USRQUOTA) && sbi->s_qf_names[USRQUOTA]) clear_opt(sbi->s_mount_opt, USRQUOTA); if (test_opt(sb, GRPQUOTA) && sbi->s_qf_names[GRPQUOTA]) clear_opt(sbi->s_mount_opt, GRPQUOTA); if (test_opt(sb, GRPQUOTA) || test_opt(sb, USRQUOTA)) { ext3_msg(sb, KERN_ERR, "error: old and new quota " "format mixing."); return 0; } if (!sbi->s_jquota_fmt) { ext3_msg(sb, KERN_ERR, "error: journaled quota format " "not specified."); return 0; } } else { if (sbi->s_jquota_fmt) { ext3_msg(sb, KERN_ERR, "error: journaled quota format " "specified with no journaling " "enabled."); return 0; } } #endif return 1; } static int ext3_setup_super(struct super_block *sb, struct ext3_super_block *es, int read_only) { struct ext3_sb_info *sbi = EXT3_SB(sb); int res = 0; if (le32_to_cpu(es->s_rev_level) > EXT3_MAX_SUPP_REV) { ext3_msg(sb, KERN_ERR, "error: revision level too high, " "forcing read-only mode"); res = MS_RDONLY; } if (read_only) return res; if (!(sbi->s_mount_state & EXT3_VALID_FS)) ext3_msg(sb, KERN_WARNING, "warning: mounting unchecked fs, " "running e2fsck is recommended"); else if ((sbi->s_mount_state & EXT3_ERROR_FS)) ext3_msg(sb, KERN_WARNING, "warning: mounting fs with errors, " "running e2fsck is recommended"); else if ((__s16) le16_to_cpu(es->s_max_mnt_count) > 0 && le16_to_cpu(es->s_mnt_count) >= le16_to_cpu(es->s_max_mnt_count)) ext3_msg(sb, KERN_WARNING, "warning: maximal mount count reached, " "running e2fsck is recommended"); else if (le32_to_cpu(es->s_checkinterval) && (le32_to_cpu(es->s_lastcheck) + le32_to_cpu(es->s_checkinterval) <= get_seconds())) ext3_msg(sb, KERN_WARNING, "warning: checktime reached, " "running e2fsck is recommended"); #if 0 /* @@@ We _will_ want to clear the valid bit if we find inconsistencies, to force a fsck at reboot. But for a plain journaled filesystem we can keep it set as valid forever! :) */ es->s_state &= cpu_to_le16(~EXT3_VALID_FS); #endif if (!le16_to_cpu(es->s_max_mnt_count)) es->s_max_mnt_count = cpu_to_le16(EXT3_DFL_MAX_MNT_COUNT); le16_add_cpu(&es->s_mnt_count, 1); es->s_mtime = cpu_to_le32(get_seconds()); ext3_update_dynamic_rev(sb); EXT3_SET_INCOMPAT_FEATURE(sb, EXT3_FEATURE_INCOMPAT_RECOVER); ext3_commit_super(sb, es, 1); if (test_opt(sb, DEBUG)) ext3_msg(sb, KERN_INFO, "[bs=%lu, gc=%lu, " "bpg=%lu, ipg=%lu, mo=%04lx]", sb->s_blocksize, sbi->s_groups_count, EXT3_BLOCKS_PER_GROUP(sb), EXT3_INODES_PER_GROUP(sb), sbi->s_mount_opt); if (EXT3_SB(sb)->s_journal->j_inode == NULL) { char b[BDEVNAME_SIZE]; ext3_msg(sb, KERN_INFO, "using external journal on %s", bdevname(EXT3_SB(sb)->s_journal->j_dev, b)); } else { ext3_msg(sb, KERN_INFO, "using internal journal"); } cleancache_init_fs(sb); return res; } /* Called at mount-time, super-block is locked */ static int ext3_check_descriptors(struct super_block *sb) { struct ext3_sb_info *sbi = EXT3_SB(sb); int i; ext3_debug ("Checking group descriptors"); for (i = 0; i < sbi->s_groups_count; i++) { struct ext3_group_desc *gdp = ext3_get_group_desc(sb, i, NULL); ext3_fsblk_t first_block = ext3_group_first_block_no(sb, i); ext3_fsblk_t last_block; if (i == sbi->s_groups_count - 1) last_block = le32_to_cpu(sbi->s_es->s_blocks_count) - 1; else last_block = first_block + (EXT3_BLOCKS_PER_GROUP(sb) - 1); if (le32_to_cpu(gdp->bg_block_bitmap) < first_block || le32_to_cpu(gdp->bg_block_bitmap) > last_block) { ext3_error (sb, "ext3_check_descriptors", "Block bitmap for group %d" " not in group (block %lu)!", i, (unsigned long) le32_to_cpu(gdp->bg_block_bitmap)); return 0; } if (le32_to_cpu(gdp->bg_inode_bitmap) < first_block || le32_to_cpu(gdp->bg_inode_bitmap) > last_block) { ext3_error (sb, "ext3_check_descriptors", "Inode bitmap for group %d" " not in group (block %lu)!", i, (unsigned long) le32_to_cpu(gdp->bg_inode_bitmap)); return 0; } if (le32_to_cpu(gdp->bg_inode_table) < first_block || le32_to_cpu(gdp->bg_inode_table) + sbi->s_itb_per_group - 1 > last_block) { ext3_error (sb, "ext3_check_descriptors", "Inode table for group %d" " not in group (block %lu)!", i, (unsigned long) le32_to_cpu(gdp->bg_inode_table)); return 0; } } sbi->s_es->s_free_blocks_count=cpu_to_le32(ext3_count_free_blocks(sb)); sbi->s_es->s_free_inodes_count=cpu_to_le32(ext3_count_free_inodes(sb)); return 1; } /* ext3_orphan_cleanup() walks a singly-linked list of inodes (starting at * the superblock) which were deleted from all directories, but held open by * a process at the time of a crash. We walk the list and try to delete these * inodes at recovery time (only with a read-write filesystem). * * In order to keep the orphan inode chain consistent during traversal (in * case of crash during recovery), we link each inode into the superblock * orphan list_head and handle it the same way as an inode deletion during * normal operation (which journals the operations for us). * * We only do an iget() and an iput() on each inode, which is very safe if we * accidentally point at an in-use or already deleted inode. The worst that * can happen in this case is that we get a "bit already cleared" message from * ext3_free_inode(). The only reason we would point at a wrong inode is if * e2fsck was run on this filesystem, and it must have already done the orphan * inode cleanup for us, so we can safely abort without any further action. */ static void ext3_orphan_cleanup (struct super_block * sb, struct ext3_super_block * es) { unsigned int s_flags = sb->s_flags; int nr_orphans = 0, nr_truncates = 0; #ifdef CONFIG_QUOTA int i; #endif if (!es->s_last_orphan) { jbd_debug(4, "no orphan inodes to clean up\n"); return; } if (bdev_read_only(sb->s_bdev)) { ext3_msg(sb, KERN_ERR, "error: write access " "unavailable, skipping orphan cleanup."); return; } /* Check if feature set allows readwrite operations */ if (EXT3_HAS_RO_COMPAT_FEATURE(sb, ~EXT3_FEATURE_RO_COMPAT_SUPP)) { ext3_msg(sb, KERN_INFO, "Skipping orphan cleanup due to " "unknown ROCOMPAT features"); return; } if (EXT3_SB(sb)->s_mount_state & EXT3_ERROR_FS) { /* don't clear list on RO mount w/ errors */ if (es->s_last_orphan && !(s_flags & MS_RDONLY)) { jbd_debug(1, "Errors on filesystem, " "clearing orphan list.\n"); es->s_last_orphan = 0; } jbd_debug(1, "Skipping orphan recovery on fs with errors.\n"); return; } if (s_flags & MS_RDONLY) { ext3_msg(sb, KERN_INFO, "orphan cleanup on readonly fs"); sb->s_flags &= ~MS_RDONLY; } #ifdef CONFIG_QUOTA /* Needed for iput() to work correctly and not trash data */ sb->s_flags |= MS_ACTIVE; /* Turn on quotas so that they are updated correctly */ for (i = 0; i < MAXQUOTAS; i++) { if (EXT3_SB(sb)->s_qf_names[i]) { int ret = ext3_quota_on_mount(sb, i); if (ret < 0) ext3_msg(sb, KERN_ERR, "error: cannot turn on journaled " "quota: %d", ret); } } #endif while (es->s_last_orphan) { struct inode *inode; inode = ext3_orphan_get(sb, le32_to_cpu(es->s_last_orphan)); if (IS_ERR(inode)) { es->s_last_orphan = 0; break; } list_add(&EXT3_I(inode)->i_orphan, &EXT3_SB(sb)->s_orphan); dquot_initialize(inode); if (inode->i_nlink) { printk(KERN_DEBUG "%s: truncating inode %lu to %Ld bytes\n", __func__, inode->i_ino, inode->i_size); jbd_debug(2, "truncating inode %lu to %Ld bytes\n", inode->i_ino, inode->i_size); ext3_truncate(inode); nr_truncates++; } else { printk(KERN_DEBUG "%s: deleting unreferenced inode %lu\n", __func__, inode->i_ino); jbd_debug(2, "deleting unreferenced inode %lu\n", inode->i_ino); nr_orphans++; } iput(inode); /* The delete magic happens here! */ } #define PLURAL(x) (x), ((x)==1) ? "" : "s" if (nr_orphans) ext3_msg(sb, KERN_INFO, "%d orphan inode%s deleted", PLURAL(nr_orphans)); if (nr_truncates) ext3_msg(sb, KERN_INFO, "%d truncate%s cleaned up", PLURAL(nr_truncates)); #ifdef CONFIG_QUOTA /* Turn quotas off */ for (i = 0; i < MAXQUOTAS; i++) { if (sb_dqopt(sb)->files[i]) dquot_quota_off(sb, i); } #endif sb->s_flags = s_flags; /* Restore MS_RDONLY status */ } /* * Maximal file size. There is a direct, and {,double-,triple-}indirect * block limit, and also a limit of (2^32 - 1) 512-byte sectors in i_blocks. * We need to be 1 filesystem block less than the 2^32 sector limit. */ static loff_t ext3_max_size(int bits) { loff_t res = EXT3_NDIR_BLOCKS; int meta_blocks; loff_t upper_limit; /* This is calculated to be the largest file size for a * dense, file such that the total number of * sectors in the file, including data and all indirect blocks, * does not exceed 2^32 -1 * __u32 i_blocks representing the total number of * 512 bytes blocks of the file */ upper_limit = (1LL << 32) - 1; /* total blocks in file system block size */ upper_limit >>= (bits - 9); /* indirect blocks */ meta_blocks = 1; /* double indirect blocks */ meta_blocks += 1 + (1LL << (bits-2)); /* tripple indirect blocks */ meta_blocks += 1 + (1LL << (bits-2)) + (1LL << (2*(bits-2))); upper_limit -= meta_blocks; upper_limit <<= bits; res += 1LL << (bits-2); res += 1LL << (2*(bits-2)); res += 1LL << (3*(bits-2)); res <<= bits; if (res > upper_limit) res = upper_limit; if (res > MAX_LFS_FILESIZE) res = MAX_LFS_FILESIZE; return res; } static ext3_fsblk_t descriptor_loc(struct super_block *sb, ext3_fsblk_t logic_sb_block, int nr) { struct ext3_sb_info *sbi = EXT3_SB(sb); unsigned long bg, first_meta_bg; int has_super = 0; first_meta_bg = le32_to_cpu(sbi->s_es->s_first_meta_bg); if (!EXT3_HAS_INCOMPAT_FEATURE(sb, EXT3_FEATURE_INCOMPAT_META_BG) || nr < first_meta_bg) return (logic_sb_block + nr + 1); bg = sbi->s_desc_per_block * nr; if (ext3_bg_has_super(sb, bg)) has_super = 1; return (has_super + ext3_group_first_block_no(sb, bg)); } static int ext3_fill_super (struct super_block *sb, void *data, int silent) { struct buffer_head * bh; struct ext3_super_block *es = NULL; struct ext3_sb_info *sbi; ext3_fsblk_t block; ext3_fsblk_t sb_block = get_sb_block(&data, sb); ext3_fsblk_t logic_sb_block; unsigned long offset = 0; unsigned int journal_inum = 0; unsigned long journal_devnum = 0; unsigned long def_mount_opts; struct inode *root; int blocksize; int hblock; int db_count; int i; int needs_recovery; int ret = -EINVAL; __le32 features; int err; sbi = kzalloc(sizeof(*sbi), GFP_KERNEL); if (!sbi) return -ENOMEM; sbi->s_blockgroup_lock = kzalloc(sizeof(struct blockgroup_lock), GFP_KERNEL); if (!sbi->s_blockgroup_lock) { kfree(sbi); return -ENOMEM; } sb->s_fs_info = sbi; sbi->s_sb_block = sb_block; blocksize = sb_min_blocksize(sb, EXT3_MIN_BLOCK_SIZE); if (!blocksize) { ext3_msg(sb, KERN_ERR, "error: unable to set blocksize"); goto out_fail; } /* * The ext3 superblock will not be buffer aligned for other than 1kB * block sizes. We need to calculate the offset from buffer start. */ if (blocksize != EXT3_MIN_BLOCK_SIZE) { logic_sb_block = (sb_block * EXT3_MIN_BLOCK_SIZE) / blocksize; offset = (sb_block * EXT3_MIN_BLOCK_SIZE) % blocksize; } else { logic_sb_block = sb_block; } if (!(bh = sb_bread(sb, logic_sb_block))) { ext3_msg(sb, KERN_ERR, "error: unable to read superblock"); goto out_fail; } /* * Note: s_es must be initialized as soon as possible because * some ext3 macro-instructions depend on its value */ es = (struct ext3_super_block *) (bh->b_data + offset); sbi->s_es = es; sb->s_magic = le16_to_cpu(es->s_magic); if (sb->s_magic != EXT3_SUPER_MAGIC) goto cantfind_ext3; /* Set defaults before we parse the mount options */ def_mount_opts = le32_to_cpu(es->s_default_mount_opts); if (def_mount_opts & EXT3_DEFM_DEBUG) set_opt(sbi->s_mount_opt, DEBUG); if (def_mount_opts & EXT3_DEFM_BSDGROUPS) set_opt(sbi->s_mount_opt, GRPID); if (def_mount_opts & EXT3_DEFM_UID16) set_opt(sbi->s_mount_opt, NO_UID32); #ifdef CONFIG_EXT3_FS_XATTR if (def_mount_opts & EXT3_DEFM_XATTR_USER) set_opt(sbi->s_mount_opt, XATTR_USER); #endif #ifdef CONFIG_EXT3_FS_POSIX_ACL if (def_mount_opts & EXT3_DEFM_ACL) set_opt(sbi->s_mount_opt, POSIX_ACL); #endif if ((def_mount_opts & EXT3_DEFM_JMODE) == EXT3_DEFM_JMODE_DATA) set_opt(sbi->s_mount_opt, JOURNAL_DATA); else if ((def_mount_opts & EXT3_DEFM_JMODE) == EXT3_DEFM_JMODE_ORDERED) set_opt(sbi->s_mount_opt, ORDERED_DATA); else if ((def_mount_opts & EXT3_DEFM_JMODE) == EXT3_DEFM_JMODE_WBACK) set_opt(sbi->s_mount_opt, WRITEBACK_DATA); if (le16_to_cpu(sbi->s_es->s_errors) == EXT3_ERRORS_PANIC) set_opt(sbi->s_mount_opt, ERRORS_PANIC); else if (le16_to_cpu(sbi->s_es->s_errors) == EXT3_ERRORS_CONTINUE) set_opt(sbi->s_mount_opt, ERRORS_CONT); else set_opt(sbi->s_mount_opt, ERRORS_RO); sbi->s_resuid = make_kuid(&init_user_ns, le16_to_cpu(es->s_def_resuid)); sbi->s_resgid = make_kgid(&init_user_ns, le16_to_cpu(es->s_def_resgid)); /* enable barriers by default */ set_opt(sbi->s_mount_opt, BARRIER); set_opt(sbi->s_mount_opt, RESERVATION); if (!parse_options ((char *) data, sb, &journal_inum, &journal_devnum, NULL, 0)) goto failed_mount; sb->s_flags = (sb->s_flags & ~MS_POSIXACL) | (test_opt(sb, POSIX_ACL) ? MS_POSIXACL : 0); if (le32_to_cpu(es->s_rev_level) == EXT3_GOOD_OLD_REV && (EXT3_HAS_COMPAT_FEATURE(sb, ~0U) || EXT3_HAS_RO_COMPAT_FEATURE(sb, ~0U) || EXT3_HAS_INCOMPAT_FEATURE(sb, ~0U))) ext3_msg(sb, KERN_WARNING, "warning: feature flags set on rev 0 fs, " "running e2fsck is recommended"); /* * Check feature flags regardless of the revision level, since we * previously didn't change the revision level when setting the flags, * so there is a chance incompat flags are set on a rev 0 filesystem. */ features = EXT3_HAS_INCOMPAT_FEATURE(sb, ~EXT3_FEATURE_INCOMPAT_SUPP); if (features) { ext3_msg(sb, KERN_ERR, "error: couldn't mount because of unsupported " "optional features (%x)", le32_to_cpu(features)); goto failed_mount; } features = EXT3_HAS_RO_COMPAT_FEATURE(sb, ~EXT3_FEATURE_RO_COMPAT_SUPP); if (!(sb->s_flags & MS_RDONLY) && features) { ext3_msg(sb, KERN_ERR, "error: couldn't mount RDWR because of unsupported " "optional features (%x)", le32_to_cpu(features)); goto failed_mount; } blocksize = BLOCK_SIZE << le32_to_cpu(es->s_log_block_size); if (blocksize < EXT3_MIN_BLOCK_SIZE || blocksize > EXT3_MAX_BLOCK_SIZE) { ext3_msg(sb, KERN_ERR, "error: couldn't mount because of unsupported " "filesystem blocksize %d", blocksize); goto failed_mount; } hblock = bdev_logical_block_size(sb->s_bdev); if (sb->s_blocksize != blocksize) { /* * Make sure the blocksize for the filesystem is larger * than the hardware sectorsize for the machine. */ if (blocksize < hblock) { ext3_msg(sb, KERN_ERR, "error: fsblocksize %d too small for " "hardware sectorsize %d", blocksize, hblock); goto failed_mount; } brelse (bh); if (!sb_set_blocksize(sb, blocksize)) { ext3_msg(sb, KERN_ERR, "error: bad blocksize %d", blocksize); goto out_fail; } logic_sb_block = (sb_block * EXT3_MIN_BLOCK_SIZE) / blocksize; offset = (sb_block * EXT3_MIN_BLOCK_SIZE) % blocksize; bh = sb_bread(sb, logic_sb_block); if (!bh) { ext3_msg(sb, KERN_ERR, "error: can't read superblock on 2nd try"); goto failed_mount; } es = (struct ext3_super_block *)(bh->b_data + offset); sbi->s_es = es; if (es->s_magic != cpu_to_le16(EXT3_SUPER_MAGIC)) { ext3_msg(sb, KERN_ERR, "error: magic mismatch"); goto failed_mount; } } sb->s_maxbytes = ext3_max_size(sb->s_blocksize_bits); if (le32_to_cpu(es->s_rev_level) == EXT3_GOOD_OLD_REV) { sbi->s_inode_size = EXT3_GOOD_OLD_INODE_SIZE; sbi->s_first_ino = EXT3_GOOD_OLD_FIRST_INO; } else { sbi->s_inode_size = le16_to_cpu(es->s_inode_size); sbi->s_first_ino = le32_to_cpu(es->s_first_ino); if ((sbi->s_inode_size < EXT3_GOOD_OLD_INODE_SIZE) || (!is_power_of_2(sbi->s_inode_size)) || (sbi->s_inode_size > blocksize)) { ext3_msg(sb, KERN_ERR, "error: unsupported inode size: %d", sbi->s_inode_size); goto failed_mount; } } sbi->s_frag_size = EXT3_MIN_FRAG_SIZE << le32_to_cpu(es->s_log_frag_size); if (blocksize != sbi->s_frag_size) { ext3_msg(sb, KERN_ERR, "error: fragsize %lu != blocksize %u (unsupported)", sbi->s_frag_size, blocksize); goto failed_mount; } sbi->s_frags_per_block = 1; sbi->s_blocks_per_group = le32_to_cpu(es->s_blocks_per_group); sbi->s_frags_per_group = le32_to_cpu(es->s_frags_per_group); sbi->s_inodes_per_group = le32_to_cpu(es->s_inodes_per_group); if (EXT3_INODE_SIZE(sb) == 0 || EXT3_INODES_PER_GROUP(sb) == 0) goto cantfind_ext3; sbi->s_inodes_per_block = blocksize / EXT3_INODE_SIZE(sb); if (sbi->s_inodes_per_block == 0) goto cantfind_ext3; sbi->s_itb_per_group = sbi->s_inodes_per_group / sbi->s_inodes_per_block; sbi->s_desc_per_block = blocksize / sizeof(struct ext3_group_desc); sbi->s_sbh = bh; sbi->s_mount_state = le16_to_cpu(es->s_state); sbi->s_addr_per_block_bits = ilog2(EXT3_ADDR_PER_BLOCK(sb)); sbi->s_desc_per_block_bits = ilog2(EXT3_DESC_PER_BLOCK(sb)); for (i=0; i < 4; i++) sbi->s_hash_seed[i] = le32_to_cpu(es->s_hash_seed[i]); sbi->s_def_hash_version = es->s_def_hash_version; i = le32_to_cpu(es->s_flags); if (i & EXT2_FLAGS_UNSIGNED_HASH) sbi->s_hash_unsigned = 3; else if ((i & EXT2_FLAGS_SIGNED_HASH) == 0) { #ifdef __CHAR_UNSIGNED__ es->s_flags |= cpu_to_le32(EXT2_FLAGS_UNSIGNED_HASH); sbi->s_hash_unsigned = 3; #else es->s_flags |= cpu_to_le32(EXT2_FLAGS_SIGNED_HASH); #endif } if (sbi->s_blocks_per_group > blocksize * 8) { ext3_msg(sb, KERN_ERR, "#blocks per group too big: %lu", sbi->s_blocks_per_group); goto failed_mount; } if (sbi->s_frags_per_group > blocksize * 8) { ext3_msg(sb, KERN_ERR, "error: #fragments per group too big: %lu", sbi->s_frags_per_group); goto failed_mount; } if (sbi->s_inodes_per_group > blocksize * 8) { ext3_msg(sb, KERN_ERR, "error: #inodes per group too big: %lu", sbi->s_inodes_per_group); goto failed_mount; } err = generic_check_addressable(sb->s_blocksize_bits, le32_to_cpu(es->s_blocks_count)); if (err) { ext3_msg(sb, KERN_ERR, "error: filesystem is too large to mount safely"); if (sizeof(sector_t) < 8) ext3_msg(sb, KERN_ERR, "error: CONFIG_LBDAF not enabled"); ret = err; goto failed_mount; } if (EXT3_BLOCKS_PER_GROUP(sb) == 0) goto cantfind_ext3; sbi->s_groups_count = ((le32_to_cpu(es->s_blocks_count) - le32_to_cpu(es->s_first_data_block) - 1) / EXT3_BLOCKS_PER_GROUP(sb)) + 1; db_count = DIV_ROUND_UP(sbi->s_groups_count, EXT3_DESC_PER_BLOCK(sb)); sbi->s_group_desc = kmalloc(db_count * sizeof (struct buffer_head *), GFP_KERNEL); if (sbi->s_group_desc == NULL) { ext3_msg(sb, KERN_ERR, "error: not enough memory"); ret = -ENOMEM; goto failed_mount; } bgl_lock_init(sbi->s_blockgroup_lock); for (i = 0; i < db_count; i++) { block = descriptor_loc(sb, logic_sb_block, i); sbi->s_group_desc[i] = sb_bread(sb, block); if (!sbi->s_group_desc[i]) { ext3_msg(sb, KERN_ERR, "error: can't read group descriptor %d", i); db_count = i; goto failed_mount2; } } if (!ext3_check_descriptors (sb)) { ext3_msg(sb, KERN_ERR, "error: group descriptors corrupted"); goto failed_mount2; } sbi->s_gdb_count = db_count; get_random_bytes(&sbi->s_next_generation, sizeof(u32)); spin_lock_init(&sbi->s_next_gen_lock); /* per fileystem reservation list head & lock */ spin_lock_init(&sbi->s_rsv_window_lock); sbi->s_rsv_window_root = RB_ROOT; /* Add a single, static dummy reservation to the start of the * reservation window list --- it gives us a placeholder for * append-at-start-of-list which makes the allocation logic * _much_ simpler. */ sbi->s_rsv_window_head.rsv_start = EXT3_RESERVE_WINDOW_NOT_ALLOCATED; sbi->s_rsv_window_head.rsv_end = EXT3_RESERVE_WINDOW_NOT_ALLOCATED; sbi->s_rsv_window_head.rsv_alloc_hit = 0; sbi->s_rsv_window_head.rsv_goal_size = 0; ext3_rsv_window_add(sb, &sbi->s_rsv_window_head); /* * set up enough so that it can read an inode */ sb->s_op = &ext3_sops; sb->s_export_op = &ext3_export_ops; sb->s_xattr = ext3_xattr_handlers; #ifdef CONFIG_QUOTA sb->s_qcop = &ext3_qctl_operations; sb->dq_op = &ext3_quota_operations; #endif memcpy(sb->s_uuid, es->s_uuid, sizeof(es->s_uuid)); INIT_LIST_HEAD(&sbi->s_orphan); /* unlinked but open files */ mutex_init(&sbi->s_orphan_lock); mutex_init(&sbi->s_resize_lock); sb->s_root = NULL; needs_recovery = (es->s_last_orphan != 0 || EXT3_HAS_INCOMPAT_FEATURE(sb, EXT3_FEATURE_INCOMPAT_RECOVER)); /* * The first inode we look at is the journal inode. Don't try * root first: it may be modified in the journal! */ if (!test_opt(sb, NOLOAD) && EXT3_HAS_COMPAT_FEATURE(sb, EXT3_FEATURE_COMPAT_HAS_JOURNAL)) { if (ext3_load_journal(sb, es, journal_devnum)) goto failed_mount2; } else if (journal_inum) { if (ext3_create_journal(sb, es, journal_inum)) goto failed_mount2; } else { if (!silent) ext3_msg(sb, KERN_ERR, "error: no journal found. " "mounting ext3 over ext2?"); goto failed_mount2; } err = percpu_counter_init(&sbi->s_freeblocks_counter, ext3_count_free_blocks(sb)); if (!err) { err = percpu_counter_init(&sbi->s_freeinodes_counter, ext3_count_free_inodes(sb)); } if (!err) { err = percpu_counter_init(&sbi->s_dirs_counter, ext3_count_dirs(sb)); } if (err) { ext3_msg(sb, KERN_ERR, "error: insufficient memory"); ret = err; goto failed_mount3; } /* We have now updated the journal if required, so we can * validate the data journaling mode. */ switch (test_opt(sb, DATA_FLAGS)) { case 0: /* No mode set, assume a default based on the journal capabilities: ORDERED_DATA if the journal can cope, else JOURNAL_DATA */ if (journal_check_available_features (sbi->s_journal, 0, 0, JFS_FEATURE_INCOMPAT_REVOKE)) set_opt(sbi->s_mount_opt, DEFAULT_DATA_MODE); else set_opt(sbi->s_mount_opt, JOURNAL_DATA); break; case EXT3_MOUNT_ORDERED_DATA: case EXT3_MOUNT_WRITEBACK_DATA: if (!journal_check_available_features (sbi->s_journal, 0, 0, JFS_FEATURE_INCOMPAT_REVOKE)) { ext3_msg(sb, KERN_ERR, "error: journal does not support " "requested data journaling mode"); goto failed_mount3; } default: break; } /* * The journal_load will have done any necessary log recovery, * so we can safely mount the rest of the filesystem now. */ root = ext3_iget(sb, EXT3_ROOT_INO); if (IS_ERR(root)) { ext3_msg(sb, KERN_ERR, "error: get root inode failed"); ret = PTR_ERR(root); goto failed_mount3; } if (!S_ISDIR(root->i_mode) || !root->i_blocks || !root->i_size) { iput(root); ext3_msg(sb, KERN_ERR, "error: corrupt root inode, run e2fsck"); goto failed_mount3; } sb->s_root = d_make_root(root); if (!sb->s_root) { ext3_msg(sb, KERN_ERR, "error: get root dentry failed"); ret = -ENOMEM; goto failed_mount3; } if (ext3_setup_super(sb, es, sb->s_flags & MS_RDONLY)) sb->s_flags |= MS_RDONLY; EXT3_SB(sb)->s_mount_state |= EXT3_ORPHAN_FS; ext3_orphan_cleanup(sb, es); EXT3_SB(sb)->s_mount_state &= ~EXT3_ORPHAN_FS; if (needs_recovery) { ext3_mark_recovery_complete(sb, es); ext3_msg(sb, KERN_INFO, "recovery complete"); } ext3_msg(sb, KERN_INFO, "mounted filesystem with %s data mode", test_opt(sb,DATA_FLAGS) == EXT3_MOUNT_JOURNAL_DATA ? "journal": test_opt(sb,DATA_FLAGS) == EXT3_MOUNT_ORDERED_DATA ? "ordered": "writeback"); sb->s_flags |= MS_SNAP_STABLE; return 0; cantfind_ext3: if (!silent) ext3_msg(sb, KERN_INFO, "error: can't find ext3 filesystem on dev %s.", sb->s_id); goto failed_mount; failed_mount3: percpu_counter_destroy(&sbi->s_freeblocks_counter); percpu_counter_destroy(&sbi->s_freeinodes_counter); percpu_counter_destroy(&sbi->s_dirs_counter); journal_destroy(sbi->s_journal); failed_mount2: for (i = 0; i < db_count; i++) brelse(sbi->s_group_desc[i]); kfree(sbi->s_group_desc); failed_mount: #ifdef CONFIG_QUOTA for (i = 0; i < MAXQUOTAS; i++) kfree(sbi->s_qf_names[i]); #endif ext3_blkdev_remove(sbi); brelse(bh); out_fail: sb->s_fs_info = NULL; kfree(sbi->s_blockgroup_lock); kfree(sbi); return ret; } /* * Setup any per-fs journal parameters now. We'll do this both on * initial mount, once the journal has been initialised but before we've * done any recovery; and again on any subsequent remount. */ static void ext3_init_journal_params(struct super_block *sb, journal_t *journal) { struct ext3_sb_info *sbi = EXT3_SB(sb); if (sbi->s_commit_interval) journal->j_commit_interval = sbi->s_commit_interval; /* We could also set up an ext3-specific default for the commit * interval here, but for now we'll just fall back to the jbd * default. */ spin_lock(&journal->j_state_lock); if (test_opt(sb, BARRIER)) journal->j_flags |= JFS_BARRIER; else journal->j_flags &= ~JFS_BARRIER; if (test_opt(sb, DATA_ERR_ABORT)) journal->j_flags |= JFS_ABORT_ON_SYNCDATA_ERR; else journal->j_flags &= ~JFS_ABORT_ON_SYNCDATA_ERR; spin_unlock(&journal->j_state_lock); } static journal_t *ext3_get_journal(struct super_block *sb, unsigned int journal_inum) { struct inode *journal_inode; journal_t *journal; /* First, test for the existence of a valid inode on disk. Bad * things happen if we iget() an unused inode, as the subsequent * iput() will try to delete it. */ journal_inode = ext3_iget(sb, journal_inum); if (IS_ERR(journal_inode)) { ext3_msg(sb, KERN_ERR, "error: no journal found"); return NULL; } if (!journal_inode->i_nlink) { make_bad_inode(journal_inode); iput(journal_inode); ext3_msg(sb, KERN_ERR, "error: journal inode is deleted"); return NULL; } jbd_debug(2, "Journal inode found at %p: %Ld bytes\n", journal_inode, journal_inode->i_size); if (!S_ISREG(journal_inode->i_mode)) { ext3_msg(sb, KERN_ERR, "error: invalid journal inode"); iput(journal_inode); return NULL; } journal = journal_init_inode(journal_inode); if (!journal) { ext3_msg(sb, KERN_ERR, "error: could not load journal inode"); iput(journal_inode); return NULL; } journal->j_private = sb; ext3_init_journal_params(sb, journal); return journal; } static journal_t *ext3_get_dev_journal(struct super_block *sb, dev_t j_dev) { struct buffer_head * bh; journal_t *journal; ext3_fsblk_t start; ext3_fsblk_t len; int hblock, blocksize; ext3_fsblk_t sb_block; unsigned long offset; struct ext3_super_block * es; struct block_device *bdev; bdev = ext3_blkdev_get(j_dev, sb); if (bdev == NULL) return NULL; blocksize = sb->s_blocksize; hblock = bdev_logical_block_size(bdev); if (blocksize < hblock) { ext3_msg(sb, KERN_ERR, "error: blocksize too small for journal device"); goto out_bdev; } sb_block = EXT3_MIN_BLOCK_SIZE / blocksize; offset = EXT3_MIN_BLOCK_SIZE % blocksize; set_blocksize(bdev, blocksize); if (!(bh = __bread(bdev, sb_block, blocksize))) { ext3_msg(sb, KERN_ERR, "error: couldn't read superblock of " "external journal"); goto out_bdev; } es = (struct ext3_super_block *) (bh->b_data + offset); if ((le16_to_cpu(es->s_magic) != EXT3_SUPER_MAGIC) || !(le32_to_cpu(es->s_feature_incompat) & EXT3_FEATURE_INCOMPAT_JOURNAL_DEV)) { ext3_msg(sb, KERN_ERR, "error: external journal has " "bad superblock"); brelse(bh); goto out_bdev; } if (memcmp(EXT3_SB(sb)->s_es->s_journal_uuid, es->s_uuid, 16)) { ext3_msg(sb, KERN_ERR, "error: journal UUID does not match"); brelse(bh); goto out_bdev; } len = le32_to_cpu(es->s_blocks_count); start = sb_block + 1; brelse(bh); /* we're done with the superblock */ journal = journal_init_dev(bdev, sb->s_bdev, start, len, blocksize); if (!journal) { ext3_msg(sb, KERN_ERR, "error: failed to create device journal"); goto out_bdev; } journal->j_private = sb; if (!bh_uptodate_or_lock(journal->j_sb_buffer)) { if (bh_submit_read(journal->j_sb_buffer)) { ext3_msg(sb, KERN_ERR, "I/O error on journal device"); goto out_journal; } } if (be32_to_cpu(journal->j_superblock->s_nr_users) != 1) { ext3_msg(sb, KERN_ERR, "error: external journal has more than one " "user (unsupported) - %d", be32_to_cpu(journal->j_superblock->s_nr_users)); goto out_journal; } EXT3_SB(sb)->journal_bdev = bdev; ext3_init_journal_params(sb, journal); return journal; out_journal: journal_destroy(journal); out_bdev: ext3_blkdev_put(bdev); return NULL; } static int ext3_load_journal(struct super_block *sb, struct ext3_super_block *es, unsigned long journal_devnum) { journal_t *journal; unsigned int journal_inum = le32_to_cpu(es->s_journal_inum); dev_t journal_dev; int err = 0; int really_read_only; if (journal_devnum && journal_devnum != le32_to_cpu(es->s_journal_dev)) { ext3_msg(sb, KERN_INFO, "external journal device major/minor " "numbers have changed"); journal_dev = new_decode_dev(journal_devnum); } else journal_dev = new_decode_dev(le32_to_cpu(es->s_journal_dev)); really_read_only = bdev_read_only(sb->s_bdev); /* * Are we loading a blank journal or performing recovery after a * crash? For recovery, we need to check in advance whether we * can get read-write access to the device. */ if (EXT3_HAS_INCOMPAT_FEATURE(sb, EXT3_FEATURE_INCOMPAT_RECOVER)) { if (sb->s_flags & MS_RDONLY) { ext3_msg(sb, KERN_INFO, "recovery required on readonly filesystem"); if (really_read_only) { ext3_msg(sb, KERN_ERR, "error: write access " "unavailable, cannot proceed"); return -EROFS; } ext3_msg(sb, KERN_INFO, "write access will be enabled during recovery"); } } if (journal_inum && journal_dev) { ext3_msg(sb, KERN_ERR, "error: filesystem has both journal " "and inode journals"); return -EINVAL; } if (journal_inum) { if (!(journal = ext3_get_journal(sb, journal_inum))) return -EINVAL; } else { if (!(journal = ext3_get_dev_journal(sb, journal_dev))) return -EINVAL; } if (!(journal->j_flags & JFS_BARRIER)) printk(KERN_INFO "EXT3-fs: barriers not enabled\n"); if (!really_read_only && test_opt(sb, UPDATE_JOURNAL)) { err = journal_update_format(journal); if (err) { ext3_msg(sb, KERN_ERR, "error updating journal"); journal_destroy(journal); return err; } } if (!EXT3_HAS_INCOMPAT_FEATURE(sb, EXT3_FEATURE_INCOMPAT_RECOVER)) err = journal_wipe(journal, !really_read_only); if (!err) err = journal_load(journal); if (err) { ext3_msg(sb, KERN_ERR, "error loading journal"); journal_destroy(journal); return err; } EXT3_SB(sb)->s_journal = journal; ext3_clear_journal_err(sb, es); if (!really_read_only && journal_devnum && journal_devnum != le32_to_cpu(es->s_journal_dev)) { es->s_journal_dev = cpu_to_le32(journal_devnum); /* Make sure we flush the recovery flag to disk. */ ext3_commit_super(sb, es, 1); } return 0; } static int ext3_create_journal(struct super_block *sb, struct ext3_super_block *es, unsigned int journal_inum) { journal_t *journal; int err; if (sb->s_flags & MS_RDONLY) { ext3_msg(sb, KERN_ERR, "error: readonly filesystem when trying to " "create journal"); return -EROFS; } journal = ext3_get_journal(sb, journal_inum); if (!journal) return -EINVAL; ext3_msg(sb, KERN_INFO, "creating new journal on inode %u", journal_inum); err = journal_create(journal); if (err) { ext3_msg(sb, KERN_ERR, "error creating journal"); journal_destroy(journal); return -EIO; } EXT3_SB(sb)->s_journal = journal; ext3_update_dynamic_rev(sb); EXT3_SET_INCOMPAT_FEATURE(sb, EXT3_FEATURE_INCOMPAT_RECOVER); EXT3_SET_COMPAT_FEATURE(sb, EXT3_FEATURE_COMPAT_HAS_JOURNAL); es->s_journal_inum = cpu_to_le32(journal_inum); /* Make sure we flush the recovery flag to disk. */ ext3_commit_super(sb, es, 1); return 0; } static int ext3_commit_super(struct super_block *sb, struct ext3_super_block *es, int sync) { struct buffer_head *sbh = EXT3_SB(sb)->s_sbh; int error = 0; if (!sbh) return error; if (buffer_write_io_error(sbh)) { /* * Oh, dear. A previous attempt to write the * superblock failed. This could happen because the * USB device was yanked out. Or it could happen to * be a transient write error and maybe the block will * be remapped. Nothing we can do but to retry the * write and hope for the best. */ ext3_msg(sb, KERN_ERR, "previous I/O error to " "superblock detected"); clear_buffer_write_io_error(sbh); set_buffer_uptodate(sbh); } /* * If the file system is mounted read-only, don't update the * superblock write time. This avoids updating the superblock * write time when we are mounting the root file system * read/only but we need to replay the journal; at that point, * for people who are east of GMT and who make their clock * tick in localtime for Windows bug-for-bug compatibility, * the clock is set in the future, and this will cause e2fsck * to complain and force a full file system check. */ if (!(sb->s_flags & MS_RDONLY)) es->s_wtime = cpu_to_le32(get_seconds()); es->s_free_blocks_count = cpu_to_le32(ext3_count_free_blocks(sb)); es->s_free_inodes_count = cpu_to_le32(ext3_count_free_inodes(sb)); BUFFER_TRACE(sbh, "marking dirty"); mark_buffer_dirty(sbh); if (sync) { error = sync_dirty_buffer(sbh); if (buffer_write_io_error(sbh)) { ext3_msg(sb, KERN_ERR, "I/O error while writing " "superblock"); clear_buffer_write_io_error(sbh); set_buffer_uptodate(sbh); } } return error; } /* * Have we just finished recovery? If so, and if we are mounting (or * remounting) the filesystem readonly, then we will end up with a * consistent fs on disk. Record that fact. */ static void ext3_mark_recovery_complete(struct super_block * sb, struct ext3_super_block * es) { journal_t *journal = EXT3_SB(sb)->s_journal; journal_lock_updates(journal); if (journal_flush(journal) < 0) goto out; if (EXT3_HAS_INCOMPAT_FEATURE(sb, EXT3_FEATURE_INCOMPAT_RECOVER) && sb->s_flags & MS_RDONLY) { EXT3_CLEAR_INCOMPAT_FEATURE(sb, EXT3_FEATURE_INCOMPAT_RECOVER); ext3_commit_super(sb, es, 1); } out: journal_unlock_updates(journal); } /* * If we are mounting (or read-write remounting) a filesystem whose journal * has recorded an error from a previous lifetime, move that error to the * main filesystem now. */ static void ext3_clear_journal_err(struct super_block *sb, struct ext3_super_block *es) { journal_t *journal; int j_errno; const char *errstr; journal = EXT3_SB(sb)->s_journal; /* * Now check for any error status which may have been recorded in the * journal by a prior ext3_error() or ext3_abort() */ j_errno = journal_errno(journal); if (j_errno) { char nbuf[16]; errstr = ext3_decode_error(sb, j_errno, nbuf); ext3_warning(sb, __func__, "Filesystem error recorded " "from previous mount: %s", errstr); ext3_warning(sb, __func__, "Marking fs in need of " "filesystem check."); EXT3_SB(sb)->s_mount_state |= EXT3_ERROR_FS; es->s_state |= cpu_to_le16(EXT3_ERROR_FS); ext3_commit_super (sb, es, 1); journal_clear_err(journal); } } /* * Force the running and committing transactions to commit, * and wait on the commit. */ int ext3_force_commit(struct super_block *sb) { journal_t *journal; int ret; if (sb->s_flags & MS_RDONLY) return 0; journal = EXT3_SB(sb)->s_journal; ret = ext3_journal_force_commit(journal); return ret; } static int ext3_sync_fs(struct super_block *sb, int wait) { tid_t target; trace_ext3_sync_fs(sb, wait); /* * Writeback quota in non-journalled quota case - journalled quota has * no dirty dquots */ dquot_writeback_dquots(sb, -1); if (journal_start_commit(EXT3_SB(sb)->s_journal, &target)) { if (wait) log_wait_commit(EXT3_SB(sb)->s_journal, target); } return 0; } /* * LVM calls this function before a (read-only) snapshot is created. This * gives us a chance to flush the journal completely and mark the fs clean. */ static int ext3_freeze(struct super_block *sb) { int error = 0; journal_t *journal; if (!(sb->s_flags & MS_RDONLY)) { journal = EXT3_SB(sb)->s_journal; /* Now we set up the journal barrier. */ journal_lock_updates(journal); /* * We don't want to clear needs_recovery flag when we failed * to flush the journal. */ error = journal_flush(journal); if (error < 0) goto out; /* Journal blocked and flushed, clear needs_recovery flag. */ EXT3_CLEAR_INCOMPAT_FEATURE(sb, EXT3_FEATURE_INCOMPAT_RECOVER); error = ext3_commit_super(sb, EXT3_SB(sb)->s_es, 1); if (error) goto out; } return 0; out: journal_unlock_updates(journal); return error; } /* * Called by LVM after the snapshot is done. We need to reset the RECOVER * flag here, even though the filesystem is not technically dirty yet. */ static int ext3_unfreeze(struct super_block *sb) { if (!(sb->s_flags & MS_RDONLY)) { /* Reser the needs_recovery flag before the fs is unlocked. */ EXT3_SET_INCOMPAT_FEATURE(sb, EXT3_FEATURE_INCOMPAT_RECOVER); ext3_commit_super(sb, EXT3_SB(sb)->s_es, 1); journal_unlock_updates(EXT3_SB(sb)->s_journal); } return 0; } static int ext3_remount (struct super_block * sb, int * flags, char * data) { struct ext3_super_block * es; struct ext3_sb_info *sbi = EXT3_SB(sb); ext3_fsblk_t n_blocks_count = 0; unsigned long old_sb_flags; struct ext3_mount_options old_opts; int enable_quota = 0; int err; #ifdef CONFIG_QUOTA int i; #endif /* Store the original options */ old_sb_flags = sb->s_flags; old_opts.s_mount_opt = sbi->s_mount_opt; old_opts.s_resuid = sbi->s_resuid; old_opts.s_resgid = sbi->s_resgid; old_opts.s_commit_interval = sbi->s_commit_interval; #ifdef CONFIG_QUOTA old_opts.s_jquota_fmt = sbi->s_jquota_fmt; for (i = 0; i < MAXQUOTAS; i++) if (sbi->s_qf_names[i]) { old_opts.s_qf_names[i] = kstrdup(sbi->s_qf_names[i], GFP_KERNEL); if (!old_opts.s_qf_names[i]) { int j; for (j = 0; j < i; j++) kfree(old_opts.s_qf_names[j]); return -ENOMEM; } } else old_opts.s_qf_names[i] = NULL; #endif /* * Allow the "check" option to be passed as a remount option. */ if (!parse_options(data, sb, NULL, NULL, &n_blocks_count, 1)) { err = -EINVAL; goto restore_opts; } if (test_opt(sb, ABORT)) ext3_abort(sb, __func__, "Abort forced by user"); sb->s_flags = (sb->s_flags & ~MS_POSIXACL) | (test_opt(sb, POSIX_ACL) ? MS_POSIXACL : 0); es = sbi->s_es; ext3_init_journal_params(sb, sbi->s_journal); if ((*flags & MS_RDONLY) != (sb->s_flags & MS_RDONLY) || n_blocks_count > le32_to_cpu(es->s_blocks_count)) { if (test_opt(sb, ABORT)) { err = -EROFS; goto restore_opts; } if (*flags & MS_RDONLY) { err = dquot_suspend(sb, -1); if (err < 0) goto restore_opts; /* * First of all, the unconditional stuff we have to do * to disable replay of the journal when we next remount */ sb->s_flags |= MS_RDONLY; /* * OK, test if we are remounting a valid rw partition * readonly, and if so set the rdonly flag and then * mark the partition as valid again. */ if (!(es->s_state & cpu_to_le16(EXT3_VALID_FS)) && (sbi->s_mount_state & EXT3_VALID_FS)) es->s_state = cpu_to_le16(sbi->s_mount_state); ext3_mark_recovery_complete(sb, es); } else { __le32 ret; if ((ret = EXT3_HAS_RO_COMPAT_FEATURE(sb, ~EXT3_FEATURE_RO_COMPAT_SUPP))) { ext3_msg(sb, KERN_WARNING, "warning: couldn't remount RDWR " "because of unsupported optional " "features (%x)", le32_to_cpu(ret)); err = -EROFS; goto restore_opts; } /* * If we have an unprocessed orphan list hanging * around from a previously readonly bdev mount, * require a full umount & mount for now. */ if (es->s_last_orphan) { ext3_msg(sb, KERN_WARNING, "warning: couldn't " "remount RDWR because of unprocessed " "orphan inode list. Please " "umount & mount instead."); err = -EINVAL; goto restore_opts; } /* * Mounting a RDONLY partition read-write, so reread * and store the current valid flag. (It may have * been changed by e2fsck since we originally mounted * the partition.) */ ext3_clear_journal_err(sb, es); sbi->s_mount_state = le16_to_cpu(es->s_state); if ((err = ext3_group_extend(sb, es, n_blocks_count))) goto restore_opts; if (!ext3_setup_super (sb, es, 0)) sb->s_flags &= ~MS_RDONLY; enable_quota = 1; } } #ifdef CONFIG_QUOTA /* Release old quota file names */ for (i = 0; i < MAXQUOTAS; i++) kfree(old_opts.s_qf_names[i]); #endif if (enable_quota) dquot_resume(sb, -1); return 0; restore_opts: sb->s_flags = old_sb_flags; sbi->s_mount_opt = old_opts.s_mount_opt; sbi->s_resuid = old_opts.s_resuid; sbi->s_resgid = old_opts.s_resgid; sbi->s_commit_interval = old_opts.s_commit_interval; #ifdef CONFIG_QUOTA sbi->s_jquota_fmt = old_opts.s_jquota_fmt; for (i = 0; i < MAXQUOTAS; i++) { kfree(sbi->s_qf_names[i]); sbi->s_qf_names[i] = old_opts.s_qf_names[i]; } #endif return err; } static int ext3_statfs (struct dentry * dentry, struct kstatfs * buf) { struct super_block *sb = dentry->d_sb; struct ext3_sb_info *sbi = EXT3_SB(sb); struct ext3_super_block *es = sbi->s_es; u64 fsid; if (test_opt(sb, MINIX_DF)) { sbi->s_overhead_last = 0; } else if (sbi->s_blocks_last != le32_to_cpu(es->s_blocks_count)) { unsigned long ngroups = sbi->s_groups_count, i; ext3_fsblk_t overhead = 0; smp_rmb(); /* * Compute the overhead (FS structures). This is constant * for a given filesystem unless the number of block groups * changes so we cache the previous value until it does. */ /* * All of the blocks before first_data_block are * overhead */ overhead = le32_to_cpu(es->s_first_data_block); /* * Add the overhead attributed to the superblock and * block group descriptors. If the sparse superblocks * feature is turned on, then not all groups have this. */ for (i = 0; i < ngroups; i++) { overhead += ext3_bg_has_super(sb, i) + ext3_bg_num_gdb(sb, i); cond_resched(); } /* * Every block group has an inode bitmap, a block * bitmap, and an inode table. */ overhead += ngroups * (2 + sbi->s_itb_per_group); sbi->s_overhead_last = overhead; smp_wmb(); sbi->s_blocks_last = le32_to_cpu(es->s_blocks_count); } buf->f_type = EXT3_SUPER_MAGIC; buf->f_bsize = sb->s_blocksize; buf->f_blocks = le32_to_cpu(es->s_blocks_count) - sbi->s_overhead_last; buf->f_bfree = percpu_counter_sum_positive(&sbi->s_freeblocks_counter); buf->f_bavail = buf->f_bfree - le32_to_cpu(es->s_r_blocks_count); if (buf->f_bfree < le32_to_cpu(es->s_r_blocks_count)) buf->f_bavail = 0; buf->f_files = le32_to_cpu(es->s_inodes_count); buf->f_ffree = percpu_counter_sum_positive(&sbi->s_freeinodes_counter); buf->f_namelen = EXT3_NAME_LEN; fsid = le64_to_cpup((void *)es->s_uuid) ^ le64_to_cpup((void *)es->s_uuid + sizeof(u64)); buf->f_fsid.val[0] = fsid & 0xFFFFFFFFUL; buf->f_fsid.val[1] = (fsid >> 32) & 0xFFFFFFFFUL; return 0; } /* Helper function for writing quotas on sync - we need to start transaction before quota file * is locked for write. Otherwise the are possible deadlocks: * Process 1 Process 2 * ext3_create() quota_sync() * journal_start() write_dquot() * dquot_initialize() down(dqio_mutex) * down(dqio_mutex) journal_start() * */ #ifdef CONFIG_QUOTA static inline struct inode *dquot_to_inode(struct dquot *dquot) { return sb_dqopt(dquot->dq_sb)->files[dquot->dq_id.type]; } static int ext3_write_dquot(struct dquot *dquot) { int ret, err; handle_t *handle; struct inode *inode; inode = dquot_to_inode(dquot); handle = ext3_journal_start(inode, EXT3_QUOTA_TRANS_BLOCKS(dquot->dq_sb)); if (IS_ERR(handle)) return PTR_ERR(handle); ret = dquot_commit(dquot); err = ext3_journal_stop(handle); if (!ret) ret = err; return ret; } static int ext3_acquire_dquot(struct dquot *dquot) { int ret, err; handle_t *handle; handle = ext3_journal_start(dquot_to_inode(dquot), EXT3_QUOTA_INIT_BLOCKS(dquot->dq_sb)); if (IS_ERR(handle)) return PTR_ERR(handle); ret = dquot_acquire(dquot); err = ext3_journal_stop(handle); if (!ret) ret = err; return ret; } static int ext3_release_dquot(struct dquot *dquot) { int ret, err; handle_t *handle; handle = ext3_journal_start(dquot_to_inode(dquot), EXT3_QUOTA_DEL_BLOCKS(dquot->dq_sb)); if (IS_ERR(handle)) { /* Release dquot anyway to avoid endless cycle in dqput() */ dquot_release(dquot); return PTR_ERR(handle); } ret = dquot_release(dquot); err = ext3_journal_stop(handle); if (!ret) ret = err; return ret; } static int ext3_mark_dquot_dirty(struct dquot *dquot) { /* Are we journaling quotas? */ if (EXT3_SB(dquot->dq_sb)->s_qf_names[USRQUOTA] || EXT3_SB(dquot->dq_sb)->s_qf_names[GRPQUOTA]) { dquot_mark_dquot_dirty(dquot); return ext3_write_dquot(dquot); } else { return dquot_mark_dquot_dirty(dquot); } } static int ext3_write_info(struct super_block *sb, int type) { int ret, err; handle_t *handle; /* Data block + inode block */ handle = ext3_journal_start(sb->s_root->d_inode, 2); if (IS_ERR(handle)) return PTR_ERR(handle); ret = dquot_commit_info(sb, type); err = ext3_journal_stop(handle); if (!ret) ret = err; return ret; } /* * Turn on quotas during mount time - we need to find * the quota file and such... */ static int ext3_quota_on_mount(struct super_block *sb, int type) { return dquot_quota_on_mount(sb, EXT3_SB(sb)->s_qf_names[type], EXT3_SB(sb)->s_jquota_fmt, type); } /* * Standard function to be called on quota_on */ static int ext3_quota_on(struct super_block *sb, int type, int format_id, struct path *path) { int err; if (!test_opt(sb, QUOTA)) return -EINVAL; /* Quotafile not on the same filesystem? */ if (path->dentry->d_sb != sb) return -EXDEV; /* Journaling quota? */ if (EXT3_SB(sb)->s_qf_names[type]) { /* Quotafile not of fs root? */ if (path->dentry->d_parent != sb->s_root) ext3_msg(sb, KERN_WARNING, "warning: Quota file not on filesystem root. " "Journaled quota will not work."); } /* * When we journal data on quota file, we have to flush journal to see * all updates to the file when we bypass pagecache... */ if (ext3_should_journal_data(path->dentry->d_inode)) { /* * We don't need to lock updates but journal_flush() could * otherwise be livelocked... */ journal_lock_updates(EXT3_SB(sb)->s_journal); err = journal_flush(EXT3_SB(sb)->s_journal); journal_unlock_updates(EXT3_SB(sb)->s_journal); if (err) return err; } return dquot_quota_on(sb, type, format_id, path); } /* Read data from quotafile - avoid pagecache and such because we cannot afford * acquiring the locks... As quota files are never truncated and quota code * itself serializes the operations (and no one else should touch the files) * we don't have to be afraid of races */ static ssize_t ext3_quota_read(struct super_block *sb, int type, char *data, size_t len, loff_t off) { struct inode *inode = sb_dqopt(sb)->files[type]; sector_t blk = off >> EXT3_BLOCK_SIZE_BITS(sb); int err = 0; int offset = off & (sb->s_blocksize - 1); int tocopy; size_t toread; struct buffer_head *bh; loff_t i_size = i_size_read(inode); if (off > i_size) return 0; if (off+len > i_size) len = i_size-off; toread = len; while (toread > 0) { tocopy = sb->s_blocksize - offset < toread ? sb->s_blocksize - offset : toread; bh = ext3_bread(NULL, inode, blk, 0, &err); if (err) return err; if (!bh) /* A hole? */ memset(data, 0, tocopy); else memcpy(data, bh->b_data+offset, tocopy); brelse(bh); offset = 0; toread -= tocopy; data += tocopy; blk++; } return len; } /* Write to quotafile (we know the transaction is already started and has * enough credits) */ static ssize_t ext3_quota_write(struct super_block *sb, int type, const char *data, size_t len, loff_t off) { struct inode *inode = sb_dqopt(sb)->files[type]; sector_t blk = off >> EXT3_BLOCK_SIZE_BITS(sb); int err = 0; int offset = off & (sb->s_blocksize - 1); int journal_quota = EXT3_SB(sb)->s_qf_names[type] != NULL; struct buffer_head *bh; handle_t *handle = journal_current_handle(); if (!handle) { ext3_msg(sb, KERN_WARNING, "warning: quota write (off=%llu, len=%llu)" " cancelled because transaction is not started.", (unsigned long long)off, (unsigned long long)len); return -EIO; } /* * Since we account only one data block in transaction credits, * then it is impossible to cross a block boundary. */ if (sb->s_blocksize - offset < len) { ext3_msg(sb, KERN_WARNING, "Quota write (off=%llu, len=%llu)" " cancelled because not block aligned", (unsigned long long)off, (unsigned long long)len); return -EIO; } bh = ext3_bread(handle, inode, blk, 1, &err); if (!bh) goto out; if (journal_quota) { err = ext3_journal_get_write_access(handle, bh); if (err) { brelse(bh); goto out; } } lock_buffer(bh); memcpy(bh->b_data+offset, data, len); flush_dcache_page(bh->b_page); unlock_buffer(bh); if (journal_quota) err = ext3_journal_dirty_metadata(handle, bh); else { /* Always do at least ordered writes for quotas */ err = ext3_journal_dirty_data(handle, bh); mark_buffer_dirty(bh); } brelse(bh); out: if (err) return err; if (inode->i_size < off + len) { i_size_write(inode, off + len); EXT3_I(inode)->i_disksize = inode->i_size; } inode->i_version++; inode->i_mtime = inode->i_ctime = CURRENT_TIME; ext3_mark_inode_dirty(handle, inode); return len; } #endif static struct dentry *ext3_mount(struct file_system_type *fs_type, int flags, const char *dev_name, void *data) { return mount_bdev(fs_type, flags, dev_name, data, ext3_fill_super); } static struct file_system_type ext3_fs_type = { .owner = THIS_MODULE, .name = "ext3", .mount = ext3_mount, .kill_sb = kill_block_super, .fs_flags = FS_REQUIRES_DEV, }; MODULE_ALIAS_FS("ext3"); static int __init init_ext3_fs(void) { int err = init_ext3_xattr(); if (err) return err; err = init_inodecache(); if (err) goto out1; err = register_filesystem(&ext3_fs_type); if (err) goto out; return 0; out: destroy_inodecache(); out1: exit_ext3_xattr(); return err; } static void __exit exit_ext3_fs(void) { unregister_filesystem(&ext3_fs_type); destroy_inodecache(); exit_ext3_xattr(); } MODULE_AUTHOR("Remy Card, Stephen Tweedie, Andrew Morton, Andreas Dilger, Theodore Ts'o and others"); MODULE_DESCRIPTION("Second Extended Filesystem with journaling extensions"); MODULE_LICENSE("GPL"); module_init(init_ext3_fs) module_exit(exit_ext3_fs)
./CrossVul/dataset_final_sorted/CWE-20/c/good_5604_0
crossvul-cpp_data_bad_5845_17
/* * IUCV protocol stack for Linux on zSeries * * Copyright IBM Corp. 2006, 2009 * * Author(s): Jennifer Hunt <jenhunt@us.ibm.com> * Hendrik Brueckner <brueckner@linux.vnet.ibm.com> * PM functions: * Ursula Braun <ursula.braun@de.ibm.com> */ #define KMSG_COMPONENT "af_iucv" #define pr_fmt(fmt) KMSG_COMPONENT ": " fmt #include <linux/module.h> #include <linux/types.h> #include <linux/list.h> #include <linux/errno.h> #include <linux/kernel.h> #include <linux/sched.h> #include <linux/slab.h> #include <linux/skbuff.h> #include <linux/init.h> #include <linux/poll.h> #include <net/sock.h> #include <asm/ebcdic.h> #include <asm/cpcmd.h> #include <linux/kmod.h> #include <net/iucv/af_iucv.h> #define VERSION "1.2" static char iucv_userid[80]; static const struct proto_ops iucv_sock_ops; static struct proto iucv_proto = { .name = "AF_IUCV", .owner = THIS_MODULE, .obj_size = sizeof(struct iucv_sock), }; static struct iucv_interface *pr_iucv; /* special AF_IUCV IPRM messages */ static const u8 iprm_shutdown[8] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01}; #define TRGCLS_SIZE (sizeof(((struct iucv_message *)0)->class)) #define __iucv_sock_wait(sk, condition, timeo, ret) \ do { \ DEFINE_WAIT(__wait); \ long __timeo = timeo; \ ret = 0; \ prepare_to_wait(sk_sleep(sk), &__wait, TASK_INTERRUPTIBLE); \ while (!(condition)) { \ if (!__timeo) { \ ret = -EAGAIN; \ break; \ } \ if (signal_pending(current)) { \ ret = sock_intr_errno(__timeo); \ break; \ } \ release_sock(sk); \ __timeo = schedule_timeout(__timeo); \ lock_sock(sk); \ ret = sock_error(sk); \ if (ret) \ break; \ } \ finish_wait(sk_sleep(sk), &__wait); \ } while (0) #define iucv_sock_wait(sk, condition, timeo) \ ({ \ int __ret = 0; \ if (!(condition)) \ __iucv_sock_wait(sk, condition, timeo, __ret); \ __ret; \ }) static void iucv_sock_kill(struct sock *sk); static void iucv_sock_close(struct sock *sk); static void iucv_sever_path(struct sock *, int); static int afiucv_hs_rcv(struct sk_buff *skb, struct net_device *dev, struct packet_type *pt, struct net_device *orig_dev); static int afiucv_hs_send(struct iucv_message *imsg, struct sock *sock, struct sk_buff *skb, u8 flags); static void afiucv_hs_callback_txnotify(struct sk_buff *, enum iucv_tx_notify); /* Call Back functions */ static void iucv_callback_rx(struct iucv_path *, struct iucv_message *); static void iucv_callback_txdone(struct iucv_path *, struct iucv_message *); static void iucv_callback_connack(struct iucv_path *, u8 ipuser[16]); static int iucv_callback_connreq(struct iucv_path *, u8 ipvmid[8], u8 ipuser[16]); static void iucv_callback_connrej(struct iucv_path *, u8 ipuser[16]); static void iucv_callback_shutdown(struct iucv_path *, u8 ipuser[16]); static struct iucv_sock_list iucv_sk_list = { .lock = __RW_LOCK_UNLOCKED(iucv_sk_list.lock), .autobind_name = ATOMIC_INIT(0) }; static struct iucv_handler af_iucv_handler = { .path_pending = iucv_callback_connreq, .path_complete = iucv_callback_connack, .path_severed = iucv_callback_connrej, .message_pending = iucv_callback_rx, .message_complete = iucv_callback_txdone, .path_quiesced = iucv_callback_shutdown, }; static inline void high_nmcpy(unsigned char *dst, char *src) { memcpy(dst, src, 8); } static inline void low_nmcpy(unsigned char *dst, char *src) { memcpy(&dst[8], src, 8); } static int afiucv_pm_prepare(struct device *dev) { #ifdef CONFIG_PM_DEBUG printk(KERN_WARNING "afiucv_pm_prepare\n"); #endif return 0; } static void afiucv_pm_complete(struct device *dev) { #ifdef CONFIG_PM_DEBUG printk(KERN_WARNING "afiucv_pm_complete\n"); #endif } /** * afiucv_pm_freeze() - Freeze PM callback * @dev: AFIUCV dummy device * * Sever all established IUCV communication pathes */ static int afiucv_pm_freeze(struct device *dev) { struct iucv_sock *iucv; struct sock *sk; int err = 0; #ifdef CONFIG_PM_DEBUG printk(KERN_WARNING "afiucv_pm_freeze\n"); #endif read_lock(&iucv_sk_list.lock); sk_for_each(sk, &iucv_sk_list.head) { iucv = iucv_sk(sk); switch (sk->sk_state) { case IUCV_DISCONN: case IUCV_CLOSING: case IUCV_CONNECTED: iucv_sever_path(sk, 0); break; case IUCV_OPEN: case IUCV_BOUND: case IUCV_LISTEN: case IUCV_CLOSED: default: break; } skb_queue_purge(&iucv->send_skb_q); skb_queue_purge(&iucv->backlog_skb_q); } read_unlock(&iucv_sk_list.lock); return err; } /** * afiucv_pm_restore_thaw() - Thaw and restore PM callback * @dev: AFIUCV dummy device * * socket clean up after freeze */ static int afiucv_pm_restore_thaw(struct device *dev) { struct sock *sk; #ifdef CONFIG_PM_DEBUG printk(KERN_WARNING "afiucv_pm_restore_thaw\n"); #endif read_lock(&iucv_sk_list.lock); sk_for_each(sk, &iucv_sk_list.head) { switch (sk->sk_state) { case IUCV_CONNECTED: sk->sk_err = EPIPE; sk->sk_state = IUCV_DISCONN; sk->sk_state_change(sk); break; case IUCV_DISCONN: case IUCV_CLOSING: case IUCV_LISTEN: case IUCV_BOUND: case IUCV_OPEN: default: break; } } read_unlock(&iucv_sk_list.lock); return 0; } static const struct dev_pm_ops afiucv_pm_ops = { .prepare = afiucv_pm_prepare, .complete = afiucv_pm_complete, .freeze = afiucv_pm_freeze, .thaw = afiucv_pm_restore_thaw, .restore = afiucv_pm_restore_thaw, }; static struct device_driver af_iucv_driver = { .owner = THIS_MODULE, .name = "afiucv", .bus = NULL, .pm = &afiucv_pm_ops, }; /* dummy device used as trigger for PM functions */ static struct device *af_iucv_dev; /** * iucv_msg_length() - Returns the length of an iucv message. * @msg: Pointer to struct iucv_message, MUST NOT be NULL * * The function returns the length of the specified iucv message @msg of data * stored in a buffer and of data stored in the parameter list (PRMDATA). * * For IUCV_IPRMDATA, AF_IUCV uses the following convention to transport socket * data: * PRMDATA[0..6] socket data (max 7 bytes); * PRMDATA[7] socket data length value (len is 0xff - PRMDATA[7]) * * The socket data length is computed by subtracting the socket data length * value from 0xFF. * If the socket data len is greater 7, then PRMDATA can be used for special * notifications (see iucv_sock_shutdown); and further, * if the socket data len is > 7, the function returns 8. * * Use this function to allocate socket buffers to store iucv message data. */ static inline size_t iucv_msg_length(struct iucv_message *msg) { size_t datalen; if (msg->flags & IUCV_IPRMDATA) { datalen = 0xff - msg->rmmsg[7]; return (datalen < 8) ? datalen : 8; } return msg->length; } /** * iucv_sock_in_state() - check for specific states * @sk: sock structure * @state: first iucv sk state * @state: second iucv sk state * * Returns true if the socket in either in the first or second state. */ static int iucv_sock_in_state(struct sock *sk, int state, int state2) { return (sk->sk_state == state || sk->sk_state == state2); } /** * iucv_below_msglim() - function to check if messages can be sent * @sk: sock structure * * Returns true if the send queue length is lower than the message limit. * Always returns true if the socket is not connected (no iucv path for * checking the message limit). */ static inline int iucv_below_msglim(struct sock *sk) { struct iucv_sock *iucv = iucv_sk(sk); if (sk->sk_state != IUCV_CONNECTED) return 1; if (iucv->transport == AF_IUCV_TRANS_IUCV) return (skb_queue_len(&iucv->send_skb_q) < iucv->path->msglim); else return ((atomic_read(&iucv->msg_sent) < iucv->msglimit_peer) && (atomic_read(&iucv->pendings) <= 0)); } /** * iucv_sock_wake_msglim() - Wake up thread waiting on msg limit */ static void iucv_sock_wake_msglim(struct sock *sk) { struct socket_wq *wq; rcu_read_lock(); wq = rcu_dereference(sk->sk_wq); if (wq_has_sleeper(wq)) wake_up_interruptible_all(&wq->wait); sk_wake_async(sk, SOCK_WAKE_SPACE, POLL_OUT); rcu_read_unlock(); } /** * afiucv_hs_send() - send a message through HiperSockets transport */ static int afiucv_hs_send(struct iucv_message *imsg, struct sock *sock, struct sk_buff *skb, u8 flags) { struct iucv_sock *iucv = iucv_sk(sock); struct af_iucv_trans_hdr *phs_hdr; struct sk_buff *nskb; int err, confirm_recv = 0; memset(skb->head, 0, ETH_HLEN); phs_hdr = (struct af_iucv_trans_hdr *)skb_push(skb, sizeof(struct af_iucv_trans_hdr)); skb_reset_mac_header(skb); skb_reset_network_header(skb); skb_push(skb, ETH_HLEN); skb_reset_mac_header(skb); memset(phs_hdr, 0, sizeof(struct af_iucv_trans_hdr)); phs_hdr->magic = ETH_P_AF_IUCV; phs_hdr->version = 1; phs_hdr->flags = flags; if (flags == AF_IUCV_FLAG_SYN) phs_hdr->window = iucv->msglimit; else if ((flags == AF_IUCV_FLAG_WIN) || !flags) { confirm_recv = atomic_read(&iucv->msg_recv); phs_hdr->window = confirm_recv; if (confirm_recv) phs_hdr->flags = phs_hdr->flags | AF_IUCV_FLAG_WIN; } memcpy(phs_hdr->destUserID, iucv->dst_user_id, 8); memcpy(phs_hdr->destAppName, iucv->dst_name, 8); memcpy(phs_hdr->srcUserID, iucv->src_user_id, 8); memcpy(phs_hdr->srcAppName, iucv->src_name, 8); ASCEBC(phs_hdr->destUserID, sizeof(phs_hdr->destUserID)); ASCEBC(phs_hdr->destAppName, sizeof(phs_hdr->destAppName)); ASCEBC(phs_hdr->srcUserID, sizeof(phs_hdr->srcUserID)); ASCEBC(phs_hdr->srcAppName, sizeof(phs_hdr->srcAppName)); if (imsg) memcpy(&phs_hdr->iucv_hdr, imsg, sizeof(struct iucv_message)); skb->dev = iucv->hs_dev; if (!skb->dev) return -ENODEV; if (!(skb->dev->flags & IFF_UP) || !netif_carrier_ok(skb->dev)) return -ENETDOWN; if (skb->len > skb->dev->mtu) { if (sock->sk_type == SOCK_SEQPACKET) return -EMSGSIZE; else skb_trim(skb, skb->dev->mtu); } skb->protocol = ETH_P_AF_IUCV; nskb = skb_clone(skb, GFP_ATOMIC); if (!nskb) return -ENOMEM; skb_queue_tail(&iucv->send_skb_q, nskb); err = dev_queue_xmit(skb); if (net_xmit_eval(err)) { skb_unlink(nskb, &iucv->send_skb_q); kfree_skb(nskb); } else { atomic_sub(confirm_recv, &iucv->msg_recv); WARN_ON(atomic_read(&iucv->msg_recv) < 0); } return net_xmit_eval(err); } static struct sock *__iucv_get_sock_by_name(char *nm) { struct sock *sk; sk_for_each(sk, &iucv_sk_list.head) if (!memcmp(&iucv_sk(sk)->src_name, nm, 8)) return sk; return NULL; } static void iucv_sock_destruct(struct sock *sk) { skb_queue_purge(&sk->sk_receive_queue); skb_queue_purge(&sk->sk_error_queue); sk_mem_reclaim(sk); if (!sock_flag(sk, SOCK_DEAD)) { pr_err("Attempt to release alive iucv socket %p\n", sk); return; } WARN_ON(atomic_read(&sk->sk_rmem_alloc)); WARN_ON(atomic_read(&sk->sk_wmem_alloc)); WARN_ON(sk->sk_wmem_queued); WARN_ON(sk->sk_forward_alloc); } /* Cleanup Listen */ static void iucv_sock_cleanup_listen(struct sock *parent) { struct sock *sk; /* Close non-accepted connections */ while ((sk = iucv_accept_dequeue(parent, NULL))) { iucv_sock_close(sk); iucv_sock_kill(sk); } parent->sk_state = IUCV_CLOSED; } /* Kill socket (only if zapped and orphaned) */ static void iucv_sock_kill(struct sock *sk) { if (!sock_flag(sk, SOCK_ZAPPED) || sk->sk_socket) return; iucv_sock_unlink(&iucv_sk_list, sk); sock_set_flag(sk, SOCK_DEAD); sock_put(sk); } /* Terminate an IUCV path */ static void iucv_sever_path(struct sock *sk, int with_user_data) { unsigned char user_data[16]; struct iucv_sock *iucv = iucv_sk(sk); struct iucv_path *path = iucv->path; if (iucv->path) { iucv->path = NULL; if (with_user_data) { low_nmcpy(user_data, iucv->src_name); high_nmcpy(user_data, iucv->dst_name); ASCEBC(user_data, sizeof(user_data)); pr_iucv->path_sever(path, user_data); } else pr_iucv->path_sever(path, NULL); iucv_path_free(path); } } /* Send FIN through an IUCV socket for HIPER transport */ static int iucv_send_ctrl(struct sock *sk, u8 flags) { int err = 0; int blen; struct sk_buff *skb; blen = sizeof(struct af_iucv_trans_hdr) + ETH_HLEN; skb = sock_alloc_send_skb(sk, blen, 1, &err); if (skb) { skb_reserve(skb, blen); err = afiucv_hs_send(NULL, sk, skb, flags); } return err; } /* Close an IUCV socket */ static void iucv_sock_close(struct sock *sk) { struct iucv_sock *iucv = iucv_sk(sk); unsigned long timeo; int err = 0; lock_sock(sk); switch (sk->sk_state) { case IUCV_LISTEN: iucv_sock_cleanup_listen(sk); break; case IUCV_CONNECTED: if (iucv->transport == AF_IUCV_TRANS_HIPER) { err = iucv_send_ctrl(sk, AF_IUCV_FLAG_FIN); sk->sk_state = IUCV_DISCONN; sk->sk_state_change(sk); } case IUCV_DISCONN: /* fall through */ sk->sk_state = IUCV_CLOSING; sk->sk_state_change(sk); if (!err && !skb_queue_empty(&iucv->send_skb_q)) { if (sock_flag(sk, SOCK_LINGER) && sk->sk_lingertime) timeo = sk->sk_lingertime; else timeo = IUCV_DISCONN_TIMEOUT; iucv_sock_wait(sk, iucv_sock_in_state(sk, IUCV_CLOSED, 0), timeo); } case IUCV_CLOSING: /* fall through */ sk->sk_state = IUCV_CLOSED; sk->sk_state_change(sk); sk->sk_err = ECONNRESET; sk->sk_state_change(sk); skb_queue_purge(&iucv->send_skb_q); skb_queue_purge(&iucv->backlog_skb_q); default: /* fall through */ iucv_sever_path(sk, 1); } if (iucv->hs_dev) { dev_put(iucv->hs_dev); iucv->hs_dev = NULL; sk->sk_bound_dev_if = 0; } /* mark socket for deletion by iucv_sock_kill() */ sock_set_flag(sk, SOCK_ZAPPED); release_sock(sk); } static void iucv_sock_init(struct sock *sk, struct sock *parent) { if (parent) sk->sk_type = parent->sk_type; } static struct sock *iucv_sock_alloc(struct socket *sock, int proto, gfp_t prio) { struct sock *sk; struct iucv_sock *iucv; sk = sk_alloc(&init_net, PF_IUCV, prio, &iucv_proto); if (!sk) return NULL; iucv = iucv_sk(sk); sock_init_data(sock, sk); INIT_LIST_HEAD(&iucv->accept_q); spin_lock_init(&iucv->accept_q_lock); skb_queue_head_init(&iucv->send_skb_q); INIT_LIST_HEAD(&iucv->message_q.list); spin_lock_init(&iucv->message_q.lock); skb_queue_head_init(&iucv->backlog_skb_q); iucv->send_tag = 0; atomic_set(&iucv->pendings, 0); iucv->flags = 0; iucv->msglimit = 0; atomic_set(&iucv->msg_sent, 0); atomic_set(&iucv->msg_recv, 0); iucv->path = NULL; iucv->sk_txnotify = afiucv_hs_callback_txnotify; memset(&iucv->src_user_id , 0, 32); if (pr_iucv) iucv->transport = AF_IUCV_TRANS_IUCV; else iucv->transport = AF_IUCV_TRANS_HIPER; sk->sk_destruct = iucv_sock_destruct; sk->sk_sndtimeo = IUCV_CONN_TIMEOUT; sk->sk_allocation = GFP_DMA; sock_reset_flag(sk, SOCK_ZAPPED); sk->sk_protocol = proto; sk->sk_state = IUCV_OPEN; iucv_sock_link(&iucv_sk_list, sk); return sk; } /* Create an IUCV socket */ static int iucv_sock_create(struct net *net, struct socket *sock, int protocol, int kern) { struct sock *sk; if (protocol && protocol != PF_IUCV) return -EPROTONOSUPPORT; sock->state = SS_UNCONNECTED; switch (sock->type) { case SOCK_STREAM: sock->ops = &iucv_sock_ops; break; case SOCK_SEQPACKET: /* currently, proto ops can handle both sk types */ sock->ops = &iucv_sock_ops; break; default: return -ESOCKTNOSUPPORT; } sk = iucv_sock_alloc(sock, protocol, GFP_KERNEL); if (!sk) return -ENOMEM; iucv_sock_init(sk, NULL); return 0; } void iucv_sock_link(struct iucv_sock_list *l, struct sock *sk) { write_lock_bh(&l->lock); sk_add_node(sk, &l->head); write_unlock_bh(&l->lock); } void iucv_sock_unlink(struct iucv_sock_list *l, struct sock *sk) { write_lock_bh(&l->lock); sk_del_node_init(sk); write_unlock_bh(&l->lock); } void iucv_accept_enqueue(struct sock *parent, struct sock *sk) { unsigned long flags; struct iucv_sock *par = iucv_sk(parent); sock_hold(sk); spin_lock_irqsave(&par->accept_q_lock, flags); list_add_tail(&iucv_sk(sk)->accept_q, &par->accept_q); spin_unlock_irqrestore(&par->accept_q_lock, flags); iucv_sk(sk)->parent = parent; sk_acceptq_added(parent); } void iucv_accept_unlink(struct sock *sk) { unsigned long flags; struct iucv_sock *par = iucv_sk(iucv_sk(sk)->parent); spin_lock_irqsave(&par->accept_q_lock, flags); list_del_init(&iucv_sk(sk)->accept_q); spin_unlock_irqrestore(&par->accept_q_lock, flags); sk_acceptq_removed(iucv_sk(sk)->parent); iucv_sk(sk)->parent = NULL; sock_put(sk); } struct sock *iucv_accept_dequeue(struct sock *parent, struct socket *newsock) { struct iucv_sock *isk, *n; struct sock *sk; list_for_each_entry_safe(isk, n, &iucv_sk(parent)->accept_q, accept_q) { sk = (struct sock *) isk; lock_sock(sk); if (sk->sk_state == IUCV_CLOSED) { iucv_accept_unlink(sk); release_sock(sk); continue; } if (sk->sk_state == IUCV_CONNECTED || sk->sk_state == IUCV_DISCONN || !newsock) { iucv_accept_unlink(sk); if (newsock) sock_graft(sk, newsock); release_sock(sk); return sk; } release_sock(sk); } return NULL; } /* Bind an unbound socket */ static int iucv_sock_bind(struct socket *sock, struct sockaddr *addr, int addr_len) { struct sockaddr_iucv *sa = (struct sockaddr_iucv *) addr; struct sock *sk = sock->sk; struct iucv_sock *iucv; int err = 0; struct net_device *dev; char uid[9]; /* Verify the input sockaddr */ if (!addr || addr->sa_family != AF_IUCV) return -EINVAL; lock_sock(sk); if (sk->sk_state != IUCV_OPEN) { err = -EBADFD; goto done; } write_lock_bh(&iucv_sk_list.lock); iucv = iucv_sk(sk); if (__iucv_get_sock_by_name(sa->siucv_name)) { err = -EADDRINUSE; goto done_unlock; } if (iucv->path) goto done_unlock; /* Bind the socket */ if (pr_iucv) if (!memcmp(sa->siucv_user_id, iucv_userid, 8)) goto vm_bind; /* VM IUCV transport */ /* try hiper transport */ memcpy(uid, sa->siucv_user_id, sizeof(uid)); ASCEBC(uid, 8); rcu_read_lock(); for_each_netdev_rcu(&init_net, dev) { if (!memcmp(dev->perm_addr, uid, 8)) { memcpy(iucv->src_name, sa->siucv_name, 8); memcpy(iucv->src_user_id, sa->siucv_user_id, 8); sk->sk_bound_dev_if = dev->ifindex; iucv->hs_dev = dev; dev_hold(dev); sk->sk_state = IUCV_BOUND; iucv->transport = AF_IUCV_TRANS_HIPER; if (!iucv->msglimit) iucv->msglimit = IUCV_HIPER_MSGLIM_DEFAULT; rcu_read_unlock(); goto done_unlock; } } rcu_read_unlock(); vm_bind: if (pr_iucv) { /* use local userid for backward compat */ memcpy(iucv->src_name, sa->siucv_name, 8); memcpy(iucv->src_user_id, iucv_userid, 8); sk->sk_state = IUCV_BOUND; iucv->transport = AF_IUCV_TRANS_IUCV; if (!iucv->msglimit) iucv->msglimit = IUCV_QUEUELEN_DEFAULT; goto done_unlock; } /* found no dev to bind */ err = -ENODEV; done_unlock: /* Release the socket list lock */ write_unlock_bh(&iucv_sk_list.lock); done: release_sock(sk); return err; } /* Automatically bind an unbound socket */ static int iucv_sock_autobind(struct sock *sk) { struct iucv_sock *iucv = iucv_sk(sk); char name[12]; int err = 0; if (unlikely(!pr_iucv)) return -EPROTO; memcpy(iucv->src_user_id, iucv_userid, 8); write_lock_bh(&iucv_sk_list.lock); sprintf(name, "%08x", atomic_inc_return(&iucv_sk_list.autobind_name)); while (__iucv_get_sock_by_name(name)) { sprintf(name, "%08x", atomic_inc_return(&iucv_sk_list.autobind_name)); } write_unlock_bh(&iucv_sk_list.lock); memcpy(&iucv->src_name, name, 8); if (!iucv->msglimit) iucv->msglimit = IUCV_QUEUELEN_DEFAULT; return err; } static int afiucv_path_connect(struct socket *sock, struct sockaddr *addr) { struct sockaddr_iucv *sa = (struct sockaddr_iucv *) addr; struct sock *sk = sock->sk; struct iucv_sock *iucv = iucv_sk(sk); unsigned char user_data[16]; int err; high_nmcpy(user_data, sa->siucv_name); low_nmcpy(user_data, iucv->src_name); ASCEBC(user_data, sizeof(user_data)); /* Create path. */ iucv->path = iucv_path_alloc(iucv->msglimit, IUCV_IPRMDATA, GFP_KERNEL); if (!iucv->path) { err = -ENOMEM; goto done; } err = pr_iucv->path_connect(iucv->path, &af_iucv_handler, sa->siucv_user_id, NULL, user_data, sk); if (err) { iucv_path_free(iucv->path); iucv->path = NULL; switch (err) { case 0x0b: /* Target communicator is not logged on */ err = -ENETUNREACH; break; case 0x0d: /* Max connections for this guest exceeded */ case 0x0e: /* Max connections for target guest exceeded */ err = -EAGAIN; break; case 0x0f: /* Missing IUCV authorization */ err = -EACCES; break; default: err = -ECONNREFUSED; break; } } done: return err; } /* Connect an unconnected socket */ static int iucv_sock_connect(struct socket *sock, struct sockaddr *addr, int alen, int flags) { struct sockaddr_iucv *sa = (struct sockaddr_iucv *) addr; struct sock *sk = sock->sk; struct iucv_sock *iucv = iucv_sk(sk); int err; if (addr->sa_family != AF_IUCV || alen < sizeof(struct sockaddr_iucv)) return -EINVAL; if (sk->sk_state != IUCV_OPEN && sk->sk_state != IUCV_BOUND) return -EBADFD; if (sk->sk_state == IUCV_OPEN && iucv->transport == AF_IUCV_TRANS_HIPER) return -EBADFD; /* explicit bind required */ if (sk->sk_type != SOCK_STREAM && sk->sk_type != SOCK_SEQPACKET) return -EINVAL; if (sk->sk_state == IUCV_OPEN) { err = iucv_sock_autobind(sk); if (unlikely(err)) return err; } lock_sock(sk); /* Set the destination information */ memcpy(iucv->dst_user_id, sa->siucv_user_id, 8); memcpy(iucv->dst_name, sa->siucv_name, 8); if (iucv->transport == AF_IUCV_TRANS_HIPER) err = iucv_send_ctrl(sock->sk, AF_IUCV_FLAG_SYN); else err = afiucv_path_connect(sock, addr); if (err) goto done; if (sk->sk_state != IUCV_CONNECTED) err = iucv_sock_wait(sk, iucv_sock_in_state(sk, IUCV_CONNECTED, IUCV_DISCONN), sock_sndtimeo(sk, flags & O_NONBLOCK)); if (sk->sk_state == IUCV_DISCONN || sk->sk_state == IUCV_CLOSED) err = -ECONNREFUSED; if (err && iucv->transport == AF_IUCV_TRANS_IUCV) iucv_sever_path(sk, 0); done: release_sock(sk); return err; } /* Move a socket into listening state. */ static int iucv_sock_listen(struct socket *sock, int backlog) { struct sock *sk = sock->sk; int err; lock_sock(sk); err = -EINVAL; if (sk->sk_state != IUCV_BOUND) goto done; if (sock->type != SOCK_STREAM && sock->type != SOCK_SEQPACKET) goto done; sk->sk_max_ack_backlog = backlog; sk->sk_ack_backlog = 0; sk->sk_state = IUCV_LISTEN; err = 0; done: release_sock(sk); return err; } /* Accept a pending connection */ static int iucv_sock_accept(struct socket *sock, struct socket *newsock, int flags) { DECLARE_WAITQUEUE(wait, current); struct sock *sk = sock->sk, *nsk; long timeo; int err = 0; lock_sock_nested(sk, SINGLE_DEPTH_NESTING); if (sk->sk_state != IUCV_LISTEN) { err = -EBADFD; goto done; } timeo = sock_rcvtimeo(sk, flags & O_NONBLOCK); /* Wait for an incoming connection */ add_wait_queue_exclusive(sk_sleep(sk), &wait); while (!(nsk = iucv_accept_dequeue(sk, newsock))) { set_current_state(TASK_INTERRUPTIBLE); if (!timeo) { err = -EAGAIN; break; } release_sock(sk); timeo = schedule_timeout(timeo); lock_sock_nested(sk, SINGLE_DEPTH_NESTING); if (sk->sk_state != IUCV_LISTEN) { err = -EBADFD; break; } if (signal_pending(current)) { err = sock_intr_errno(timeo); break; } } set_current_state(TASK_RUNNING); remove_wait_queue(sk_sleep(sk), &wait); if (err) goto done; newsock->state = SS_CONNECTED; done: release_sock(sk); return err; } static int iucv_sock_getname(struct socket *sock, struct sockaddr *addr, int *len, int peer) { struct sockaddr_iucv *siucv = (struct sockaddr_iucv *) addr; struct sock *sk = sock->sk; struct iucv_sock *iucv = iucv_sk(sk); addr->sa_family = AF_IUCV; *len = sizeof(struct sockaddr_iucv); if (peer) { memcpy(siucv->siucv_user_id, iucv->dst_user_id, 8); memcpy(siucv->siucv_name, iucv->dst_name, 8); } else { memcpy(siucv->siucv_user_id, iucv->src_user_id, 8); memcpy(siucv->siucv_name, iucv->src_name, 8); } memset(&siucv->siucv_port, 0, sizeof(siucv->siucv_port)); memset(&siucv->siucv_addr, 0, sizeof(siucv->siucv_addr)); memset(&siucv->siucv_nodeid, 0, sizeof(siucv->siucv_nodeid)); return 0; } /** * iucv_send_iprm() - Send socket data in parameter list of an iucv message. * @path: IUCV path * @msg: Pointer to a struct iucv_message * @skb: The socket data to send, skb->len MUST BE <= 7 * * Send the socket data in the parameter list in the iucv message * (IUCV_IPRMDATA). The socket data is stored at index 0 to 6 in the parameter * list and the socket data len at index 7 (last byte). * See also iucv_msg_length(). * * Returns the error code from the iucv_message_send() call. */ static int iucv_send_iprm(struct iucv_path *path, struct iucv_message *msg, struct sk_buff *skb) { u8 prmdata[8]; memcpy(prmdata, (void *) skb->data, skb->len); prmdata[7] = 0xff - (u8) skb->len; return pr_iucv->message_send(path, msg, IUCV_IPRMDATA, 0, (void *) prmdata, 8); } static int iucv_sock_sendmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t len) { struct sock *sk = sock->sk; struct iucv_sock *iucv = iucv_sk(sk); struct sk_buff *skb; struct iucv_message txmsg; struct cmsghdr *cmsg; int cmsg_done; long timeo; char user_id[9]; char appl_id[9]; int err; int noblock = msg->msg_flags & MSG_DONTWAIT; err = sock_error(sk); if (err) return err; if (msg->msg_flags & MSG_OOB) return -EOPNOTSUPP; /* SOCK_SEQPACKET: we do not support segmented records */ if (sk->sk_type == SOCK_SEQPACKET && !(msg->msg_flags & MSG_EOR)) return -EOPNOTSUPP; lock_sock(sk); if (sk->sk_shutdown & SEND_SHUTDOWN) { err = -EPIPE; goto out; } /* Return if the socket is not in connected state */ if (sk->sk_state != IUCV_CONNECTED) { err = -ENOTCONN; goto out; } /* initialize defaults */ cmsg_done = 0; /* check for duplicate headers */ txmsg.class = 0; /* iterate over control messages */ for (cmsg = CMSG_FIRSTHDR(msg); cmsg; cmsg = CMSG_NXTHDR(msg, cmsg)) { if (!CMSG_OK(msg, cmsg)) { err = -EINVAL; goto out; } if (cmsg->cmsg_level != SOL_IUCV) continue; if (cmsg->cmsg_type & cmsg_done) { err = -EINVAL; goto out; } cmsg_done |= cmsg->cmsg_type; switch (cmsg->cmsg_type) { case SCM_IUCV_TRGCLS: if (cmsg->cmsg_len != CMSG_LEN(TRGCLS_SIZE)) { err = -EINVAL; goto out; } /* set iucv message target class */ memcpy(&txmsg.class, (void *) CMSG_DATA(cmsg), TRGCLS_SIZE); break; default: err = -EINVAL; goto out; break; } } /* allocate one skb for each iucv message: * this is fine for SOCK_SEQPACKET (unless we want to support * segmented records using the MSG_EOR flag), but * for SOCK_STREAM we might want to improve it in future */ if (iucv->transport == AF_IUCV_TRANS_HIPER) skb = sock_alloc_send_skb(sk, len + sizeof(struct af_iucv_trans_hdr) + ETH_HLEN, noblock, &err); else skb = sock_alloc_send_skb(sk, len, noblock, &err); if (!skb) { err = -ENOMEM; goto out; } if (iucv->transport == AF_IUCV_TRANS_HIPER) skb_reserve(skb, sizeof(struct af_iucv_trans_hdr) + ETH_HLEN); if (memcpy_fromiovec(skb_put(skb, len), msg->msg_iov, len)) { err = -EFAULT; goto fail; } /* wait if outstanding messages for iucv path has reached */ timeo = sock_sndtimeo(sk, noblock); err = iucv_sock_wait(sk, iucv_below_msglim(sk), timeo); if (err) goto fail; /* return -ECONNRESET if the socket is no longer connected */ if (sk->sk_state != IUCV_CONNECTED) { err = -ECONNRESET; goto fail; } /* increment and save iucv message tag for msg_completion cbk */ txmsg.tag = iucv->send_tag++; IUCV_SKB_CB(skb)->tag = txmsg.tag; if (iucv->transport == AF_IUCV_TRANS_HIPER) { atomic_inc(&iucv->msg_sent); err = afiucv_hs_send(&txmsg, sk, skb, 0); if (err) { atomic_dec(&iucv->msg_sent); goto fail; } goto release; } skb_queue_tail(&iucv->send_skb_q, skb); if (((iucv->path->flags & IUCV_IPRMDATA) & iucv->flags) && skb->len <= 7) { err = iucv_send_iprm(iucv->path, &txmsg, skb); /* on success: there is no message_complete callback * for an IPRMDATA msg; remove skb from send queue */ if (err == 0) { skb_unlink(skb, &iucv->send_skb_q); kfree_skb(skb); } /* this error should never happen since the * IUCV_IPRMDATA path flag is set... sever path */ if (err == 0x15) { pr_iucv->path_sever(iucv->path, NULL); skb_unlink(skb, &iucv->send_skb_q); err = -EPIPE; goto fail; } } else err = pr_iucv->message_send(iucv->path, &txmsg, 0, 0, (void *) skb->data, skb->len); if (err) { if (err == 3) { user_id[8] = 0; memcpy(user_id, iucv->dst_user_id, 8); appl_id[8] = 0; memcpy(appl_id, iucv->dst_name, 8); pr_err("Application %s on z/VM guest %s" " exceeds message limit\n", appl_id, user_id); err = -EAGAIN; } else err = -EPIPE; skb_unlink(skb, &iucv->send_skb_q); goto fail; } release: release_sock(sk); return len; fail: kfree_skb(skb); out: release_sock(sk); return err; } /* iucv_fragment_skb() - Fragment a single IUCV message into multiple skb's * * Locking: must be called with message_q.lock held */ static int iucv_fragment_skb(struct sock *sk, struct sk_buff *skb, int len) { int dataleft, size, copied = 0; struct sk_buff *nskb; dataleft = len; while (dataleft) { if (dataleft >= sk->sk_rcvbuf / 4) size = sk->sk_rcvbuf / 4; else size = dataleft; nskb = alloc_skb(size, GFP_ATOMIC | GFP_DMA); if (!nskb) return -ENOMEM; /* copy target class to control buffer of new skb */ IUCV_SKB_CB(nskb)->class = IUCV_SKB_CB(skb)->class; /* copy data fragment */ memcpy(nskb->data, skb->data + copied, size); copied += size; dataleft -= size; skb_reset_transport_header(nskb); skb_reset_network_header(nskb); nskb->len = size; skb_queue_tail(&iucv_sk(sk)->backlog_skb_q, nskb); } return 0; } /* iucv_process_message() - Receive a single outstanding IUCV message * * Locking: must be called with message_q.lock held */ static void iucv_process_message(struct sock *sk, struct sk_buff *skb, struct iucv_path *path, struct iucv_message *msg) { int rc; unsigned int len; len = iucv_msg_length(msg); /* store msg target class in the second 4 bytes of skb ctrl buffer */ /* Note: the first 4 bytes are reserved for msg tag */ IUCV_SKB_CB(skb)->class = msg->class; /* check for special IPRM messages (e.g. iucv_sock_shutdown) */ if ((msg->flags & IUCV_IPRMDATA) && len > 7) { if (memcmp(msg->rmmsg, iprm_shutdown, 8) == 0) { skb->data = NULL; skb->len = 0; } } else { rc = pr_iucv->message_receive(path, msg, msg->flags & IUCV_IPRMDATA, skb->data, len, NULL); if (rc) { kfree_skb(skb); return; } /* we need to fragment iucv messages for SOCK_STREAM only; * for SOCK_SEQPACKET, it is only relevant if we support * record segmentation using MSG_EOR (see also recvmsg()) */ if (sk->sk_type == SOCK_STREAM && skb->truesize >= sk->sk_rcvbuf / 4) { rc = iucv_fragment_skb(sk, skb, len); kfree_skb(skb); skb = NULL; if (rc) { pr_iucv->path_sever(path, NULL); return; } skb = skb_dequeue(&iucv_sk(sk)->backlog_skb_q); } else { skb_reset_transport_header(skb); skb_reset_network_header(skb); skb->len = len; } } IUCV_SKB_CB(skb)->offset = 0; if (sock_queue_rcv_skb(sk, skb)) skb_queue_head(&iucv_sk(sk)->backlog_skb_q, skb); } /* iucv_process_message_q() - Process outstanding IUCV messages * * Locking: must be called with message_q.lock held */ static void iucv_process_message_q(struct sock *sk) { struct iucv_sock *iucv = iucv_sk(sk); struct sk_buff *skb; struct sock_msg_q *p, *n; list_for_each_entry_safe(p, n, &iucv->message_q.list, list) { skb = alloc_skb(iucv_msg_length(&p->msg), GFP_ATOMIC | GFP_DMA); if (!skb) break; iucv_process_message(sk, skb, p->path, &p->msg); list_del(&p->list); kfree(p); if (!skb_queue_empty(&iucv->backlog_skb_q)) break; } } static int iucv_sock_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t len, int flags) { int noblock = flags & MSG_DONTWAIT; struct sock *sk = sock->sk; struct iucv_sock *iucv = iucv_sk(sk); unsigned int copied, rlen; struct sk_buff *skb, *rskb, *cskb; int err = 0; u32 offset; msg->msg_namelen = 0; if ((sk->sk_state == IUCV_DISCONN) && skb_queue_empty(&iucv->backlog_skb_q) && skb_queue_empty(&sk->sk_receive_queue) && list_empty(&iucv->message_q.list)) return 0; if (flags & (MSG_OOB)) return -EOPNOTSUPP; /* receive/dequeue next skb: * the function understands MSG_PEEK and, thus, does not dequeue skb */ skb = skb_recv_datagram(sk, flags, noblock, &err); if (!skb) { if (sk->sk_shutdown & RCV_SHUTDOWN) return 0; return err; } offset = IUCV_SKB_CB(skb)->offset; rlen = skb->len - offset; /* real length of skb */ copied = min_t(unsigned int, rlen, len); if (!rlen) sk->sk_shutdown = sk->sk_shutdown | RCV_SHUTDOWN; cskb = skb; if (skb_copy_datagram_iovec(cskb, offset, msg->msg_iov, copied)) { if (!(flags & MSG_PEEK)) skb_queue_head(&sk->sk_receive_queue, skb); return -EFAULT; } /* SOCK_SEQPACKET: set MSG_TRUNC if recv buf size is too small */ if (sk->sk_type == SOCK_SEQPACKET) { if (copied < rlen) msg->msg_flags |= MSG_TRUNC; /* each iucv message contains a complete record */ msg->msg_flags |= MSG_EOR; } /* create control message to store iucv msg target class: * get the trgcls from the control buffer of the skb due to * fragmentation of original iucv message. */ err = put_cmsg(msg, SOL_IUCV, SCM_IUCV_TRGCLS, sizeof(IUCV_SKB_CB(skb)->class), (void *)&IUCV_SKB_CB(skb)->class); if (err) { if (!(flags & MSG_PEEK)) skb_queue_head(&sk->sk_receive_queue, skb); return err; } /* Mark read part of skb as used */ if (!(flags & MSG_PEEK)) { /* SOCK_STREAM: re-queue skb if it contains unreceived data */ if (sk->sk_type == SOCK_STREAM) { if (copied < rlen) { IUCV_SKB_CB(skb)->offset = offset + copied; goto done; } } kfree_skb(skb); if (iucv->transport == AF_IUCV_TRANS_HIPER) { atomic_inc(&iucv->msg_recv); if (atomic_read(&iucv->msg_recv) > iucv->msglimit) { WARN_ON(1); iucv_sock_close(sk); return -EFAULT; } } /* Queue backlog skbs */ spin_lock_bh(&iucv->message_q.lock); rskb = skb_dequeue(&iucv->backlog_skb_q); while (rskb) { IUCV_SKB_CB(rskb)->offset = 0; if (sock_queue_rcv_skb(sk, rskb)) { skb_queue_head(&iucv->backlog_skb_q, rskb); break; } else { rskb = skb_dequeue(&iucv->backlog_skb_q); } } if (skb_queue_empty(&iucv->backlog_skb_q)) { if (!list_empty(&iucv->message_q.list)) iucv_process_message_q(sk); if (atomic_read(&iucv->msg_recv) >= iucv->msglimit / 2) { err = iucv_send_ctrl(sk, AF_IUCV_FLAG_WIN); if (err) { sk->sk_state = IUCV_DISCONN; sk->sk_state_change(sk); } } } spin_unlock_bh(&iucv->message_q.lock); } done: /* SOCK_SEQPACKET: return real length if MSG_TRUNC is set */ if (sk->sk_type == SOCK_SEQPACKET && (flags & MSG_TRUNC)) copied = rlen; return copied; } static inline unsigned int iucv_accept_poll(struct sock *parent) { struct iucv_sock *isk, *n; struct sock *sk; list_for_each_entry_safe(isk, n, &iucv_sk(parent)->accept_q, accept_q) { sk = (struct sock *) isk; if (sk->sk_state == IUCV_CONNECTED) return POLLIN | POLLRDNORM; } return 0; } unsigned int iucv_sock_poll(struct file *file, struct socket *sock, poll_table *wait) { struct sock *sk = sock->sk; unsigned int mask = 0; sock_poll_wait(file, sk_sleep(sk), wait); if (sk->sk_state == IUCV_LISTEN) return iucv_accept_poll(sk); if (sk->sk_err || !skb_queue_empty(&sk->sk_error_queue)) mask |= POLLERR | (sock_flag(sk, SOCK_SELECT_ERR_QUEUE) ? POLLPRI : 0); if (sk->sk_shutdown & RCV_SHUTDOWN) mask |= POLLRDHUP; if (sk->sk_shutdown == SHUTDOWN_MASK) mask |= POLLHUP; if (!skb_queue_empty(&sk->sk_receive_queue) || (sk->sk_shutdown & RCV_SHUTDOWN)) mask |= POLLIN | POLLRDNORM; if (sk->sk_state == IUCV_CLOSED) mask |= POLLHUP; if (sk->sk_state == IUCV_DISCONN) mask |= POLLIN; if (sock_writeable(sk) && iucv_below_msglim(sk)) mask |= POLLOUT | POLLWRNORM | POLLWRBAND; else set_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags); return mask; } static int iucv_sock_shutdown(struct socket *sock, int how) { struct sock *sk = sock->sk; struct iucv_sock *iucv = iucv_sk(sk); struct iucv_message txmsg; int err = 0; how++; if ((how & ~SHUTDOWN_MASK) || !how) return -EINVAL; lock_sock(sk); switch (sk->sk_state) { case IUCV_LISTEN: case IUCV_DISCONN: case IUCV_CLOSING: case IUCV_CLOSED: err = -ENOTCONN; goto fail; default: break; } if (how == SEND_SHUTDOWN || how == SHUTDOWN_MASK) { if (iucv->transport == AF_IUCV_TRANS_IUCV) { txmsg.class = 0; txmsg.tag = 0; err = pr_iucv->message_send(iucv->path, &txmsg, IUCV_IPRMDATA, 0, (void *) iprm_shutdown, 8); if (err) { switch (err) { case 1: err = -ENOTCONN; break; case 2: err = -ECONNRESET; break; default: err = -ENOTCONN; break; } } } else iucv_send_ctrl(sk, AF_IUCV_FLAG_SHT); } sk->sk_shutdown |= how; if (how == RCV_SHUTDOWN || how == SHUTDOWN_MASK) { if (iucv->transport == AF_IUCV_TRANS_IUCV) { err = pr_iucv->path_quiesce(iucv->path, NULL); if (err) err = -ENOTCONN; /* skb_queue_purge(&sk->sk_receive_queue); */ } skb_queue_purge(&sk->sk_receive_queue); } /* Wake up anyone sleeping in poll */ sk->sk_state_change(sk); fail: release_sock(sk); return err; } static int iucv_sock_release(struct socket *sock) { struct sock *sk = sock->sk; int err = 0; if (!sk) return 0; iucv_sock_close(sk); sock_orphan(sk); iucv_sock_kill(sk); return err; } /* getsockopt and setsockopt */ static int iucv_sock_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen) { struct sock *sk = sock->sk; struct iucv_sock *iucv = iucv_sk(sk); int val; int rc; if (level != SOL_IUCV) return -ENOPROTOOPT; if (optlen < sizeof(int)) return -EINVAL; if (get_user(val, (int __user *) optval)) return -EFAULT; rc = 0; lock_sock(sk); switch (optname) { case SO_IPRMDATA_MSG: if (val) iucv->flags |= IUCV_IPRMDATA; else iucv->flags &= ~IUCV_IPRMDATA; break; case SO_MSGLIMIT: switch (sk->sk_state) { case IUCV_OPEN: case IUCV_BOUND: if (val < 1 || val > (u16)(~0)) rc = -EINVAL; else iucv->msglimit = val; break; default: rc = -EINVAL; break; } break; default: rc = -ENOPROTOOPT; break; } release_sock(sk); return rc; } static int iucv_sock_getsockopt(struct socket *sock, int level, int optname, char __user *optval, int __user *optlen) { struct sock *sk = sock->sk; struct iucv_sock *iucv = iucv_sk(sk); unsigned int val; int len; if (level != SOL_IUCV) return -ENOPROTOOPT; if (get_user(len, optlen)) return -EFAULT; if (len < 0) return -EINVAL; len = min_t(unsigned int, len, sizeof(int)); switch (optname) { case SO_IPRMDATA_MSG: val = (iucv->flags & IUCV_IPRMDATA) ? 1 : 0; break; case SO_MSGLIMIT: lock_sock(sk); val = (iucv->path != NULL) ? iucv->path->msglim /* connected */ : iucv->msglimit; /* default */ release_sock(sk); break; case SO_MSGSIZE: if (sk->sk_state == IUCV_OPEN) return -EBADFD; val = (iucv->hs_dev) ? iucv->hs_dev->mtu - sizeof(struct af_iucv_trans_hdr) - ETH_HLEN : 0x7fffffff; break; default: return -ENOPROTOOPT; } if (put_user(len, optlen)) return -EFAULT; if (copy_to_user(optval, &val, len)) return -EFAULT; return 0; } /* Callback wrappers - called from iucv base support */ static int iucv_callback_connreq(struct iucv_path *path, u8 ipvmid[8], u8 ipuser[16]) { unsigned char user_data[16]; unsigned char nuser_data[16]; unsigned char src_name[8]; struct sock *sk, *nsk; struct iucv_sock *iucv, *niucv; int err; memcpy(src_name, ipuser, 8); EBCASC(src_name, 8); /* Find out if this path belongs to af_iucv. */ read_lock(&iucv_sk_list.lock); iucv = NULL; sk = NULL; sk_for_each(sk, &iucv_sk_list.head) if (sk->sk_state == IUCV_LISTEN && !memcmp(&iucv_sk(sk)->src_name, src_name, 8)) { /* * Found a listening socket with * src_name == ipuser[0-7]. */ iucv = iucv_sk(sk); break; } read_unlock(&iucv_sk_list.lock); if (!iucv) /* No socket found, not one of our paths. */ return -EINVAL; bh_lock_sock(sk); /* Check if parent socket is listening */ low_nmcpy(user_data, iucv->src_name); high_nmcpy(user_data, iucv->dst_name); ASCEBC(user_data, sizeof(user_data)); if (sk->sk_state != IUCV_LISTEN) { err = pr_iucv->path_sever(path, user_data); iucv_path_free(path); goto fail; } /* Check for backlog size */ if (sk_acceptq_is_full(sk)) { err = pr_iucv->path_sever(path, user_data); iucv_path_free(path); goto fail; } /* Create the new socket */ nsk = iucv_sock_alloc(NULL, sk->sk_type, GFP_ATOMIC); if (!nsk) { err = pr_iucv->path_sever(path, user_data); iucv_path_free(path); goto fail; } niucv = iucv_sk(nsk); iucv_sock_init(nsk, sk); /* Set the new iucv_sock */ memcpy(niucv->dst_name, ipuser + 8, 8); EBCASC(niucv->dst_name, 8); memcpy(niucv->dst_user_id, ipvmid, 8); memcpy(niucv->src_name, iucv->src_name, 8); memcpy(niucv->src_user_id, iucv->src_user_id, 8); niucv->path = path; /* Call iucv_accept */ high_nmcpy(nuser_data, ipuser + 8); memcpy(nuser_data + 8, niucv->src_name, 8); ASCEBC(nuser_data + 8, 8); /* set message limit for path based on msglimit of accepting socket */ niucv->msglimit = iucv->msglimit; path->msglim = iucv->msglimit; err = pr_iucv->path_accept(path, &af_iucv_handler, nuser_data, nsk); if (err) { iucv_sever_path(nsk, 1); iucv_sock_kill(nsk); goto fail; } iucv_accept_enqueue(sk, nsk); /* Wake up accept */ nsk->sk_state = IUCV_CONNECTED; sk->sk_data_ready(sk, 1); err = 0; fail: bh_unlock_sock(sk); return 0; } static void iucv_callback_connack(struct iucv_path *path, u8 ipuser[16]) { struct sock *sk = path->private; sk->sk_state = IUCV_CONNECTED; sk->sk_state_change(sk); } static void iucv_callback_rx(struct iucv_path *path, struct iucv_message *msg) { struct sock *sk = path->private; struct iucv_sock *iucv = iucv_sk(sk); struct sk_buff *skb; struct sock_msg_q *save_msg; int len; if (sk->sk_shutdown & RCV_SHUTDOWN) { pr_iucv->message_reject(path, msg); return; } spin_lock(&iucv->message_q.lock); if (!list_empty(&iucv->message_q.list) || !skb_queue_empty(&iucv->backlog_skb_q)) goto save_message; len = atomic_read(&sk->sk_rmem_alloc); len += SKB_TRUESIZE(iucv_msg_length(msg)); if (len > sk->sk_rcvbuf) goto save_message; skb = alloc_skb(iucv_msg_length(msg), GFP_ATOMIC | GFP_DMA); if (!skb) goto save_message; iucv_process_message(sk, skb, path, msg); goto out_unlock; save_message: save_msg = kzalloc(sizeof(struct sock_msg_q), GFP_ATOMIC | GFP_DMA); if (!save_msg) goto out_unlock; save_msg->path = path; save_msg->msg = *msg; list_add_tail(&save_msg->list, &iucv->message_q.list); out_unlock: spin_unlock(&iucv->message_q.lock); } static void iucv_callback_txdone(struct iucv_path *path, struct iucv_message *msg) { struct sock *sk = path->private; struct sk_buff *this = NULL; struct sk_buff_head *list = &iucv_sk(sk)->send_skb_q; struct sk_buff *list_skb = list->next; unsigned long flags; bh_lock_sock(sk); if (!skb_queue_empty(list)) { spin_lock_irqsave(&list->lock, flags); while (list_skb != (struct sk_buff *)list) { if (msg->tag != IUCV_SKB_CB(list_skb)->tag) { this = list_skb; break; } list_skb = list_skb->next; } if (this) __skb_unlink(this, list); spin_unlock_irqrestore(&list->lock, flags); if (this) { kfree_skb(this); /* wake up any process waiting for sending */ iucv_sock_wake_msglim(sk); } } if (sk->sk_state == IUCV_CLOSING) { if (skb_queue_empty(&iucv_sk(sk)->send_skb_q)) { sk->sk_state = IUCV_CLOSED; sk->sk_state_change(sk); } } bh_unlock_sock(sk); } static void iucv_callback_connrej(struct iucv_path *path, u8 ipuser[16]) { struct sock *sk = path->private; if (sk->sk_state == IUCV_CLOSED) return; bh_lock_sock(sk); iucv_sever_path(sk, 1); sk->sk_state = IUCV_DISCONN; sk->sk_state_change(sk); bh_unlock_sock(sk); } /* called if the other communication side shuts down its RECV direction; * in turn, the callback sets SEND_SHUTDOWN to disable sending of data. */ static void iucv_callback_shutdown(struct iucv_path *path, u8 ipuser[16]) { struct sock *sk = path->private; bh_lock_sock(sk); if (sk->sk_state != IUCV_CLOSED) { sk->sk_shutdown |= SEND_SHUTDOWN; sk->sk_state_change(sk); } bh_unlock_sock(sk); } /***************** HiperSockets transport callbacks ********************/ static void afiucv_swap_src_dest(struct sk_buff *skb) { struct af_iucv_trans_hdr *trans_hdr = (struct af_iucv_trans_hdr *)skb->data; char tmpID[8]; char tmpName[8]; ASCEBC(trans_hdr->destUserID, sizeof(trans_hdr->destUserID)); ASCEBC(trans_hdr->destAppName, sizeof(trans_hdr->destAppName)); ASCEBC(trans_hdr->srcUserID, sizeof(trans_hdr->srcUserID)); ASCEBC(trans_hdr->srcAppName, sizeof(trans_hdr->srcAppName)); memcpy(tmpID, trans_hdr->srcUserID, 8); memcpy(tmpName, trans_hdr->srcAppName, 8); memcpy(trans_hdr->srcUserID, trans_hdr->destUserID, 8); memcpy(trans_hdr->srcAppName, trans_hdr->destAppName, 8); memcpy(trans_hdr->destUserID, tmpID, 8); memcpy(trans_hdr->destAppName, tmpName, 8); skb_push(skb, ETH_HLEN); memset(skb->data, 0, ETH_HLEN); } /** * afiucv_hs_callback_syn - react on received SYN **/ static int afiucv_hs_callback_syn(struct sock *sk, struct sk_buff *skb) { struct sock *nsk; struct iucv_sock *iucv, *niucv; struct af_iucv_trans_hdr *trans_hdr; int err; iucv = iucv_sk(sk); trans_hdr = (struct af_iucv_trans_hdr *)skb->data; if (!iucv) { /* no sock - connection refused */ afiucv_swap_src_dest(skb); trans_hdr->flags = AF_IUCV_FLAG_SYN | AF_IUCV_FLAG_FIN; err = dev_queue_xmit(skb); goto out; } nsk = iucv_sock_alloc(NULL, sk->sk_type, GFP_ATOMIC); bh_lock_sock(sk); if ((sk->sk_state != IUCV_LISTEN) || sk_acceptq_is_full(sk) || !nsk) { /* error on server socket - connection refused */ if (nsk) sk_free(nsk); afiucv_swap_src_dest(skb); trans_hdr->flags = AF_IUCV_FLAG_SYN | AF_IUCV_FLAG_FIN; err = dev_queue_xmit(skb); bh_unlock_sock(sk); goto out; } niucv = iucv_sk(nsk); iucv_sock_init(nsk, sk); niucv->transport = AF_IUCV_TRANS_HIPER; niucv->msglimit = iucv->msglimit; if (!trans_hdr->window) niucv->msglimit_peer = IUCV_HIPER_MSGLIM_DEFAULT; else niucv->msglimit_peer = trans_hdr->window; memcpy(niucv->dst_name, trans_hdr->srcAppName, 8); memcpy(niucv->dst_user_id, trans_hdr->srcUserID, 8); memcpy(niucv->src_name, iucv->src_name, 8); memcpy(niucv->src_user_id, iucv->src_user_id, 8); nsk->sk_bound_dev_if = sk->sk_bound_dev_if; niucv->hs_dev = iucv->hs_dev; dev_hold(niucv->hs_dev); afiucv_swap_src_dest(skb); trans_hdr->flags = AF_IUCV_FLAG_SYN | AF_IUCV_FLAG_ACK; trans_hdr->window = niucv->msglimit; /* if receiver acks the xmit connection is established */ err = dev_queue_xmit(skb); if (!err) { iucv_accept_enqueue(sk, nsk); nsk->sk_state = IUCV_CONNECTED; sk->sk_data_ready(sk, 1); } else iucv_sock_kill(nsk); bh_unlock_sock(sk); out: return NET_RX_SUCCESS; } /** * afiucv_hs_callback_synack() - react on received SYN-ACK **/ static int afiucv_hs_callback_synack(struct sock *sk, struct sk_buff *skb) { struct iucv_sock *iucv = iucv_sk(sk); struct af_iucv_trans_hdr *trans_hdr = (struct af_iucv_trans_hdr *)skb->data; if (!iucv) goto out; if (sk->sk_state != IUCV_BOUND) goto out; bh_lock_sock(sk); iucv->msglimit_peer = trans_hdr->window; sk->sk_state = IUCV_CONNECTED; sk->sk_state_change(sk); bh_unlock_sock(sk); out: kfree_skb(skb); return NET_RX_SUCCESS; } /** * afiucv_hs_callback_synfin() - react on received SYN_FIN **/ static int afiucv_hs_callback_synfin(struct sock *sk, struct sk_buff *skb) { struct iucv_sock *iucv = iucv_sk(sk); if (!iucv) goto out; if (sk->sk_state != IUCV_BOUND) goto out; bh_lock_sock(sk); sk->sk_state = IUCV_DISCONN; sk->sk_state_change(sk); bh_unlock_sock(sk); out: kfree_skb(skb); return NET_RX_SUCCESS; } /** * afiucv_hs_callback_fin() - react on received FIN **/ static int afiucv_hs_callback_fin(struct sock *sk, struct sk_buff *skb) { struct iucv_sock *iucv = iucv_sk(sk); /* other end of connection closed */ if (!iucv) goto out; bh_lock_sock(sk); if (sk->sk_state == IUCV_CONNECTED) { sk->sk_state = IUCV_DISCONN; sk->sk_state_change(sk); } bh_unlock_sock(sk); out: kfree_skb(skb); return NET_RX_SUCCESS; } /** * afiucv_hs_callback_win() - react on received WIN **/ static int afiucv_hs_callback_win(struct sock *sk, struct sk_buff *skb) { struct iucv_sock *iucv = iucv_sk(sk); struct af_iucv_trans_hdr *trans_hdr = (struct af_iucv_trans_hdr *)skb->data; if (!iucv) return NET_RX_SUCCESS; if (sk->sk_state != IUCV_CONNECTED) return NET_RX_SUCCESS; atomic_sub(trans_hdr->window, &iucv->msg_sent); iucv_sock_wake_msglim(sk); return NET_RX_SUCCESS; } /** * afiucv_hs_callback_rx() - react on received data **/ static int afiucv_hs_callback_rx(struct sock *sk, struct sk_buff *skb) { struct iucv_sock *iucv = iucv_sk(sk); if (!iucv) { kfree_skb(skb); return NET_RX_SUCCESS; } if (sk->sk_state != IUCV_CONNECTED) { kfree_skb(skb); return NET_RX_SUCCESS; } if (sk->sk_shutdown & RCV_SHUTDOWN) { kfree_skb(skb); return NET_RX_SUCCESS; } /* write stuff from iucv_msg to skb cb */ if (skb->len < sizeof(struct af_iucv_trans_hdr)) { kfree_skb(skb); return NET_RX_SUCCESS; } skb_pull(skb, sizeof(struct af_iucv_trans_hdr)); skb_reset_transport_header(skb); skb_reset_network_header(skb); IUCV_SKB_CB(skb)->offset = 0; spin_lock(&iucv->message_q.lock); if (skb_queue_empty(&iucv->backlog_skb_q)) { if (sock_queue_rcv_skb(sk, skb)) { /* handle rcv queue full */ skb_queue_tail(&iucv->backlog_skb_q, skb); } } else skb_queue_tail(&iucv_sk(sk)->backlog_skb_q, skb); spin_unlock(&iucv->message_q.lock); return NET_RX_SUCCESS; } /** * afiucv_hs_rcv() - base function for arriving data through HiperSockets * transport * called from netif RX softirq **/ static int afiucv_hs_rcv(struct sk_buff *skb, struct net_device *dev, struct packet_type *pt, struct net_device *orig_dev) { struct sock *sk; struct iucv_sock *iucv; struct af_iucv_trans_hdr *trans_hdr; char nullstring[8]; int err = 0; skb_pull(skb, ETH_HLEN); trans_hdr = (struct af_iucv_trans_hdr *)skb->data; EBCASC(trans_hdr->destAppName, sizeof(trans_hdr->destAppName)); EBCASC(trans_hdr->destUserID, sizeof(trans_hdr->destUserID)); EBCASC(trans_hdr->srcAppName, sizeof(trans_hdr->srcAppName)); EBCASC(trans_hdr->srcUserID, sizeof(trans_hdr->srcUserID)); memset(nullstring, 0, sizeof(nullstring)); iucv = NULL; sk = NULL; read_lock(&iucv_sk_list.lock); sk_for_each(sk, &iucv_sk_list.head) { if (trans_hdr->flags == AF_IUCV_FLAG_SYN) { if ((!memcmp(&iucv_sk(sk)->src_name, trans_hdr->destAppName, 8)) && (!memcmp(&iucv_sk(sk)->src_user_id, trans_hdr->destUserID, 8)) && (!memcmp(&iucv_sk(sk)->dst_name, nullstring, 8)) && (!memcmp(&iucv_sk(sk)->dst_user_id, nullstring, 8))) { iucv = iucv_sk(sk); break; } } else { if ((!memcmp(&iucv_sk(sk)->src_name, trans_hdr->destAppName, 8)) && (!memcmp(&iucv_sk(sk)->src_user_id, trans_hdr->destUserID, 8)) && (!memcmp(&iucv_sk(sk)->dst_name, trans_hdr->srcAppName, 8)) && (!memcmp(&iucv_sk(sk)->dst_user_id, trans_hdr->srcUserID, 8))) { iucv = iucv_sk(sk); break; } } } read_unlock(&iucv_sk_list.lock); if (!iucv) sk = NULL; /* no sock how should we send with no sock 1) send without sock no send rc checking? 2) introduce default sock to handle this cases SYN -> send SYN|ACK in good case, send SYN|FIN in bad case data -> send FIN SYN|ACK, SYN|FIN, FIN -> no action? */ switch (trans_hdr->flags) { case AF_IUCV_FLAG_SYN: /* connect request */ err = afiucv_hs_callback_syn(sk, skb); break; case (AF_IUCV_FLAG_SYN | AF_IUCV_FLAG_ACK): /* connect request confirmed */ err = afiucv_hs_callback_synack(sk, skb); break; case (AF_IUCV_FLAG_SYN | AF_IUCV_FLAG_FIN): /* connect request refused */ err = afiucv_hs_callback_synfin(sk, skb); break; case (AF_IUCV_FLAG_FIN): /* close request */ err = afiucv_hs_callback_fin(sk, skb); break; case (AF_IUCV_FLAG_WIN): err = afiucv_hs_callback_win(sk, skb); if (skb->len == sizeof(struct af_iucv_trans_hdr)) { kfree_skb(skb); break; } /* fall through and receive non-zero length data */ case (AF_IUCV_FLAG_SHT): /* shutdown request */ /* fall through and receive zero length data */ case 0: /* plain data frame */ IUCV_SKB_CB(skb)->class = trans_hdr->iucv_hdr.class; err = afiucv_hs_callback_rx(sk, skb); break; default: ; } return err; } /** * afiucv_hs_callback_txnotify() - handle send notifcations from HiperSockets * transport **/ static void afiucv_hs_callback_txnotify(struct sk_buff *skb, enum iucv_tx_notify n) { struct sock *isk = skb->sk; struct sock *sk = NULL; struct iucv_sock *iucv = NULL; struct sk_buff_head *list; struct sk_buff *list_skb; struct sk_buff *nskb; unsigned long flags; read_lock_irqsave(&iucv_sk_list.lock, flags); sk_for_each(sk, &iucv_sk_list.head) if (sk == isk) { iucv = iucv_sk(sk); break; } read_unlock_irqrestore(&iucv_sk_list.lock, flags); if (!iucv || sock_flag(sk, SOCK_ZAPPED)) return; list = &iucv->send_skb_q; spin_lock_irqsave(&list->lock, flags); if (skb_queue_empty(list)) goto out_unlock; list_skb = list->next; nskb = list_skb->next; while (list_skb != (struct sk_buff *)list) { if (skb_shinfo(list_skb) == skb_shinfo(skb)) { switch (n) { case TX_NOTIFY_OK: __skb_unlink(list_skb, list); kfree_skb(list_skb); iucv_sock_wake_msglim(sk); break; case TX_NOTIFY_PENDING: atomic_inc(&iucv->pendings); break; case TX_NOTIFY_DELAYED_OK: __skb_unlink(list_skb, list); atomic_dec(&iucv->pendings); if (atomic_read(&iucv->pendings) <= 0) iucv_sock_wake_msglim(sk); kfree_skb(list_skb); break; case TX_NOTIFY_UNREACHABLE: case TX_NOTIFY_DELAYED_UNREACHABLE: case TX_NOTIFY_TPQFULL: /* not yet used */ case TX_NOTIFY_GENERALERROR: case TX_NOTIFY_DELAYED_GENERALERROR: __skb_unlink(list_skb, list); kfree_skb(list_skb); if (sk->sk_state == IUCV_CONNECTED) { sk->sk_state = IUCV_DISCONN; sk->sk_state_change(sk); } break; } break; } list_skb = nskb; nskb = nskb->next; } out_unlock: spin_unlock_irqrestore(&list->lock, flags); if (sk->sk_state == IUCV_CLOSING) { if (skb_queue_empty(&iucv_sk(sk)->send_skb_q)) { sk->sk_state = IUCV_CLOSED; sk->sk_state_change(sk); } } } /* * afiucv_netdev_event: handle netdev notifier chain events */ static int afiucv_netdev_event(struct notifier_block *this, unsigned long event, void *ptr) { struct net_device *event_dev = netdev_notifier_info_to_dev(ptr); struct sock *sk; struct iucv_sock *iucv; switch (event) { case NETDEV_REBOOT: case NETDEV_GOING_DOWN: sk_for_each(sk, &iucv_sk_list.head) { iucv = iucv_sk(sk); if ((iucv->hs_dev == event_dev) && (sk->sk_state == IUCV_CONNECTED)) { if (event == NETDEV_GOING_DOWN) iucv_send_ctrl(sk, AF_IUCV_FLAG_FIN); sk->sk_state = IUCV_DISCONN; sk->sk_state_change(sk); } } break; case NETDEV_DOWN: case NETDEV_UNREGISTER: default: break; } return NOTIFY_DONE; } static struct notifier_block afiucv_netdev_notifier = { .notifier_call = afiucv_netdev_event, }; static const struct proto_ops iucv_sock_ops = { .family = PF_IUCV, .owner = THIS_MODULE, .release = iucv_sock_release, .bind = iucv_sock_bind, .connect = iucv_sock_connect, .listen = iucv_sock_listen, .accept = iucv_sock_accept, .getname = iucv_sock_getname, .sendmsg = iucv_sock_sendmsg, .recvmsg = iucv_sock_recvmsg, .poll = iucv_sock_poll, .ioctl = sock_no_ioctl, .mmap = sock_no_mmap, .socketpair = sock_no_socketpair, .shutdown = iucv_sock_shutdown, .setsockopt = iucv_sock_setsockopt, .getsockopt = iucv_sock_getsockopt, }; static const struct net_proto_family iucv_sock_family_ops = { .family = AF_IUCV, .owner = THIS_MODULE, .create = iucv_sock_create, }; static struct packet_type iucv_packet_type = { .type = cpu_to_be16(ETH_P_AF_IUCV), .func = afiucv_hs_rcv, }; static int afiucv_iucv_init(void) { int err; err = pr_iucv->iucv_register(&af_iucv_handler, 0); if (err) goto out; /* establish dummy device */ af_iucv_driver.bus = pr_iucv->bus; err = driver_register(&af_iucv_driver); if (err) goto out_iucv; af_iucv_dev = kzalloc(sizeof(struct device), GFP_KERNEL); if (!af_iucv_dev) { err = -ENOMEM; goto out_driver; } dev_set_name(af_iucv_dev, "af_iucv"); af_iucv_dev->bus = pr_iucv->bus; af_iucv_dev->parent = pr_iucv->root; af_iucv_dev->release = (void (*)(struct device *))kfree; af_iucv_dev->driver = &af_iucv_driver; err = device_register(af_iucv_dev); if (err) goto out_driver; return 0; out_driver: driver_unregister(&af_iucv_driver); out_iucv: pr_iucv->iucv_unregister(&af_iucv_handler, 0); out: return err; } static int __init afiucv_init(void) { int err; if (MACHINE_IS_VM) { cpcmd("QUERY USERID", iucv_userid, sizeof(iucv_userid), &err); if (unlikely(err)) { WARN_ON(err); err = -EPROTONOSUPPORT; goto out; } pr_iucv = try_then_request_module(symbol_get(iucv_if), "iucv"); if (!pr_iucv) { printk(KERN_WARNING "iucv_if lookup failed\n"); memset(&iucv_userid, 0, sizeof(iucv_userid)); } } else { memset(&iucv_userid, 0, sizeof(iucv_userid)); pr_iucv = NULL; } err = proto_register(&iucv_proto, 0); if (err) goto out; err = sock_register(&iucv_sock_family_ops); if (err) goto out_proto; if (pr_iucv) { err = afiucv_iucv_init(); if (err) goto out_sock; } else register_netdevice_notifier(&afiucv_netdev_notifier); dev_add_pack(&iucv_packet_type); return 0; out_sock: sock_unregister(PF_IUCV); out_proto: proto_unregister(&iucv_proto); out: if (pr_iucv) symbol_put(iucv_if); return err; } static void __exit afiucv_exit(void) { if (pr_iucv) { device_unregister(af_iucv_dev); driver_unregister(&af_iucv_driver); pr_iucv->iucv_unregister(&af_iucv_handler, 0); symbol_put(iucv_if); } else unregister_netdevice_notifier(&afiucv_netdev_notifier); dev_remove_pack(&iucv_packet_type); sock_unregister(PF_IUCV); proto_unregister(&iucv_proto); } module_init(afiucv_init); module_exit(afiucv_exit); MODULE_AUTHOR("Jennifer Hunt <jenhunt@us.ibm.com>"); MODULE_DESCRIPTION("IUCV Sockets ver " VERSION); MODULE_VERSION(VERSION); MODULE_LICENSE("GPL"); MODULE_ALIAS_NETPROTO(PF_IUCV);
./CrossVul/dataset_final_sorted/CWE-20/c/bad_5845_17
crossvul-cpp_data_good_5418_3
/* * Copyright (c) 2001-2002 Michael David Adams. * All rights reserved. */ /* __START_OF_JASPER_LICENSE__ * * JasPer License Version 2.0 * * Copyright (c) 2001-2006 Michael David Adams * Copyright (c) 1999-2000 Image Power, Inc. * Copyright (c) 1999-2000 The University of British Columbia * * All rights reserved. * * Permission is hereby granted, free of charge, to any person (the * "User") obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, * publish, distribute, and/or sell copies of the Software, and to permit * persons to whom the Software is furnished to do so, subject to the * following conditions: * * 1. The above copyright notices and this permission notice (which * includes the disclaimer below) shall be included in all copies or * substantial portions of the Software. * * 2. The name of a copyright holder shall not be used to endorse or * promote products derived from the Software without specific prior * written permission. * * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY. * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES, * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH, * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. * * __END_OF_JASPER_LICENSE__ */ /******************************************************************************\ * Includes. \******************************************************************************/ #include <stdarg.h> #include <stdio.h> #include "jasper/jas_types.h" #include "jasper/jas_debug.h" /******************************************************************************\ * Local data. \******************************************************************************/ static int jas_dbglevel = 0; /* The debug level. */ /******************************************************************************\ * Code for getting/setting the debug level. \******************************************************************************/ /* Set the library debug level. */ int jas_setdbglevel(int dbglevel) { int olddbglevel; /* Save the old debug level. */ olddbglevel = jas_dbglevel; /* Change the debug level. */ jas_dbglevel = dbglevel; /* Return the old debug level. */ return olddbglevel; } /* Get the library debug level. */ int jas_getdbglevel() { return jas_dbglevel; } /******************************************************************************\ * Code. \******************************************************************************/ /* Perform formatted output to standard error. */ int jas_eprintf(const char *fmt, ...) { int ret; va_list ap; va_start(ap, fmt); ret = vfprintf(stderr, fmt, ap); va_end(ap); return ret; } /* Dump memory to a stream. */ int jas_memdump(FILE *out, void *data, size_t len) { size_t i; size_t j; jas_uchar *dp; dp = data; for (i = 0; i < len; i += 16) { fprintf(out, "%04zx:", i); for (j = 0; j < 16; ++j) { if (i + j < len) { fprintf(out, " %02x", dp[i + j]); } } fprintf(out, "\n"); } return 0; } /******************************************************************************\ * Code. \******************************************************************************/ void jas_deprecated(const char *s) { static char message[] = "WARNING!!! WARNING!!! WARNING!!! WARNING!!! WARNING!!! WARNING!!!\n" "WARNING!!! WARNING!!! WARNING!!! WARNING!!! WARNING!!! WARNING!!!\n" "WARNING!!! WARNING!!! WARNING!!! WARNING!!! WARNING!!! WARNING!!!\n" "YOUR CODE IS RELYING ON DEPRECATED FUNCTIONALTIY IN THE JASPER LIBRARY.\n" "THIS FUNCTIONALITY WILL BE REMOVED IN THE NEAR FUTURE.\n" "PLEASE FIX THIS PROBLEM BEFORE YOUR CODE STOPS WORKING!\n" ; jas_eprintf("%s", message); jas_eprintf("The specific problem is as follows:\n%s\n", s); //abort(); }
./CrossVul/dataset_final_sorted/CWE-20/c/good_5418_3
crossvul-cpp_data_good_1776_0
/* * IPv6 Address [auto]configuration * Linux INET6 implementation * * Authors: * Pedro Roque <roque@di.fc.ul.pt> * Alexey Kuznetsov <kuznet@ms2.inr.ac.ru> * * 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. */ /* * Changes: * * Janos Farkas : delete timer on ifdown * <chexum@bankinf.banki.hu> * Andi Kleen : kill double kfree on module * unload. * Maciej W. Rozycki : FDDI support * sekiya@USAGI : Don't send too many RS * packets. * yoshfuji@USAGI : Fixed interval between DAD * packets. * YOSHIFUJI Hideaki @USAGI : improved accuracy of * address validation timer. * YOSHIFUJI Hideaki @USAGI : Privacy Extensions (RFC3041) * support. * Yuji SEKIYA @USAGI : Don't assign a same IPv6 * address on a same interface. * YOSHIFUJI Hideaki @USAGI : ARCnet support * YOSHIFUJI Hideaki @USAGI : convert /proc/net/if_inet6 to * seq_file. * YOSHIFUJI Hideaki @USAGI : improved source address * selection; consider scope, * status etc. */ #define pr_fmt(fmt) "IPv6: " fmt #include <linux/errno.h> #include <linux/types.h> #include <linux/kernel.h> #include <linux/socket.h> #include <linux/sockios.h> #include <linux/net.h> #include <linux/in6.h> #include <linux/netdevice.h> #include <linux/if_addr.h> #include <linux/if_arp.h> #include <linux/if_arcnet.h> #include <linux/if_infiniband.h> #include <linux/route.h> #include <linux/inetdevice.h> #include <linux/init.h> #include <linux/slab.h> #ifdef CONFIG_SYSCTL #include <linux/sysctl.h> #endif #include <linux/capability.h> #include <linux/delay.h> #include <linux/notifier.h> #include <linux/string.h> #include <linux/hash.h> #include <net/net_namespace.h> #include <net/sock.h> #include <net/snmp.h> #include <net/af_ieee802154.h> #include <net/firewire.h> #include <net/ipv6.h> #include <net/protocol.h> #include <net/ndisc.h> #include <net/ip6_route.h> #include <net/addrconf.h> #include <net/tcp.h> #include <net/ip.h> #include <net/netlink.h> #include <net/pkt_sched.h> #include <linux/if_tunnel.h> #include <linux/rtnetlink.h> #include <linux/netconf.h> #include <linux/random.h> #include <linux/uaccess.h> #include <asm/unaligned.h> #include <linux/proc_fs.h> #include <linux/seq_file.h> #include <linux/export.h> /* Set to 3 to get tracing... */ #define ACONF_DEBUG 2 #if ACONF_DEBUG >= 3 #define ADBG(fmt, ...) printk(fmt, ##__VA_ARGS__) #else #define ADBG(fmt, ...) do { if (0) printk(fmt, ##__VA_ARGS__); } while (0) #endif #define INFINITY_LIFE_TIME 0xFFFFFFFF static inline u32 cstamp_delta(unsigned long cstamp) { return (cstamp - INITIAL_JIFFIES) * 100UL / HZ; } #ifdef CONFIG_SYSCTL static int addrconf_sysctl_register(struct inet6_dev *idev); static void addrconf_sysctl_unregister(struct inet6_dev *idev); #else static inline int addrconf_sysctl_register(struct inet6_dev *idev) { return 0; } static inline void addrconf_sysctl_unregister(struct inet6_dev *idev) { } #endif static void __ipv6_regen_rndid(struct inet6_dev *idev); static void __ipv6_try_regen_rndid(struct inet6_dev *idev, struct in6_addr *tmpaddr); static void ipv6_regen_rndid(unsigned long data); static int ipv6_generate_eui64(u8 *eui, struct net_device *dev); static int ipv6_count_addresses(struct inet6_dev *idev); /* * Configured unicast address hash table */ static struct hlist_head inet6_addr_lst[IN6_ADDR_HSIZE]; static DEFINE_SPINLOCK(addrconf_hash_lock); static void addrconf_verify(void); static void addrconf_verify_rtnl(void); static void addrconf_verify_work(struct work_struct *); static struct workqueue_struct *addrconf_wq; static DECLARE_DELAYED_WORK(addr_chk_work, addrconf_verify_work); static void addrconf_join_anycast(struct inet6_ifaddr *ifp); static void addrconf_leave_anycast(struct inet6_ifaddr *ifp); static void addrconf_type_change(struct net_device *dev, unsigned long event); static int addrconf_ifdown(struct net_device *dev, int how); static struct rt6_info *addrconf_get_prefix_route(const struct in6_addr *pfx, int plen, const struct net_device *dev, u32 flags, u32 noflags); static void addrconf_dad_start(struct inet6_ifaddr *ifp); static void addrconf_dad_work(struct work_struct *w); static void addrconf_dad_completed(struct inet6_ifaddr *ifp); static void addrconf_dad_run(struct inet6_dev *idev); static void addrconf_rs_timer(unsigned long data); static void __ipv6_ifa_notify(int event, struct inet6_ifaddr *ifa); static void ipv6_ifa_notify(int event, struct inet6_ifaddr *ifa); static void inet6_prefix_notify(int event, struct inet6_dev *idev, struct prefix_info *pinfo); static bool ipv6_chk_same_addr(struct net *net, const struct in6_addr *addr, struct net_device *dev); static struct ipv6_devconf ipv6_devconf __read_mostly = { .forwarding = 0, .hop_limit = IPV6_DEFAULT_HOPLIMIT, .mtu6 = IPV6_MIN_MTU, .accept_ra = 1, .accept_redirects = 1, .autoconf = 1, .force_mld_version = 0, .mldv1_unsolicited_report_interval = 10 * HZ, .mldv2_unsolicited_report_interval = HZ, .dad_transmits = 1, .rtr_solicits = MAX_RTR_SOLICITATIONS, .rtr_solicit_interval = RTR_SOLICITATION_INTERVAL, .rtr_solicit_delay = MAX_RTR_SOLICITATION_DELAY, .use_tempaddr = 0, .temp_valid_lft = TEMP_VALID_LIFETIME, .temp_prefered_lft = TEMP_PREFERRED_LIFETIME, .regen_max_retry = REGEN_MAX_RETRY, .max_desync_factor = MAX_DESYNC_FACTOR, .max_addresses = IPV6_MAX_ADDRESSES, .accept_ra_defrtr = 1, .accept_ra_from_local = 0, .accept_ra_pinfo = 1, #ifdef CONFIG_IPV6_ROUTER_PREF .accept_ra_rtr_pref = 1, .rtr_probe_interval = 60 * HZ, #ifdef CONFIG_IPV6_ROUTE_INFO .accept_ra_rt_info_max_plen = 0, #endif #endif .proxy_ndp = 0, .accept_source_route = 0, /* we do not accept RH0 by default. */ .disable_ipv6 = 0, .accept_dad = 1, .suppress_frag_ndisc = 1, .accept_ra_mtu = 1, }; static struct ipv6_devconf ipv6_devconf_dflt __read_mostly = { .forwarding = 0, .hop_limit = IPV6_DEFAULT_HOPLIMIT, .mtu6 = IPV6_MIN_MTU, .accept_ra = 1, .accept_redirects = 1, .autoconf = 1, .force_mld_version = 0, .mldv1_unsolicited_report_interval = 10 * HZ, .mldv2_unsolicited_report_interval = HZ, .dad_transmits = 1, .rtr_solicits = MAX_RTR_SOLICITATIONS, .rtr_solicit_interval = RTR_SOLICITATION_INTERVAL, .rtr_solicit_delay = MAX_RTR_SOLICITATION_DELAY, .use_tempaddr = 0, .temp_valid_lft = TEMP_VALID_LIFETIME, .temp_prefered_lft = TEMP_PREFERRED_LIFETIME, .regen_max_retry = REGEN_MAX_RETRY, .max_desync_factor = MAX_DESYNC_FACTOR, .max_addresses = IPV6_MAX_ADDRESSES, .accept_ra_defrtr = 1, .accept_ra_from_local = 0, .accept_ra_pinfo = 1, #ifdef CONFIG_IPV6_ROUTER_PREF .accept_ra_rtr_pref = 1, .rtr_probe_interval = 60 * HZ, #ifdef CONFIG_IPV6_ROUTE_INFO .accept_ra_rt_info_max_plen = 0, #endif #endif .proxy_ndp = 0, .accept_source_route = 0, /* we do not accept RH0 by default. */ .disable_ipv6 = 0, .accept_dad = 1, .suppress_frag_ndisc = 1, .accept_ra_mtu = 1, }; /* Check if a valid qdisc is available */ static inline bool addrconf_qdisc_ok(const struct net_device *dev) { return !qdisc_tx_is_noop(dev); } static void addrconf_del_rs_timer(struct inet6_dev *idev) { if (del_timer(&idev->rs_timer)) __in6_dev_put(idev); } static void addrconf_del_dad_work(struct inet6_ifaddr *ifp) { if (cancel_delayed_work(&ifp->dad_work)) __in6_ifa_put(ifp); } static void addrconf_mod_rs_timer(struct inet6_dev *idev, unsigned long when) { if (!timer_pending(&idev->rs_timer)) in6_dev_hold(idev); mod_timer(&idev->rs_timer, jiffies + when); } static void addrconf_mod_dad_work(struct inet6_ifaddr *ifp, unsigned long delay) { if (!delayed_work_pending(&ifp->dad_work)) in6_ifa_hold(ifp); mod_delayed_work(addrconf_wq, &ifp->dad_work, delay); } static int snmp6_alloc_dev(struct inet6_dev *idev) { int i; idev->stats.ipv6 = alloc_percpu(struct ipstats_mib); if (!idev->stats.ipv6) goto err_ip; for_each_possible_cpu(i) { struct ipstats_mib *addrconf_stats; addrconf_stats = per_cpu_ptr(idev->stats.ipv6, i); u64_stats_init(&addrconf_stats->syncp); } idev->stats.icmpv6dev = kzalloc(sizeof(struct icmpv6_mib_device), GFP_KERNEL); if (!idev->stats.icmpv6dev) goto err_icmp; idev->stats.icmpv6msgdev = kzalloc(sizeof(struct icmpv6msg_mib_device), GFP_KERNEL); if (!idev->stats.icmpv6msgdev) goto err_icmpmsg; return 0; err_icmpmsg: kfree(idev->stats.icmpv6dev); err_icmp: free_percpu(idev->stats.ipv6); err_ip: return -ENOMEM; } static struct inet6_dev *ipv6_add_dev(struct net_device *dev) { struct inet6_dev *ndev; int err = -ENOMEM; ASSERT_RTNL(); if (dev->mtu < IPV6_MIN_MTU) return ERR_PTR(-EINVAL); ndev = kzalloc(sizeof(struct inet6_dev), GFP_KERNEL); if (ndev == NULL) return ERR_PTR(err); rwlock_init(&ndev->lock); ndev->dev = dev; INIT_LIST_HEAD(&ndev->addr_list); setup_timer(&ndev->rs_timer, addrconf_rs_timer, (unsigned long)ndev); memcpy(&ndev->cnf, dev_net(dev)->ipv6.devconf_dflt, sizeof(ndev->cnf)); ndev->cnf.mtu6 = dev->mtu; ndev->cnf.sysctl = NULL; ndev->nd_parms = neigh_parms_alloc(dev, &nd_tbl); if (ndev->nd_parms == NULL) { kfree(ndev); return ERR_PTR(err); } if (ndev->cnf.forwarding) dev_disable_lro(dev); /* We refer to the device */ dev_hold(dev); if (snmp6_alloc_dev(ndev) < 0) { ADBG(KERN_WARNING "%s: cannot allocate memory for statistics; dev=%s.\n", __func__, dev->name); neigh_parms_release(&nd_tbl, ndev->nd_parms); dev_put(dev); kfree(ndev); return ERR_PTR(err); } if (snmp6_register_dev(ndev) < 0) { ADBG(KERN_WARNING "%s: cannot create /proc/net/dev_snmp6/%s\n", __func__, dev->name); goto err_release; } /* One reference from device. We must do this before * we invoke __ipv6_regen_rndid(). */ in6_dev_hold(ndev); if (dev->flags & (IFF_NOARP | IFF_LOOPBACK)) ndev->cnf.accept_dad = -1; #if IS_ENABLED(CONFIG_IPV6_SIT) if (dev->type == ARPHRD_SIT && (dev->priv_flags & IFF_ISATAP)) { pr_info("%s: Disabled Multicast RS\n", dev->name); ndev->cnf.rtr_solicits = 0; } #endif INIT_LIST_HEAD(&ndev->tempaddr_list); setup_timer(&ndev->regen_timer, ipv6_regen_rndid, (unsigned long)ndev); if ((dev->flags&IFF_LOOPBACK) || dev->type == ARPHRD_TUNNEL || dev->type == ARPHRD_TUNNEL6 || dev->type == ARPHRD_SIT || dev->type == ARPHRD_NONE) { ndev->cnf.use_tempaddr = -1; } else { in6_dev_hold(ndev); ipv6_regen_rndid((unsigned long) ndev); } ndev->token = in6addr_any; if (netif_running(dev) && addrconf_qdisc_ok(dev)) ndev->if_flags |= IF_READY; ipv6_mc_init_dev(ndev); ndev->tstamp = jiffies; err = addrconf_sysctl_register(ndev); if (err) { ipv6_mc_destroy_dev(ndev); del_timer(&ndev->regen_timer); goto err_release; } /* protected by rtnl_lock */ rcu_assign_pointer(dev->ip6_ptr, ndev); /* Join interface-local all-node multicast group */ ipv6_dev_mc_inc(dev, &in6addr_interfacelocal_allnodes); /* Join all-node multicast group */ ipv6_dev_mc_inc(dev, &in6addr_linklocal_allnodes); /* Join all-router multicast group if forwarding is set */ if (ndev->cnf.forwarding && (dev->flags & IFF_MULTICAST)) ipv6_dev_mc_inc(dev, &in6addr_linklocal_allrouters); return ndev; err_release: neigh_parms_release(&nd_tbl, ndev->nd_parms); ndev->dead = 1; in6_dev_finish_destroy(ndev); return ERR_PTR(err); } static struct inet6_dev *ipv6_find_idev(struct net_device *dev) { struct inet6_dev *idev; ASSERT_RTNL(); idev = __in6_dev_get(dev); if (!idev) { idev = ipv6_add_dev(dev); if (IS_ERR(idev)) return NULL; } if (dev->flags&IFF_UP) ipv6_mc_up(idev); return idev; } static int inet6_netconf_msgsize_devconf(int type) { int size = NLMSG_ALIGN(sizeof(struct netconfmsg)) + nla_total_size(4); /* NETCONFA_IFINDEX */ /* type -1 is used for ALL */ if (type == -1 || type == NETCONFA_FORWARDING) size += nla_total_size(4); #ifdef CONFIG_IPV6_MROUTE if (type == -1 || type == NETCONFA_MC_FORWARDING) size += nla_total_size(4); #endif if (type == -1 || type == NETCONFA_PROXY_NEIGH) size += nla_total_size(4); return size; } static int inet6_netconf_fill_devconf(struct sk_buff *skb, int ifindex, struct ipv6_devconf *devconf, u32 portid, u32 seq, int event, unsigned int flags, int type) { struct nlmsghdr *nlh; struct netconfmsg *ncm; nlh = nlmsg_put(skb, portid, seq, event, sizeof(struct netconfmsg), flags); if (nlh == NULL) return -EMSGSIZE; ncm = nlmsg_data(nlh); ncm->ncm_family = AF_INET6; if (nla_put_s32(skb, NETCONFA_IFINDEX, ifindex) < 0) goto nla_put_failure; /* type -1 is used for ALL */ if ((type == -1 || type == NETCONFA_FORWARDING) && nla_put_s32(skb, NETCONFA_FORWARDING, devconf->forwarding) < 0) goto nla_put_failure; #ifdef CONFIG_IPV6_MROUTE if ((type == -1 || type == NETCONFA_MC_FORWARDING) && nla_put_s32(skb, NETCONFA_MC_FORWARDING, devconf->mc_forwarding) < 0) goto nla_put_failure; #endif if ((type == -1 || type == NETCONFA_PROXY_NEIGH) && nla_put_s32(skb, NETCONFA_PROXY_NEIGH, devconf->proxy_ndp) < 0) goto nla_put_failure; nlmsg_end(skb, nlh); return 0; nla_put_failure: nlmsg_cancel(skb, nlh); return -EMSGSIZE; } void inet6_netconf_notify_devconf(struct net *net, int type, int ifindex, struct ipv6_devconf *devconf) { struct sk_buff *skb; int err = -ENOBUFS; skb = nlmsg_new(inet6_netconf_msgsize_devconf(type), GFP_ATOMIC); if (skb == NULL) goto errout; err = inet6_netconf_fill_devconf(skb, ifindex, devconf, 0, 0, RTM_NEWNETCONF, 0, type); if (err < 0) { /* -EMSGSIZE implies BUG in inet6_netconf_msgsize_devconf() */ WARN_ON(err == -EMSGSIZE); kfree_skb(skb); goto errout; } rtnl_notify(skb, net, 0, RTNLGRP_IPV6_NETCONF, NULL, GFP_ATOMIC); return; errout: rtnl_set_sk_err(net, RTNLGRP_IPV6_NETCONF, err); } static const struct nla_policy devconf_ipv6_policy[NETCONFA_MAX+1] = { [NETCONFA_IFINDEX] = { .len = sizeof(int) }, [NETCONFA_FORWARDING] = { .len = sizeof(int) }, [NETCONFA_PROXY_NEIGH] = { .len = sizeof(int) }, }; static int inet6_netconf_get_devconf(struct sk_buff *in_skb, struct nlmsghdr *nlh) { struct net *net = sock_net(in_skb->sk); struct nlattr *tb[NETCONFA_MAX+1]; struct netconfmsg *ncm; struct sk_buff *skb; struct ipv6_devconf *devconf; struct inet6_dev *in6_dev; struct net_device *dev; int ifindex; int err; err = nlmsg_parse(nlh, sizeof(*ncm), tb, NETCONFA_MAX, devconf_ipv6_policy); if (err < 0) goto errout; err = EINVAL; if (!tb[NETCONFA_IFINDEX]) goto errout; ifindex = nla_get_s32(tb[NETCONFA_IFINDEX]); switch (ifindex) { case NETCONFA_IFINDEX_ALL: devconf = net->ipv6.devconf_all; break; case NETCONFA_IFINDEX_DEFAULT: devconf = net->ipv6.devconf_dflt; break; default: dev = __dev_get_by_index(net, ifindex); if (dev == NULL) goto errout; in6_dev = __in6_dev_get(dev); if (in6_dev == NULL) goto errout; devconf = &in6_dev->cnf; break; } err = -ENOBUFS; skb = nlmsg_new(inet6_netconf_msgsize_devconf(-1), GFP_ATOMIC); if (skb == NULL) goto errout; err = inet6_netconf_fill_devconf(skb, ifindex, devconf, NETLINK_CB(in_skb).portid, nlh->nlmsg_seq, RTM_NEWNETCONF, 0, -1); if (err < 0) { /* -EMSGSIZE implies BUG in inet6_netconf_msgsize_devconf() */ WARN_ON(err == -EMSGSIZE); kfree_skb(skb); goto errout; } err = rtnl_unicast(skb, net, NETLINK_CB(in_skb).portid); errout: return err; } static int inet6_netconf_dump_devconf(struct sk_buff *skb, struct netlink_callback *cb) { struct net *net = sock_net(skb->sk); int h, s_h; int idx, s_idx; struct net_device *dev; struct inet6_dev *idev; struct hlist_head *head; s_h = cb->args[0]; s_idx = idx = cb->args[1]; for (h = s_h; h < NETDEV_HASHENTRIES; h++, s_idx = 0) { idx = 0; head = &net->dev_index_head[h]; rcu_read_lock(); cb->seq = atomic_read(&net->ipv6.dev_addr_genid) ^ net->dev_base_seq; hlist_for_each_entry_rcu(dev, head, index_hlist) { if (idx < s_idx) goto cont; idev = __in6_dev_get(dev); if (!idev) goto cont; if (inet6_netconf_fill_devconf(skb, dev->ifindex, &idev->cnf, NETLINK_CB(cb->skb).portid, cb->nlh->nlmsg_seq, RTM_NEWNETCONF, NLM_F_MULTI, -1) < 0) { rcu_read_unlock(); goto done; } nl_dump_check_consistent(cb, nlmsg_hdr(skb)); cont: idx++; } rcu_read_unlock(); } if (h == NETDEV_HASHENTRIES) { if (inet6_netconf_fill_devconf(skb, NETCONFA_IFINDEX_ALL, net->ipv6.devconf_all, NETLINK_CB(cb->skb).portid, cb->nlh->nlmsg_seq, RTM_NEWNETCONF, NLM_F_MULTI, -1) < 0) goto done; else h++; } if (h == NETDEV_HASHENTRIES + 1) { if (inet6_netconf_fill_devconf(skb, NETCONFA_IFINDEX_DEFAULT, net->ipv6.devconf_dflt, NETLINK_CB(cb->skb).portid, cb->nlh->nlmsg_seq, RTM_NEWNETCONF, NLM_F_MULTI, -1) < 0) goto done; else h++; } done: cb->args[0] = h; cb->args[1] = idx; return skb->len; } #ifdef CONFIG_SYSCTL static void dev_forward_change(struct inet6_dev *idev) { struct net_device *dev; struct inet6_ifaddr *ifa; if (!idev) return; dev = idev->dev; if (idev->cnf.forwarding) dev_disable_lro(dev); if (dev->flags & IFF_MULTICAST) { if (idev->cnf.forwarding) { ipv6_dev_mc_inc(dev, &in6addr_linklocal_allrouters); ipv6_dev_mc_inc(dev, &in6addr_interfacelocal_allrouters); ipv6_dev_mc_inc(dev, &in6addr_sitelocal_allrouters); } else { ipv6_dev_mc_dec(dev, &in6addr_linklocal_allrouters); ipv6_dev_mc_dec(dev, &in6addr_interfacelocal_allrouters); ipv6_dev_mc_dec(dev, &in6addr_sitelocal_allrouters); } } list_for_each_entry(ifa, &idev->addr_list, if_list) { if (ifa->flags&IFA_F_TENTATIVE) continue; if (idev->cnf.forwarding) addrconf_join_anycast(ifa); else addrconf_leave_anycast(ifa); } inet6_netconf_notify_devconf(dev_net(dev), NETCONFA_FORWARDING, dev->ifindex, &idev->cnf); } static void addrconf_forward_change(struct net *net, __s32 newf) { struct net_device *dev; struct inet6_dev *idev; for_each_netdev(net, dev) { idev = __in6_dev_get(dev); if (idev) { int changed = (!idev->cnf.forwarding) ^ (!newf); idev->cnf.forwarding = newf; if (changed) dev_forward_change(idev); } } } static int addrconf_fixup_forwarding(struct ctl_table *table, int *p, int newf) { struct net *net; int old; if (!rtnl_trylock()) return restart_syscall(); net = (struct net *)table->extra2; old = *p; *p = newf; if (p == &net->ipv6.devconf_dflt->forwarding) { if ((!newf) ^ (!old)) inet6_netconf_notify_devconf(net, NETCONFA_FORWARDING, NETCONFA_IFINDEX_DEFAULT, net->ipv6.devconf_dflt); rtnl_unlock(); return 0; } if (p == &net->ipv6.devconf_all->forwarding) { net->ipv6.devconf_dflt->forwarding = newf; addrconf_forward_change(net, newf); if ((!newf) ^ (!old)) inet6_netconf_notify_devconf(net, NETCONFA_FORWARDING, NETCONFA_IFINDEX_ALL, net->ipv6.devconf_all); } else if ((!newf) ^ (!old)) dev_forward_change((struct inet6_dev *)table->extra1); rtnl_unlock(); if (newf) rt6_purge_dflt_routers(net); return 1; } #endif /* Nobody refers to this ifaddr, destroy it */ void inet6_ifa_finish_destroy(struct inet6_ifaddr *ifp) { WARN_ON(!hlist_unhashed(&ifp->addr_lst)); #ifdef NET_REFCNT_DEBUG pr_debug("%s\n", __func__); #endif in6_dev_put(ifp->idev); if (cancel_delayed_work(&ifp->dad_work)) pr_notice("delayed DAD work was pending while freeing ifa=%p\n", ifp); if (ifp->state != INET6_IFADDR_STATE_DEAD) { pr_warn("Freeing alive inet6 address %p\n", ifp); return; } ip6_rt_put(ifp->rt); kfree_rcu(ifp, rcu); } static void ipv6_link_dev_addr(struct inet6_dev *idev, struct inet6_ifaddr *ifp) { struct list_head *p; int ifp_scope = ipv6_addr_src_scope(&ifp->addr); /* * Each device address list is sorted in order of scope - * global before linklocal. */ list_for_each(p, &idev->addr_list) { struct inet6_ifaddr *ifa = list_entry(p, struct inet6_ifaddr, if_list); if (ifp_scope >= ipv6_addr_src_scope(&ifa->addr)) break; } list_add_tail(&ifp->if_list, p); } static u32 inet6_addr_hash(const struct in6_addr *addr) { return hash_32(ipv6_addr_hash(addr), IN6_ADDR_HSIZE_SHIFT); } /* On success it returns ifp with increased reference count */ static struct inet6_ifaddr * ipv6_add_addr(struct inet6_dev *idev, const struct in6_addr *addr, const struct in6_addr *peer_addr, int pfxlen, int scope, u32 flags, u32 valid_lft, u32 prefered_lft) { struct inet6_ifaddr *ifa = NULL; struct rt6_info *rt; unsigned int hash; int err = 0; int addr_type = ipv6_addr_type(addr); if (addr_type == IPV6_ADDR_ANY || addr_type & IPV6_ADDR_MULTICAST || (!(idev->dev->flags & IFF_LOOPBACK) && addr_type & IPV6_ADDR_LOOPBACK)) return ERR_PTR(-EADDRNOTAVAIL); rcu_read_lock_bh(); if (idev->dead) { err = -ENODEV; /*XXX*/ goto out2; } if (idev->cnf.disable_ipv6) { err = -EACCES; goto out2; } spin_lock(&addrconf_hash_lock); /* Ignore adding duplicate addresses on an interface */ if (ipv6_chk_same_addr(dev_net(idev->dev), addr, idev->dev)) { ADBG("ipv6_add_addr: already assigned\n"); err = -EEXIST; goto out; } ifa = kzalloc(sizeof(struct inet6_ifaddr), GFP_ATOMIC); if (ifa == NULL) { ADBG("ipv6_add_addr: malloc failed\n"); err = -ENOBUFS; goto out; } rt = addrconf_dst_alloc(idev, addr, false); if (IS_ERR(rt)) { err = PTR_ERR(rt); goto out; } neigh_parms_data_state_setall(idev->nd_parms); ifa->addr = *addr; if (peer_addr) ifa->peer_addr = *peer_addr; spin_lock_init(&ifa->lock); spin_lock_init(&ifa->state_lock); INIT_DELAYED_WORK(&ifa->dad_work, addrconf_dad_work); INIT_HLIST_NODE(&ifa->addr_lst); ifa->scope = scope; ifa->prefix_len = pfxlen; ifa->flags = flags | IFA_F_TENTATIVE; ifa->valid_lft = valid_lft; ifa->prefered_lft = prefered_lft; ifa->cstamp = ifa->tstamp = jiffies; ifa->tokenized = false; ifa->rt = rt; ifa->idev = idev; in6_dev_hold(idev); /* For caller */ in6_ifa_hold(ifa); /* Add to big hash table */ hash = inet6_addr_hash(addr); hlist_add_head_rcu(&ifa->addr_lst, &inet6_addr_lst[hash]); spin_unlock(&addrconf_hash_lock); write_lock(&idev->lock); /* Add to inet6_dev unicast addr list. */ ipv6_link_dev_addr(idev, ifa); if (ifa->flags&IFA_F_TEMPORARY) { list_add(&ifa->tmp_list, &idev->tempaddr_list); in6_ifa_hold(ifa); } in6_ifa_hold(ifa); write_unlock(&idev->lock); out2: rcu_read_unlock_bh(); if (likely(err == 0)) inet6addr_notifier_call_chain(NETDEV_UP, ifa); else { kfree(ifa); ifa = ERR_PTR(err); } return ifa; out: spin_unlock(&addrconf_hash_lock); goto out2; } enum cleanup_prefix_rt_t { CLEANUP_PREFIX_RT_NOP, /* no cleanup action for prefix route */ CLEANUP_PREFIX_RT_DEL, /* delete the prefix route */ CLEANUP_PREFIX_RT_EXPIRE, /* update the lifetime of the prefix route */ }; /* * Check, whether the prefix for ifp would still need a prefix route * after deleting ifp. The function returns one of the CLEANUP_PREFIX_RT_* * constants. * * 1) we don't purge prefix if address was not permanent. * prefix is managed by its own lifetime. * 2) we also don't purge, if the address was IFA_F_NOPREFIXROUTE. * 3) if there are no addresses, delete prefix. * 4) if there are still other permanent address(es), * corresponding prefix is still permanent. * 5) if there are still other addresses with IFA_F_NOPREFIXROUTE, * don't purge the prefix, assume user space is managing it. * 6) otherwise, update prefix lifetime to the * longest valid lifetime among the corresponding * addresses on the device. * Note: subsequent RA will update lifetime. **/ static enum cleanup_prefix_rt_t check_cleanup_prefix_route(struct inet6_ifaddr *ifp, unsigned long *expires) { struct inet6_ifaddr *ifa; struct inet6_dev *idev = ifp->idev; unsigned long lifetime; enum cleanup_prefix_rt_t action = CLEANUP_PREFIX_RT_DEL; *expires = jiffies; list_for_each_entry(ifa, &idev->addr_list, if_list) { if (ifa == ifp) continue; if (!ipv6_prefix_equal(&ifa->addr, &ifp->addr, ifp->prefix_len)) continue; if (ifa->flags & (IFA_F_PERMANENT | IFA_F_NOPREFIXROUTE)) return CLEANUP_PREFIX_RT_NOP; action = CLEANUP_PREFIX_RT_EXPIRE; spin_lock(&ifa->lock); lifetime = addrconf_timeout_fixup(ifa->valid_lft, HZ); /* * Note: Because this address is * not permanent, lifetime < * LONG_MAX / HZ here. */ if (time_before(*expires, ifa->tstamp + lifetime * HZ)) *expires = ifa->tstamp + lifetime * HZ; spin_unlock(&ifa->lock); } return action; } static void cleanup_prefix_route(struct inet6_ifaddr *ifp, unsigned long expires, bool del_rt) { struct rt6_info *rt; rt = addrconf_get_prefix_route(&ifp->addr, ifp->prefix_len, ifp->idev->dev, 0, RTF_GATEWAY | RTF_DEFAULT); if (rt) { if (del_rt) ip6_del_rt(rt); else { if (!(rt->rt6i_flags & RTF_EXPIRES)) rt6_set_expires(rt, expires); ip6_rt_put(rt); } } } /* This function wants to get referenced ifp and releases it before return */ static void ipv6_del_addr(struct inet6_ifaddr *ifp) { int state; enum cleanup_prefix_rt_t action = CLEANUP_PREFIX_RT_NOP; unsigned long expires; ASSERT_RTNL(); spin_lock_bh(&ifp->state_lock); state = ifp->state; ifp->state = INET6_IFADDR_STATE_DEAD; spin_unlock_bh(&ifp->state_lock); if (state == INET6_IFADDR_STATE_DEAD) goto out; spin_lock_bh(&addrconf_hash_lock); hlist_del_init_rcu(&ifp->addr_lst); spin_unlock_bh(&addrconf_hash_lock); write_lock_bh(&ifp->idev->lock); if (ifp->flags&IFA_F_TEMPORARY) { list_del(&ifp->tmp_list); if (ifp->ifpub) { in6_ifa_put(ifp->ifpub); ifp->ifpub = NULL; } __in6_ifa_put(ifp); } if (ifp->flags & IFA_F_PERMANENT && !(ifp->flags & IFA_F_NOPREFIXROUTE)) action = check_cleanup_prefix_route(ifp, &expires); list_del_init(&ifp->if_list); __in6_ifa_put(ifp); write_unlock_bh(&ifp->idev->lock); addrconf_del_dad_work(ifp); ipv6_ifa_notify(RTM_DELADDR, ifp); inet6addr_notifier_call_chain(NETDEV_DOWN, ifp); if (action != CLEANUP_PREFIX_RT_NOP) { cleanup_prefix_route(ifp, expires, action == CLEANUP_PREFIX_RT_DEL); } /* clean up prefsrc entries */ rt6_remove_prefsrc(ifp); out: in6_ifa_put(ifp); } static int ipv6_create_tempaddr(struct inet6_ifaddr *ifp, struct inet6_ifaddr *ift) { struct inet6_dev *idev = ifp->idev; struct in6_addr addr, *tmpaddr; unsigned long tmp_prefered_lft, tmp_valid_lft, tmp_tstamp, age; unsigned long regen_advance; int tmp_plen; int ret = 0; u32 addr_flags; unsigned long now = jiffies; write_lock_bh(&idev->lock); if (ift) { spin_lock_bh(&ift->lock); memcpy(&addr.s6_addr[8], &ift->addr.s6_addr[8], 8); spin_unlock_bh(&ift->lock); tmpaddr = &addr; } else { tmpaddr = NULL; } retry: in6_dev_hold(idev); if (idev->cnf.use_tempaddr <= 0) { write_unlock_bh(&idev->lock); pr_info("%s: use_tempaddr is disabled\n", __func__); in6_dev_put(idev); ret = -1; goto out; } spin_lock_bh(&ifp->lock); if (ifp->regen_count++ >= idev->cnf.regen_max_retry) { idev->cnf.use_tempaddr = -1; /*XXX*/ spin_unlock_bh(&ifp->lock); write_unlock_bh(&idev->lock); pr_warn("%s: regeneration time exceeded - disabled temporary address support\n", __func__); in6_dev_put(idev); ret = -1; goto out; } in6_ifa_hold(ifp); memcpy(addr.s6_addr, ifp->addr.s6_addr, 8); __ipv6_try_regen_rndid(idev, tmpaddr); memcpy(&addr.s6_addr[8], idev->rndid, 8); age = (now - ifp->tstamp) / HZ; tmp_valid_lft = min_t(__u32, ifp->valid_lft, idev->cnf.temp_valid_lft + age); tmp_prefered_lft = min_t(__u32, ifp->prefered_lft, idev->cnf.temp_prefered_lft + age - idev->cnf.max_desync_factor); tmp_plen = ifp->prefix_len; tmp_tstamp = ifp->tstamp; spin_unlock_bh(&ifp->lock); regen_advance = idev->cnf.regen_max_retry * idev->cnf.dad_transmits * NEIGH_VAR(idev->nd_parms, RETRANS_TIME) / HZ; write_unlock_bh(&idev->lock); /* A temporary address is created only if this calculated Preferred * Lifetime is greater than REGEN_ADVANCE time units. In particular, * an implementation must not create a temporary address with a zero * Preferred Lifetime. * Use age calculation as in addrconf_verify to avoid unnecessary * temporary addresses being generated. */ age = (now - tmp_tstamp + ADDRCONF_TIMER_FUZZ_MINUS) / HZ; if (tmp_prefered_lft <= regen_advance + age) { in6_ifa_put(ifp); in6_dev_put(idev); ret = -1; goto out; } addr_flags = IFA_F_TEMPORARY; /* set in addrconf_prefix_rcv() */ if (ifp->flags & IFA_F_OPTIMISTIC) addr_flags |= IFA_F_OPTIMISTIC; ift = ipv6_add_addr(idev, &addr, NULL, tmp_plen, ipv6_addr_scope(&addr), addr_flags, tmp_valid_lft, tmp_prefered_lft); if (IS_ERR(ift)) { in6_ifa_put(ifp); in6_dev_put(idev); pr_info("%s: retry temporary address regeneration\n", __func__); tmpaddr = &addr; write_lock_bh(&idev->lock); goto retry; } spin_lock_bh(&ift->lock); ift->ifpub = ifp; ift->cstamp = now; ift->tstamp = tmp_tstamp; spin_unlock_bh(&ift->lock); addrconf_dad_start(ift); in6_ifa_put(ift); in6_dev_put(idev); out: return ret; } /* * Choose an appropriate source address (RFC3484) */ enum { IPV6_SADDR_RULE_INIT = 0, IPV6_SADDR_RULE_LOCAL, IPV6_SADDR_RULE_SCOPE, IPV6_SADDR_RULE_PREFERRED, #ifdef CONFIG_IPV6_MIP6 IPV6_SADDR_RULE_HOA, #endif IPV6_SADDR_RULE_OIF, IPV6_SADDR_RULE_LABEL, IPV6_SADDR_RULE_PRIVACY, IPV6_SADDR_RULE_ORCHID, IPV6_SADDR_RULE_PREFIX, #ifdef CONFIG_IPV6_OPTIMISTIC_DAD IPV6_SADDR_RULE_NOT_OPTIMISTIC, #endif IPV6_SADDR_RULE_MAX }; struct ipv6_saddr_score { int rule; int addr_type; struct inet6_ifaddr *ifa; DECLARE_BITMAP(scorebits, IPV6_SADDR_RULE_MAX); int scopedist; int matchlen; }; struct ipv6_saddr_dst { const struct in6_addr *addr; int ifindex; int scope; int label; unsigned int prefs; }; static inline int ipv6_saddr_preferred(int type) { if (type & (IPV6_ADDR_MAPPED|IPV6_ADDR_COMPATv4|IPV6_ADDR_LOOPBACK)) return 1; return 0; } static inline bool ipv6_use_optimistic_addr(struct inet6_dev *idev) { #ifdef CONFIG_IPV6_OPTIMISTIC_DAD return idev && idev->cnf.optimistic_dad && idev->cnf.use_optimistic; #else return false; #endif } static int ipv6_get_saddr_eval(struct net *net, struct ipv6_saddr_score *score, struct ipv6_saddr_dst *dst, int i) { int ret; if (i <= score->rule) { switch (i) { case IPV6_SADDR_RULE_SCOPE: ret = score->scopedist; break; case IPV6_SADDR_RULE_PREFIX: ret = score->matchlen; break; default: ret = !!test_bit(i, score->scorebits); } goto out; } switch (i) { case IPV6_SADDR_RULE_INIT: /* Rule 0: remember if hiscore is not ready yet */ ret = !!score->ifa; break; case IPV6_SADDR_RULE_LOCAL: /* Rule 1: Prefer same address */ ret = ipv6_addr_equal(&score->ifa->addr, dst->addr); break; case IPV6_SADDR_RULE_SCOPE: /* Rule 2: Prefer appropriate scope * * ret * ^ * -1 | d 15 * ---+--+-+---> scope * | * | d is scope of the destination. * B-d | \ * | \ <- smaller scope is better if * B-15 | \ if scope is enough for destination. * | ret = B - scope (-1 <= scope >= d <= 15). * d-C-1 | / * |/ <- greater is better * -C / if scope is not enough for destination. * /| ret = scope - C (-1 <= d < scope <= 15). * * d - C - 1 < B -15 (for all -1 <= d <= 15). * C > d + 14 - B >= 15 + 14 - B = 29 - B. * Assume B = 0 and we get C > 29. */ ret = __ipv6_addr_src_scope(score->addr_type); if (ret >= dst->scope) ret = -ret; else ret -= 128; /* 30 is enough */ score->scopedist = ret; break; case IPV6_SADDR_RULE_PREFERRED: { /* Rule 3: Avoid deprecated and optimistic addresses */ u8 avoid = IFA_F_DEPRECATED; if (!ipv6_use_optimistic_addr(score->ifa->idev)) avoid |= IFA_F_OPTIMISTIC; ret = ipv6_saddr_preferred(score->addr_type) || !(score->ifa->flags & avoid); break; } #ifdef CONFIG_IPV6_MIP6 case IPV6_SADDR_RULE_HOA: { /* Rule 4: Prefer home address */ int prefhome = !(dst->prefs & IPV6_PREFER_SRC_COA); ret = !(score->ifa->flags & IFA_F_HOMEADDRESS) ^ prefhome; break; } #endif case IPV6_SADDR_RULE_OIF: /* Rule 5: Prefer outgoing interface */ ret = (!dst->ifindex || dst->ifindex == score->ifa->idev->dev->ifindex); break; case IPV6_SADDR_RULE_LABEL: /* Rule 6: Prefer matching label */ ret = ipv6_addr_label(net, &score->ifa->addr, score->addr_type, score->ifa->idev->dev->ifindex) == dst->label; break; case IPV6_SADDR_RULE_PRIVACY: { /* Rule 7: Prefer public address * Note: prefer temporary address if use_tempaddr >= 2 */ int preftmp = dst->prefs & (IPV6_PREFER_SRC_PUBLIC|IPV6_PREFER_SRC_TMP) ? !!(dst->prefs & IPV6_PREFER_SRC_TMP) : score->ifa->idev->cnf.use_tempaddr >= 2; ret = (!(score->ifa->flags & IFA_F_TEMPORARY)) ^ preftmp; break; } case IPV6_SADDR_RULE_ORCHID: /* Rule 8-: Prefer ORCHID vs ORCHID or * non-ORCHID vs non-ORCHID */ ret = !(ipv6_addr_orchid(&score->ifa->addr) ^ ipv6_addr_orchid(dst->addr)); break; case IPV6_SADDR_RULE_PREFIX: /* Rule 8: Use longest matching prefix */ ret = ipv6_addr_diff(&score->ifa->addr, dst->addr); if (ret > score->ifa->prefix_len) ret = score->ifa->prefix_len; score->matchlen = ret; break; #ifdef CONFIG_IPV6_OPTIMISTIC_DAD case IPV6_SADDR_RULE_NOT_OPTIMISTIC: /* Optimistic addresses still have lower precedence than other * preferred addresses. */ ret = !(score->ifa->flags & IFA_F_OPTIMISTIC); break; #endif default: ret = 0; } if (ret) __set_bit(i, score->scorebits); score->rule = i; out: return ret; } int ipv6_dev_get_saddr(struct net *net, const struct net_device *dst_dev, const struct in6_addr *daddr, unsigned int prefs, struct in6_addr *saddr) { struct ipv6_saddr_score scores[2], *score = &scores[0], *hiscore = &scores[1]; struct ipv6_saddr_dst dst; struct net_device *dev; int dst_type; dst_type = __ipv6_addr_type(daddr); dst.addr = daddr; dst.ifindex = dst_dev ? dst_dev->ifindex : 0; dst.scope = __ipv6_addr_src_scope(dst_type); dst.label = ipv6_addr_label(net, daddr, dst_type, dst.ifindex); dst.prefs = prefs; hiscore->rule = -1; hiscore->ifa = NULL; rcu_read_lock(); for_each_netdev_rcu(net, dev) { struct inet6_dev *idev; /* Candidate Source Address (section 4) * - multicast and link-local destination address, * the set of candidate source address MUST only * include addresses assigned to interfaces * belonging to the same link as the outgoing * interface. * (- For site-local destination addresses, the * set of candidate source addresses MUST only * include addresses assigned to interfaces * belonging to the same site as the outgoing * interface.) */ if (((dst_type & IPV6_ADDR_MULTICAST) || dst.scope <= IPV6_ADDR_SCOPE_LINKLOCAL) && dst.ifindex && dev->ifindex != dst.ifindex) continue; idev = __in6_dev_get(dev); if (!idev) continue; read_lock_bh(&idev->lock); list_for_each_entry(score->ifa, &idev->addr_list, if_list) { int i; /* * - Tentative Address (RFC2462 section 5.4) * - A tentative address is not considered * "assigned to an interface" in the traditional * sense, unless it is also flagged as optimistic. * - Candidate Source Address (section 4) * - In any case, anycast addresses, multicast * addresses, and the unspecified address MUST * NOT be included in a candidate set. */ if ((score->ifa->flags & IFA_F_TENTATIVE) && (!(score->ifa->flags & IFA_F_OPTIMISTIC))) continue; score->addr_type = __ipv6_addr_type(&score->ifa->addr); if (unlikely(score->addr_type == IPV6_ADDR_ANY || score->addr_type & IPV6_ADDR_MULTICAST)) { net_dbg_ratelimited("ADDRCONF: unspecified / multicast address assigned as unicast address on %s", dev->name); continue; } score->rule = -1; bitmap_zero(score->scorebits, IPV6_SADDR_RULE_MAX); for (i = 0; i < IPV6_SADDR_RULE_MAX; i++) { int minihiscore, miniscore; minihiscore = ipv6_get_saddr_eval(net, hiscore, &dst, i); miniscore = ipv6_get_saddr_eval(net, score, &dst, i); if (minihiscore > miniscore) { if (i == IPV6_SADDR_RULE_SCOPE && score->scopedist > 0) { /* * special case: * each remaining entry * has too small (not enough) * scope, because ifa entries * are sorted by their scope * values. */ goto try_nextdev; } break; } else if (minihiscore < miniscore) { if (hiscore->ifa) in6_ifa_put(hiscore->ifa); in6_ifa_hold(score->ifa); swap(hiscore, score); /* restore our iterator */ score->ifa = hiscore->ifa; break; } } } try_nextdev: read_unlock_bh(&idev->lock); } rcu_read_unlock(); if (!hiscore->ifa) return -EADDRNOTAVAIL; *saddr = hiscore->ifa->addr; in6_ifa_put(hiscore->ifa); return 0; } EXPORT_SYMBOL(ipv6_dev_get_saddr); int __ipv6_get_lladdr(struct inet6_dev *idev, struct in6_addr *addr, u32 banned_flags) { struct inet6_ifaddr *ifp; int err = -EADDRNOTAVAIL; list_for_each_entry_reverse(ifp, &idev->addr_list, if_list) { if (ifp->scope > IFA_LINK) break; if (ifp->scope == IFA_LINK && !(ifp->flags & banned_flags)) { *addr = ifp->addr; err = 0; break; } } return err; } int ipv6_get_lladdr(struct net_device *dev, struct in6_addr *addr, u32 banned_flags) { struct inet6_dev *idev; int err = -EADDRNOTAVAIL; rcu_read_lock(); idev = __in6_dev_get(dev); if (idev) { read_lock_bh(&idev->lock); err = __ipv6_get_lladdr(idev, addr, banned_flags); read_unlock_bh(&idev->lock); } rcu_read_unlock(); return err; } static int ipv6_count_addresses(struct inet6_dev *idev) { int cnt = 0; struct inet6_ifaddr *ifp; read_lock_bh(&idev->lock); list_for_each_entry(ifp, &idev->addr_list, if_list) cnt++; read_unlock_bh(&idev->lock); return cnt; } int ipv6_chk_addr(struct net *net, const struct in6_addr *addr, const struct net_device *dev, int strict) { return ipv6_chk_addr_and_flags(net, addr, dev, strict, IFA_F_TENTATIVE); } EXPORT_SYMBOL(ipv6_chk_addr); int ipv6_chk_addr_and_flags(struct net *net, const struct in6_addr *addr, const struct net_device *dev, int strict, u32 banned_flags) { struct inet6_ifaddr *ifp; unsigned int hash = inet6_addr_hash(addr); u32 ifp_flags; rcu_read_lock_bh(); hlist_for_each_entry_rcu(ifp, &inet6_addr_lst[hash], addr_lst) { if (!net_eq(dev_net(ifp->idev->dev), net)) continue; /* Decouple optimistic from tentative for evaluation here. * Ban optimistic addresses explicitly, when required. */ ifp_flags = (ifp->flags&IFA_F_OPTIMISTIC) ? (ifp->flags&~IFA_F_TENTATIVE) : ifp->flags; if (ipv6_addr_equal(&ifp->addr, addr) && !(ifp_flags&banned_flags) && (dev == NULL || ifp->idev->dev == dev || !(ifp->scope&(IFA_LINK|IFA_HOST) || strict))) { rcu_read_unlock_bh(); return 1; } } rcu_read_unlock_bh(); return 0; } EXPORT_SYMBOL(ipv6_chk_addr_and_flags); static bool ipv6_chk_same_addr(struct net *net, const struct in6_addr *addr, struct net_device *dev) { unsigned int hash = inet6_addr_hash(addr); struct inet6_ifaddr *ifp; hlist_for_each_entry(ifp, &inet6_addr_lst[hash], addr_lst) { if (!net_eq(dev_net(ifp->idev->dev), net)) continue; if (ipv6_addr_equal(&ifp->addr, addr)) { if (dev == NULL || ifp->idev->dev == dev) return true; } } return false; } /* Compares an address/prefix_len with addresses on device @dev. * If one is found it returns true. */ bool ipv6_chk_custom_prefix(const struct in6_addr *addr, const unsigned int prefix_len, struct net_device *dev) { struct inet6_dev *idev; struct inet6_ifaddr *ifa; bool ret = false; rcu_read_lock(); idev = __in6_dev_get(dev); if (idev) { read_lock_bh(&idev->lock); list_for_each_entry(ifa, &idev->addr_list, if_list) { ret = ipv6_prefix_equal(addr, &ifa->addr, prefix_len); if (ret) break; } read_unlock_bh(&idev->lock); } rcu_read_unlock(); return ret; } EXPORT_SYMBOL(ipv6_chk_custom_prefix); int ipv6_chk_prefix(const struct in6_addr *addr, struct net_device *dev) { struct inet6_dev *idev; struct inet6_ifaddr *ifa; int onlink; onlink = 0; rcu_read_lock(); idev = __in6_dev_get(dev); if (idev) { read_lock_bh(&idev->lock); list_for_each_entry(ifa, &idev->addr_list, if_list) { onlink = ipv6_prefix_equal(addr, &ifa->addr, ifa->prefix_len); if (onlink) break; } read_unlock_bh(&idev->lock); } rcu_read_unlock(); return onlink; } EXPORT_SYMBOL(ipv6_chk_prefix); struct inet6_ifaddr *ipv6_get_ifaddr(struct net *net, const struct in6_addr *addr, struct net_device *dev, int strict) { struct inet6_ifaddr *ifp, *result = NULL; unsigned int hash = inet6_addr_hash(addr); rcu_read_lock_bh(); hlist_for_each_entry_rcu_bh(ifp, &inet6_addr_lst[hash], addr_lst) { if (!net_eq(dev_net(ifp->idev->dev), net)) continue; if (ipv6_addr_equal(&ifp->addr, addr)) { if (dev == NULL || ifp->idev->dev == dev || !(ifp->scope&(IFA_LINK|IFA_HOST) || strict)) { result = ifp; in6_ifa_hold(ifp); break; } } } rcu_read_unlock_bh(); return result; } /* Gets referenced address, destroys ifaddr */ static void addrconf_dad_stop(struct inet6_ifaddr *ifp, int dad_failed) { if (ifp->flags&IFA_F_PERMANENT) { spin_lock_bh(&ifp->lock); addrconf_del_dad_work(ifp); ifp->flags |= IFA_F_TENTATIVE; if (dad_failed) ifp->flags |= IFA_F_DADFAILED; spin_unlock_bh(&ifp->lock); if (dad_failed) ipv6_ifa_notify(0, ifp); in6_ifa_put(ifp); } else if (ifp->flags&IFA_F_TEMPORARY) { struct inet6_ifaddr *ifpub; spin_lock_bh(&ifp->lock); ifpub = ifp->ifpub; if (ifpub) { in6_ifa_hold(ifpub); spin_unlock_bh(&ifp->lock); ipv6_create_tempaddr(ifpub, ifp); in6_ifa_put(ifpub); } else { spin_unlock_bh(&ifp->lock); } ipv6_del_addr(ifp); } else { ipv6_del_addr(ifp); } } static int addrconf_dad_end(struct inet6_ifaddr *ifp) { int err = -ENOENT; spin_lock_bh(&ifp->state_lock); if (ifp->state == INET6_IFADDR_STATE_DAD) { ifp->state = INET6_IFADDR_STATE_POSTDAD; err = 0; } spin_unlock_bh(&ifp->state_lock); return err; } void addrconf_dad_failure(struct inet6_ifaddr *ifp) { struct inet6_dev *idev = ifp->idev; if (addrconf_dad_end(ifp)) { in6_ifa_put(ifp); return; } net_info_ratelimited("%s: IPv6 duplicate address %pI6c detected!\n", ifp->idev->dev->name, &ifp->addr); if (idev->cnf.accept_dad > 1 && !idev->cnf.disable_ipv6) { struct in6_addr addr; addr.s6_addr32[0] = htonl(0xfe800000); addr.s6_addr32[1] = 0; if (!ipv6_generate_eui64(addr.s6_addr + 8, idev->dev) && ipv6_addr_equal(&ifp->addr, &addr)) { /* DAD failed for link-local based on MAC address */ idev->cnf.disable_ipv6 = 1; pr_info("%s: IPv6 being disabled!\n", ifp->idev->dev->name); } } spin_lock_bh(&ifp->state_lock); /* transition from _POSTDAD to _ERRDAD */ ifp->state = INET6_IFADDR_STATE_ERRDAD; spin_unlock_bh(&ifp->state_lock); addrconf_mod_dad_work(ifp, 0); } /* Join to solicited addr multicast group. * caller must hold RTNL */ void addrconf_join_solict(struct net_device *dev, const struct in6_addr *addr) { struct in6_addr maddr; if (dev->flags&(IFF_LOOPBACK|IFF_NOARP)) return; addrconf_addr_solict_mult(addr, &maddr); ipv6_dev_mc_inc(dev, &maddr); } /* caller must hold RTNL */ void addrconf_leave_solict(struct inet6_dev *idev, const struct in6_addr *addr) { struct in6_addr maddr; if (idev->dev->flags&(IFF_LOOPBACK|IFF_NOARP)) return; addrconf_addr_solict_mult(addr, &maddr); __ipv6_dev_mc_dec(idev, &maddr); } /* caller must hold RTNL */ static void addrconf_join_anycast(struct inet6_ifaddr *ifp) { struct in6_addr addr; if (ifp->prefix_len >= 127) /* RFC 6164 */ return; ipv6_addr_prefix(&addr, &ifp->addr, ifp->prefix_len); if (ipv6_addr_any(&addr)) return; __ipv6_dev_ac_inc(ifp->idev, &addr); } /* caller must hold RTNL */ static void addrconf_leave_anycast(struct inet6_ifaddr *ifp) { struct in6_addr addr; if (ifp->prefix_len >= 127) /* RFC 6164 */ return; ipv6_addr_prefix(&addr, &ifp->addr, ifp->prefix_len); if (ipv6_addr_any(&addr)) return; __ipv6_dev_ac_dec(ifp->idev, &addr); } static int addrconf_ifid_eui48(u8 *eui, struct net_device *dev) { if (dev->addr_len != ETH_ALEN) return -1; memcpy(eui, dev->dev_addr, 3); memcpy(eui + 5, dev->dev_addr + 3, 3); /* * The zSeries OSA network cards can be shared among various * OS instances, but the OSA cards have only one MAC address. * This leads to duplicate address conflicts in conjunction * with IPv6 if more than one instance uses the same card. * * The driver for these cards can deliver a unique 16-bit * identifier for each instance sharing the same card. It is * placed instead of 0xFFFE in the interface identifier. The * "u" bit of the interface identifier is not inverted in this * case. Hence the resulting interface identifier has local * scope according to RFC2373. */ if (dev->dev_id) { eui[3] = (dev->dev_id >> 8) & 0xFF; eui[4] = dev->dev_id & 0xFF; } else { eui[3] = 0xFF; eui[4] = 0xFE; eui[0] ^= 2; } return 0; } static int addrconf_ifid_eui64(u8 *eui, struct net_device *dev) { if (dev->addr_len != IEEE802154_ADDR_LEN) return -1; memcpy(eui, dev->dev_addr, 8); eui[0] ^= 2; return 0; } static int addrconf_ifid_ieee1394(u8 *eui, struct net_device *dev) { union fwnet_hwaddr *ha; if (dev->addr_len != FWNET_ALEN) return -1; ha = (union fwnet_hwaddr *)dev->dev_addr; memcpy(eui, &ha->uc.uniq_id, sizeof(ha->uc.uniq_id)); eui[0] ^= 2; return 0; } static int addrconf_ifid_arcnet(u8 *eui, struct net_device *dev) { /* XXX: inherit EUI-64 from other interface -- yoshfuji */ if (dev->addr_len != ARCNET_ALEN) return -1; memset(eui, 0, 7); eui[7] = *(u8 *)dev->dev_addr; return 0; } static int addrconf_ifid_infiniband(u8 *eui, struct net_device *dev) { if (dev->addr_len != INFINIBAND_ALEN) return -1; memcpy(eui, dev->dev_addr + 12, 8); eui[0] |= 2; return 0; } static int __ipv6_isatap_ifid(u8 *eui, __be32 addr) { if (addr == 0) return -1; eui[0] = (ipv4_is_zeronet(addr) || ipv4_is_private_10(addr) || ipv4_is_loopback(addr) || ipv4_is_linklocal_169(addr) || ipv4_is_private_172(addr) || ipv4_is_test_192(addr) || ipv4_is_anycast_6to4(addr) || ipv4_is_private_192(addr) || ipv4_is_test_198(addr) || ipv4_is_multicast(addr) || ipv4_is_lbcast(addr)) ? 0x00 : 0x02; eui[1] = 0; eui[2] = 0x5E; eui[3] = 0xFE; memcpy(eui + 4, &addr, 4); return 0; } static int addrconf_ifid_sit(u8 *eui, struct net_device *dev) { if (dev->priv_flags & IFF_ISATAP) return __ipv6_isatap_ifid(eui, *(__be32 *)dev->dev_addr); return -1; } static int addrconf_ifid_gre(u8 *eui, struct net_device *dev) { return __ipv6_isatap_ifid(eui, *(__be32 *)dev->dev_addr); } static int addrconf_ifid_ip6tnl(u8 *eui, struct net_device *dev) { memcpy(eui, dev->perm_addr, 3); memcpy(eui + 5, dev->perm_addr + 3, 3); eui[3] = 0xFF; eui[4] = 0xFE; eui[0] ^= 2; return 0; } static int ipv6_generate_eui64(u8 *eui, struct net_device *dev) { switch (dev->type) { case ARPHRD_ETHER: case ARPHRD_FDDI: return addrconf_ifid_eui48(eui, dev); case ARPHRD_ARCNET: return addrconf_ifid_arcnet(eui, dev); case ARPHRD_INFINIBAND: return addrconf_ifid_infiniband(eui, dev); case ARPHRD_SIT: return addrconf_ifid_sit(eui, dev); case ARPHRD_IPGRE: return addrconf_ifid_gre(eui, dev); case ARPHRD_6LOWPAN: case ARPHRD_IEEE802154: return addrconf_ifid_eui64(eui, dev); case ARPHRD_IEEE1394: return addrconf_ifid_ieee1394(eui, dev); case ARPHRD_TUNNEL6: return addrconf_ifid_ip6tnl(eui, dev); } return -1; } static int ipv6_inherit_eui64(u8 *eui, struct inet6_dev *idev) { int err = -1; struct inet6_ifaddr *ifp; read_lock_bh(&idev->lock); list_for_each_entry_reverse(ifp, &idev->addr_list, if_list) { if (ifp->scope > IFA_LINK) break; if (ifp->scope == IFA_LINK && !(ifp->flags&IFA_F_TENTATIVE)) { memcpy(eui, ifp->addr.s6_addr+8, 8); err = 0; break; } } read_unlock_bh(&idev->lock); return err; } /* (re)generation of randomized interface identifier (RFC 3041 3.2, 3.5) */ static void __ipv6_regen_rndid(struct inet6_dev *idev) { regen: get_random_bytes(idev->rndid, sizeof(idev->rndid)); idev->rndid[0] &= ~0x02; /* * <draft-ietf-ipngwg-temp-addresses-v2-00.txt>: * check if generated address is not inappropriate * * - Reserved subnet anycast (RFC 2526) * 11111101 11....11 1xxxxxxx * - ISATAP (RFC4214) 6.1 * 00-00-5E-FE-xx-xx-xx-xx * - value 0 * - XXX: already assigned to an address on the device */ if (idev->rndid[0] == 0xfd && (idev->rndid[1]&idev->rndid[2]&idev->rndid[3]&idev->rndid[4]&idev->rndid[5]&idev->rndid[6]) == 0xff && (idev->rndid[7]&0x80)) goto regen; if ((idev->rndid[0]|idev->rndid[1]) == 0) { if (idev->rndid[2] == 0x5e && idev->rndid[3] == 0xfe) goto regen; if ((idev->rndid[2]|idev->rndid[3]|idev->rndid[4]|idev->rndid[5]|idev->rndid[6]|idev->rndid[7]) == 0x00) goto regen; } } static void ipv6_regen_rndid(unsigned long data) { struct inet6_dev *idev = (struct inet6_dev *) data; unsigned long expires; rcu_read_lock_bh(); write_lock_bh(&idev->lock); if (idev->dead) goto out; __ipv6_regen_rndid(idev); expires = jiffies + idev->cnf.temp_prefered_lft * HZ - idev->cnf.regen_max_retry * idev->cnf.dad_transmits * NEIGH_VAR(idev->nd_parms, RETRANS_TIME) - idev->cnf.max_desync_factor * HZ; if (time_before(expires, jiffies)) { pr_warn("%s: too short regeneration interval; timer disabled for %s\n", __func__, idev->dev->name); goto out; } if (!mod_timer(&idev->regen_timer, expires)) in6_dev_hold(idev); out: write_unlock_bh(&idev->lock); rcu_read_unlock_bh(); in6_dev_put(idev); } static void __ipv6_try_regen_rndid(struct inet6_dev *idev, struct in6_addr *tmpaddr) { if (tmpaddr && memcmp(idev->rndid, &tmpaddr->s6_addr[8], 8) == 0) __ipv6_regen_rndid(idev); } /* * Add prefix route. */ static void addrconf_prefix_route(struct in6_addr *pfx, int plen, struct net_device *dev, unsigned long expires, u32 flags) { struct fib6_config cfg = { .fc_table = RT6_TABLE_PREFIX, .fc_metric = IP6_RT_PRIO_ADDRCONF, .fc_ifindex = dev->ifindex, .fc_expires = expires, .fc_dst_len = plen, .fc_flags = RTF_UP | flags, .fc_nlinfo.nl_net = dev_net(dev), .fc_protocol = RTPROT_KERNEL, }; cfg.fc_dst = *pfx; /* Prevent useless cloning on PtP SIT. This thing is done here expecting that the whole class of non-broadcast devices need not cloning. */ #if IS_ENABLED(CONFIG_IPV6_SIT) if (dev->type == ARPHRD_SIT && (dev->flags & IFF_POINTOPOINT)) cfg.fc_flags |= RTF_NONEXTHOP; #endif ip6_route_add(&cfg); } static struct rt6_info *addrconf_get_prefix_route(const struct in6_addr *pfx, int plen, const struct net_device *dev, u32 flags, u32 noflags) { struct fib6_node *fn; struct rt6_info *rt = NULL; struct fib6_table *table; table = fib6_get_table(dev_net(dev), RT6_TABLE_PREFIX); if (table == NULL) return NULL; read_lock_bh(&table->tb6_lock); fn = fib6_locate(&table->tb6_root, pfx, plen, NULL, 0); if (!fn) goto out; for (rt = fn->leaf; rt; rt = rt->dst.rt6_next) { if (rt->dst.dev->ifindex != dev->ifindex) continue; if ((rt->rt6i_flags & flags) != flags) continue; if ((rt->rt6i_flags & noflags) != 0) continue; dst_hold(&rt->dst); break; } out: read_unlock_bh(&table->tb6_lock); return rt; } /* Create "default" multicast route to the interface */ static void addrconf_add_mroute(struct net_device *dev) { struct fib6_config cfg = { .fc_table = RT6_TABLE_LOCAL, .fc_metric = IP6_RT_PRIO_ADDRCONF, .fc_ifindex = dev->ifindex, .fc_dst_len = 8, .fc_flags = RTF_UP, .fc_nlinfo.nl_net = dev_net(dev), }; ipv6_addr_set(&cfg.fc_dst, htonl(0xFF000000), 0, 0, 0); ip6_route_add(&cfg); } static struct inet6_dev *addrconf_add_dev(struct net_device *dev) { struct inet6_dev *idev; ASSERT_RTNL(); idev = ipv6_find_idev(dev); if (!idev) return ERR_PTR(-ENOBUFS); if (idev->cnf.disable_ipv6) return ERR_PTR(-EACCES); /* Add default multicast route */ if (!(dev->flags & IFF_LOOPBACK)) addrconf_add_mroute(dev); return idev; } static void manage_tempaddrs(struct inet6_dev *idev, struct inet6_ifaddr *ifp, __u32 valid_lft, __u32 prefered_lft, bool create, unsigned long now) { u32 flags; struct inet6_ifaddr *ift; read_lock_bh(&idev->lock); /* update all temporary addresses in the list */ list_for_each_entry(ift, &idev->tempaddr_list, tmp_list) { int age, max_valid, max_prefered; if (ifp != ift->ifpub) continue; /* RFC 4941 section 3.3: * If a received option will extend the lifetime of a public * address, the lifetimes of temporary addresses should * be extended, subject to the overall constraint that no * temporary addresses should ever remain "valid" or "preferred" * for a time longer than (TEMP_VALID_LIFETIME) or * (TEMP_PREFERRED_LIFETIME - DESYNC_FACTOR), respectively. */ age = (now - ift->cstamp) / HZ; max_valid = idev->cnf.temp_valid_lft - age; if (max_valid < 0) max_valid = 0; max_prefered = idev->cnf.temp_prefered_lft - idev->cnf.max_desync_factor - age; if (max_prefered < 0) max_prefered = 0; if (valid_lft > max_valid) valid_lft = max_valid; if (prefered_lft > max_prefered) prefered_lft = max_prefered; spin_lock(&ift->lock); flags = ift->flags; ift->valid_lft = valid_lft; ift->prefered_lft = prefered_lft; ift->tstamp = now; if (prefered_lft > 0) ift->flags &= ~IFA_F_DEPRECATED; spin_unlock(&ift->lock); if (!(flags&IFA_F_TENTATIVE)) ipv6_ifa_notify(0, ift); } if ((create || list_empty(&idev->tempaddr_list)) && idev->cnf.use_tempaddr > 0) { /* When a new public address is created as described * in [ADDRCONF], also create a new temporary address. * Also create a temporary address if it's enabled but * no temporary address currently exists. */ read_unlock_bh(&idev->lock); ipv6_create_tempaddr(ifp, NULL); } else { read_unlock_bh(&idev->lock); } } void addrconf_prefix_rcv(struct net_device *dev, u8 *opt, int len, bool sllao) { struct prefix_info *pinfo; __u32 valid_lft; __u32 prefered_lft; int addr_type; struct inet6_dev *in6_dev; struct net *net = dev_net(dev); pinfo = (struct prefix_info *) opt; if (len < sizeof(struct prefix_info)) { ADBG("addrconf: prefix option too short\n"); return; } /* * Validation checks ([ADDRCONF], page 19) */ addr_type = ipv6_addr_type(&pinfo->prefix); if (addr_type & (IPV6_ADDR_MULTICAST|IPV6_ADDR_LINKLOCAL)) return; valid_lft = ntohl(pinfo->valid); prefered_lft = ntohl(pinfo->prefered); if (prefered_lft > valid_lft) { net_warn_ratelimited("addrconf: prefix option has invalid lifetime\n"); return; } in6_dev = in6_dev_get(dev); if (in6_dev == NULL) { net_dbg_ratelimited("addrconf: device %s not configured\n", dev->name); return; } /* * Two things going on here: * 1) Add routes for on-link prefixes * 2) Configure prefixes with the auto flag set */ if (pinfo->onlink) { struct rt6_info *rt; unsigned long rt_expires; /* Avoid arithmetic overflow. Really, we could * save rt_expires in seconds, likely valid_lft, * but it would require division in fib gc, that it * not good. */ if (HZ > USER_HZ) rt_expires = addrconf_timeout_fixup(valid_lft, HZ); else rt_expires = addrconf_timeout_fixup(valid_lft, USER_HZ); if (addrconf_finite_timeout(rt_expires)) rt_expires *= HZ; rt = addrconf_get_prefix_route(&pinfo->prefix, pinfo->prefix_len, dev, RTF_ADDRCONF | RTF_PREFIX_RT, RTF_GATEWAY | RTF_DEFAULT); if (rt) { /* Autoconf prefix route */ if (valid_lft == 0) { ip6_del_rt(rt); rt = NULL; } else if (addrconf_finite_timeout(rt_expires)) { /* not infinity */ rt6_set_expires(rt, jiffies + rt_expires); } else { rt6_clean_expires(rt); } } else if (valid_lft) { clock_t expires = 0; int flags = RTF_ADDRCONF | RTF_PREFIX_RT; if (addrconf_finite_timeout(rt_expires)) { /* not infinity */ flags |= RTF_EXPIRES; expires = jiffies_to_clock_t(rt_expires); } addrconf_prefix_route(&pinfo->prefix, pinfo->prefix_len, dev, expires, flags); } ip6_rt_put(rt); } /* Try to figure out our local address for this prefix */ if (pinfo->autoconf && in6_dev->cnf.autoconf) { struct inet6_ifaddr *ifp; struct in6_addr addr; int create = 0, update_lft = 0; bool tokenized = false; if (pinfo->prefix_len == 64) { memcpy(&addr, &pinfo->prefix, 8); if (!ipv6_addr_any(&in6_dev->token)) { read_lock_bh(&in6_dev->lock); memcpy(addr.s6_addr + 8, in6_dev->token.s6_addr + 8, 8); read_unlock_bh(&in6_dev->lock); tokenized = true; } else if (ipv6_generate_eui64(addr.s6_addr + 8, dev) && ipv6_inherit_eui64(addr.s6_addr + 8, in6_dev)) { in6_dev_put(in6_dev); return; } goto ok; } net_dbg_ratelimited("IPv6 addrconf: prefix with wrong length %d\n", pinfo->prefix_len); in6_dev_put(in6_dev); return; ok: ifp = ipv6_get_ifaddr(net, &addr, dev, 1); if (ifp == NULL && valid_lft) { int max_addresses = in6_dev->cnf.max_addresses; u32 addr_flags = 0; #ifdef CONFIG_IPV6_OPTIMISTIC_DAD if (in6_dev->cnf.optimistic_dad && !net->ipv6.devconf_all->forwarding && sllao) addr_flags = IFA_F_OPTIMISTIC; #endif /* Do not allow to create too much of autoconfigured * addresses; this would be too easy way to crash kernel. */ if (!max_addresses || ipv6_count_addresses(in6_dev) < max_addresses) ifp = ipv6_add_addr(in6_dev, &addr, NULL, pinfo->prefix_len, addr_type&IPV6_ADDR_SCOPE_MASK, addr_flags, valid_lft, prefered_lft); if (IS_ERR_OR_NULL(ifp)) { in6_dev_put(in6_dev); return; } update_lft = 0; create = 1; spin_lock_bh(&ifp->lock); ifp->flags |= IFA_F_MANAGETEMPADDR; ifp->cstamp = jiffies; ifp->tokenized = tokenized; spin_unlock_bh(&ifp->lock); addrconf_dad_start(ifp); } if (ifp) { u32 flags; unsigned long now; u32 stored_lft; /* update lifetime (RFC2462 5.5.3 e) */ spin_lock(&ifp->lock); now = jiffies; if (ifp->valid_lft > (now - ifp->tstamp) / HZ) stored_lft = ifp->valid_lft - (now - ifp->tstamp) / HZ; else stored_lft = 0; if (!update_lft && !create && stored_lft) { const u32 minimum_lft = min_t(u32, stored_lft, MIN_VALID_LIFETIME); valid_lft = max(valid_lft, minimum_lft); /* RFC4862 Section 5.5.3e: * "Note that the preferred lifetime of the * corresponding address is always reset to * the Preferred Lifetime in the received * Prefix Information option, regardless of * whether the valid lifetime is also reset or * ignored." * * So we should always update prefered_lft here. */ update_lft = 1; } if (update_lft) { ifp->valid_lft = valid_lft; ifp->prefered_lft = prefered_lft; ifp->tstamp = now; flags = ifp->flags; ifp->flags &= ~IFA_F_DEPRECATED; spin_unlock(&ifp->lock); if (!(flags&IFA_F_TENTATIVE)) ipv6_ifa_notify(0, ifp); } else spin_unlock(&ifp->lock); manage_tempaddrs(in6_dev, ifp, valid_lft, prefered_lft, create, now); in6_ifa_put(ifp); addrconf_verify(); } } inet6_prefix_notify(RTM_NEWPREFIX, in6_dev, pinfo); in6_dev_put(in6_dev); } /* * Set destination address. * Special case for SIT interfaces where we create a new "virtual" * device. */ int addrconf_set_dstaddr(struct net *net, void __user *arg) { struct in6_ifreq ireq; struct net_device *dev; int err = -EINVAL; rtnl_lock(); err = -EFAULT; if (copy_from_user(&ireq, arg, sizeof(struct in6_ifreq))) goto err_exit; dev = __dev_get_by_index(net, ireq.ifr6_ifindex); err = -ENODEV; if (dev == NULL) goto err_exit; #if IS_ENABLED(CONFIG_IPV6_SIT) if (dev->type == ARPHRD_SIT) { const struct net_device_ops *ops = dev->netdev_ops; struct ifreq ifr; struct ip_tunnel_parm p; err = -EADDRNOTAVAIL; if (!(ipv6_addr_type(&ireq.ifr6_addr) & IPV6_ADDR_COMPATv4)) goto err_exit; memset(&p, 0, sizeof(p)); p.iph.daddr = ireq.ifr6_addr.s6_addr32[3]; p.iph.saddr = 0; p.iph.version = 4; p.iph.ihl = 5; p.iph.protocol = IPPROTO_IPV6; p.iph.ttl = 64; ifr.ifr_ifru.ifru_data = (__force void __user *)&p; if (ops->ndo_do_ioctl) { mm_segment_t oldfs = get_fs(); set_fs(KERNEL_DS); err = ops->ndo_do_ioctl(dev, &ifr, SIOCADDTUNNEL); set_fs(oldfs); } else err = -EOPNOTSUPP; if (err == 0) { err = -ENOBUFS; dev = __dev_get_by_name(net, p.name); if (!dev) goto err_exit; err = dev_open(dev); } } #endif err_exit: rtnl_unlock(); return err; } /* * Manual configuration of address on an interface */ static int inet6_addr_add(struct net *net, int ifindex, const struct in6_addr *pfx, const struct in6_addr *peer_pfx, unsigned int plen, __u32 ifa_flags, __u32 prefered_lft, __u32 valid_lft) { struct inet6_ifaddr *ifp; struct inet6_dev *idev; struct net_device *dev; int scope; u32 flags; clock_t expires; unsigned long timeout; ASSERT_RTNL(); if (plen > 128) return -EINVAL; /* check the lifetime */ if (!valid_lft || prefered_lft > valid_lft) return -EINVAL; if (ifa_flags & IFA_F_MANAGETEMPADDR && plen != 64) return -EINVAL; dev = __dev_get_by_index(net, ifindex); if (!dev) return -ENODEV; idev = addrconf_add_dev(dev); if (IS_ERR(idev)) return PTR_ERR(idev); scope = ipv6_addr_scope(pfx); timeout = addrconf_timeout_fixup(valid_lft, HZ); if (addrconf_finite_timeout(timeout)) { expires = jiffies_to_clock_t(timeout * HZ); valid_lft = timeout; flags = RTF_EXPIRES; } else { expires = 0; flags = 0; ifa_flags |= IFA_F_PERMANENT; } timeout = addrconf_timeout_fixup(prefered_lft, HZ); if (addrconf_finite_timeout(timeout)) { if (timeout == 0) ifa_flags |= IFA_F_DEPRECATED; prefered_lft = timeout; } ifp = ipv6_add_addr(idev, pfx, peer_pfx, plen, scope, ifa_flags, valid_lft, prefered_lft); if (!IS_ERR(ifp)) { if (!(ifa_flags & IFA_F_NOPREFIXROUTE)) { addrconf_prefix_route(&ifp->addr, ifp->prefix_len, dev, expires, flags); } /* * Note that section 3.1 of RFC 4429 indicates * that the Optimistic flag should not be set for * manually configured addresses */ addrconf_dad_start(ifp); if (ifa_flags & IFA_F_MANAGETEMPADDR) manage_tempaddrs(idev, ifp, valid_lft, prefered_lft, true, jiffies); in6_ifa_put(ifp); addrconf_verify_rtnl(); return 0; } return PTR_ERR(ifp); } static int inet6_addr_del(struct net *net, int ifindex, u32 ifa_flags, const struct in6_addr *pfx, unsigned int plen) { struct inet6_ifaddr *ifp; struct inet6_dev *idev; struct net_device *dev; if (plen > 128) return -EINVAL; dev = __dev_get_by_index(net, ifindex); if (!dev) return -ENODEV; idev = __in6_dev_get(dev); if (idev == NULL) return -ENXIO; read_lock_bh(&idev->lock); list_for_each_entry(ifp, &idev->addr_list, if_list) { if (ifp->prefix_len == plen && ipv6_addr_equal(pfx, &ifp->addr)) { in6_ifa_hold(ifp); read_unlock_bh(&idev->lock); if (!(ifp->flags & IFA_F_TEMPORARY) && (ifa_flags & IFA_F_MANAGETEMPADDR)) manage_tempaddrs(idev, ifp, 0, 0, false, jiffies); ipv6_del_addr(ifp); addrconf_verify_rtnl(); return 0; } } read_unlock_bh(&idev->lock); return -EADDRNOTAVAIL; } int addrconf_add_ifaddr(struct net *net, void __user *arg) { struct in6_ifreq ireq; int err; if (!ns_capable(net->user_ns, CAP_NET_ADMIN)) return -EPERM; if (copy_from_user(&ireq, arg, sizeof(struct in6_ifreq))) return -EFAULT; rtnl_lock(); err = inet6_addr_add(net, ireq.ifr6_ifindex, &ireq.ifr6_addr, NULL, ireq.ifr6_prefixlen, IFA_F_PERMANENT, INFINITY_LIFE_TIME, INFINITY_LIFE_TIME); rtnl_unlock(); return err; } int addrconf_del_ifaddr(struct net *net, void __user *arg) { struct in6_ifreq ireq; int err; if (!ns_capable(net->user_ns, CAP_NET_ADMIN)) return -EPERM; if (copy_from_user(&ireq, arg, sizeof(struct in6_ifreq))) return -EFAULT; rtnl_lock(); err = inet6_addr_del(net, ireq.ifr6_ifindex, 0, &ireq.ifr6_addr, ireq.ifr6_prefixlen); rtnl_unlock(); return err; } static void add_addr(struct inet6_dev *idev, const struct in6_addr *addr, int plen, int scope) { struct inet6_ifaddr *ifp; ifp = ipv6_add_addr(idev, addr, NULL, plen, scope, IFA_F_PERMANENT, INFINITY_LIFE_TIME, INFINITY_LIFE_TIME); if (!IS_ERR(ifp)) { spin_lock_bh(&ifp->lock); ifp->flags &= ~IFA_F_TENTATIVE; spin_unlock_bh(&ifp->lock); ipv6_ifa_notify(RTM_NEWADDR, ifp); in6_ifa_put(ifp); } } #if IS_ENABLED(CONFIG_IPV6_SIT) static void sit_add_v4_addrs(struct inet6_dev *idev) { struct in6_addr addr; struct net_device *dev; struct net *net = dev_net(idev->dev); int scope, plen; u32 pflags = 0; ASSERT_RTNL(); memset(&addr, 0, sizeof(struct in6_addr)); memcpy(&addr.s6_addr32[3], idev->dev->dev_addr, 4); if (idev->dev->flags&IFF_POINTOPOINT) { addr.s6_addr32[0] = htonl(0xfe800000); scope = IFA_LINK; plen = 64; } else { scope = IPV6_ADDR_COMPATv4; plen = 96; pflags |= RTF_NONEXTHOP; } if (addr.s6_addr32[3]) { add_addr(idev, &addr, plen, scope); addrconf_prefix_route(&addr, plen, idev->dev, 0, pflags); return; } for_each_netdev(net, dev) { struct in_device *in_dev = __in_dev_get_rtnl(dev); if (in_dev && (dev->flags & IFF_UP)) { struct in_ifaddr *ifa; int flag = scope; for (ifa = in_dev->ifa_list; ifa; ifa = ifa->ifa_next) { addr.s6_addr32[3] = ifa->ifa_local; if (ifa->ifa_scope == RT_SCOPE_LINK) continue; if (ifa->ifa_scope >= RT_SCOPE_HOST) { if (idev->dev->flags&IFF_POINTOPOINT) continue; flag |= IFA_HOST; } add_addr(idev, &addr, plen, flag); addrconf_prefix_route(&addr, plen, idev->dev, 0, pflags); } } } } #endif static void init_loopback(struct net_device *dev) { struct inet6_dev *idev; struct net_device *sp_dev; struct inet6_ifaddr *sp_ifa; struct rt6_info *sp_rt; /* ::1 */ ASSERT_RTNL(); idev = ipv6_find_idev(dev); if (idev == NULL) { pr_debug("%s: add_dev failed\n", __func__); return; } add_addr(idev, &in6addr_loopback, 128, IFA_HOST); /* Add routes to other interface's IPv6 addresses */ for_each_netdev(dev_net(dev), sp_dev) { if (!strcmp(sp_dev->name, dev->name)) continue; idev = __in6_dev_get(sp_dev); if (!idev) continue; read_lock_bh(&idev->lock); list_for_each_entry(sp_ifa, &idev->addr_list, if_list) { if (sp_ifa->flags & (IFA_F_DADFAILED | IFA_F_TENTATIVE)) continue; if (sp_ifa->rt) { /* This dst has been added to garbage list when * lo device down, release this obsolete dst and * reallocate a new router for ifa. */ if (sp_ifa->rt->dst.obsolete > 0) { ip6_rt_put(sp_ifa->rt); sp_ifa->rt = NULL; } else { continue; } } sp_rt = addrconf_dst_alloc(idev, &sp_ifa->addr, false); /* Failure cases are ignored */ if (!IS_ERR(sp_rt)) { sp_ifa->rt = sp_rt; ip6_ins_rt(sp_rt); } } read_unlock_bh(&idev->lock); } } static void addrconf_add_linklocal(struct inet6_dev *idev, const struct in6_addr *addr) { struct inet6_ifaddr *ifp; u32 addr_flags = IFA_F_PERMANENT; #ifdef CONFIG_IPV6_OPTIMISTIC_DAD if (idev->cnf.optimistic_dad && !dev_net(idev->dev)->ipv6.devconf_all->forwarding) addr_flags |= IFA_F_OPTIMISTIC; #endif ifp = ipv6_add_addr(idev, addr, NULL, 64, IFA_LINK, addr_flags, INFINITY_LIFE_TIME, INFINITY_LIFE_TIME); if (!IS_ERR(ifp)) { addrconf_prefix_route(&ifp->addr, ifp->prefix_len, idev->dev, 0, 0); addrconf_dad_start(ifp); in6_ifa_put(ifp); } } static void addrconf_addr_gen(struct inet6_dev *idev, bool prefix_route) { if (idev->addr_gen_mode == IN6_ADDR_GEN_MODE_EUI64) { struct in6_addr addr; ipv6_addr_set(&addr, htonl(0xFE800000), 0, 0, 0); /* addrconf_add_linklocal also adds a prefix_route and we * only need to care about prefix routes if ipv6_generate_eui64 * couldn't generate one. */ if (ipv6_generate_eui64(addr.s6_addr + 8, idev->dev) == 0) addrconf_add_linklocal(idev, &addr); else if (prefix_route) addrconf_prefix_route(&addr, 64, idev->dev, 0, 0); } } static void addrconf_dev_config(struct net_device *dev) { struct inet6_dev *idev; ASSERT_RTNL(); if ((dev->type != ARPHRD_ETHER) && (dev->type != ARPHRD_FDDI) && (dev->type != ARPHRD_ARCNET) && (dev->type != ARPHRD_INFINIBAND) && (dev->type != ARPHRD_IEEE802154) && (dev->type != ARPHRD_IEEE1394) && (dev->type != ARPHRD_TUNNEL6) && (dev->type != ARPHRD_6LOWPAN)) { /* Alas, we support only Ethernet autoconfiguration. */ return; } idev = addrconf_add_dev(dev); if (IS_ERR(idev)) return; addrconf_addr_gen(idev, false); } #if IS_ENABLED(CONFIG_IPV6_SIT) static void addrconf_sit_config(struct net_device *dev) { struct inet6_dev *idev; ASSERT_RTNL(); /* * Configure the tunnel with one of our IPv4 * addresses... we should configure all of * our v4 addrs in the tunnel */ idev = ipv6_find_idev(dev); if (idev == NULL) { pr_debug("%s: add_dev failed\n", __func__); return; } if (dev->priv_flags & IFF_ISATAP) { addrconf_addr_gen(idev, false); return; } sit_add_v4_addrs(idev); if (dev->flags&IFF_POINTOPOINT) addrconf_add_mroute(dev); } #endif #if IS_ENABLED(CONFIG_NET_IPGRE) static void addrconf_gre_config(struct net_device *dev) { struct inet6_dev *idev; ASSERT_RTNL(); idev = ipv6_find_idev(dev); if (idev == NULL) { pr_debug("%s: add_dev failed\n", __func__); return; } addrconf_addr_gen(idev, true); } #endif static int addrconf_notify(struct notifier_block *this, unsigned long event, void *ptr) { struct net_device *dev = netdev_notifier_info_to_dev(ptr); struct inet6_dev *idev = __in6_dev_get(dev); int run_pending = 0; int err; switch (event) { case NETDEV_REGISTER: if (!idev && dev->mtu >= IPV6_MIN_MTU) { idev = ipv6_add_dev(dev); if (IS_ERR(idev)) return notifier_from_errno(PTR_ERR(idev)); } break; case NETDEV_UP: case NETDEV_CHANGE: if (dev->flags & IFF_SLAVE) break; if (idev && idev->cnf.disable_ipv6) break; if (event == NETDEV_UP) { if (!addrconf_qdisc_ok(dev)) { /* device is not ready yet. */ pr_info("ADDRCONF(NETDEV_UP): %s: link is not ready\n", dev->name); break; } if (!idev && dev->mtu >= IPV6_MIN_MTU) idev = ipv6_add_dev(dev); if (!IS_ERR_OR_NULL(idev)) { idev->if_flags |= IF_READY; run_pending = 1; } } else { if (!addrconf_qdisc_ok(dev)) { /* device is still not ready. */ break; } if (idev) { if (idev->if_flags & IF_READY) /* device is already configured. */ break; idev->if_flags |= IF_READY; } pr_info("ADDRCONF(NETDEV_CHANGE): %s: link becomes ready\n", dev->name); run_pending = 1; } switch (dev->type) { #if IS_ENABLED(CONFIG_IPV6_SIT) case ARPHRD_SIT: addrconf_sit_config(dev); break; #endif #if IS_ENABLED(CONFIG_NET_IPGRE) case ARPHRD_IPGRE: addrconf_gre_config(dev); break; #endif case ARPHRD_LOOPBACK: init_loopback(dev); break; default: addrconf_dev_config(dev); break; } if (!IS_ERR_OR_NULL(idev)) { if (run_pending) addrconf_dad_run(idev); /* * If the MTU changed during the interface down, * when the interface up, the changed MTU must be * reflected in the idev as well as routers. */ if (idev->cnf.mtu6 != dev->mtu && dev->mtu >= IPV6_MIN_MTU) { rt6_mtu_change(dev, dev->mtu); idev->cnf.mtu6 = dev->mtu; } idev->tstamp = jiffies; inet6_ifinfo_notify(RTM_NEWLINK, idev); /* * If the changed mtu during down is lower than * IPV6_MIN_MTU stop IPv6 on this interface. */ if (dev->mtu < IPV6_MIN_MTU) addrconf_ifdown(dev, 1); } break; case NETDEV_CHANGEMTU: if (idev && dev->mtu >= IPV6_MIN_MTU) { rt6_mtu_change(dev, dev->mtu); idev->cnf.mtu6 = dev->mtu; break; } if (!idev && dev->mtu >= IPV6_MIN_MTU) { idev = ipv6_add_dev(dev); if (!IS_ERR(idev)) break; } /* * if MTU under IPV6_MIN_MTU. * Stop IPv6 on this interface. */ case NETDEV_DOWN: case NETDEV_UNREGISTER: /* * Remove all addresses from this interface. */ addrconf_ifdown(dev, event != NETDEV_DOWN); break; case NETDEV_CHANGENAME: if (idev) { snmp6_unregister_dev(idev); addrconf_sysctl_unregister(idev); err = addrconf_sysctl_register(idev); if (err) return notifier_from_errno(err); err = snmp6_register_dev(idev); if (err) { addrconf_sysctl_unregister(idev); return notifier_from_errno(err); } } break; case NETDEV_PRE_TYPE_CHANGE: case NETDEV_POST_TYPE_CHANGE: addrconf_type_change(dev, event); break; } return NOTIFY_OK; } /* * addrconf module should be notified of a device going up */ static struct notifier_block ipv6_dev_notf = { .notifier_call = addrconf_notify, }; static void addrconf_type_change(struct net_device *dev, unsigned long event) { struct inet6_dev *idev; ASSERT_RTNL(); idev = __in6_dev_get(dev); if (event == NETDEV_POST_TYPE_CHANGE) ipv6_mc_remap(idev); else if (event == NETDEV_PRE_TYPE_CHANGE) ipv6_mc_unmap(idev); } static int addrconf_ifdown(struct net_device *dev, int how) { struct net *net = dev_net(dev); struct inet6_dev *idev; struct inet6_ifaddr *ifa; int state, i; ASSERT_RTNL(); rt6_ifdown(net, dev); neigh_ifdown(&nd_tbl, dev); idev = __in6_dev_get(dev); if (idev == NULL) return -ENODEV; /* * Step 1: remove reference to ipv6 device from parent device. * Do not dev_put! */ if (how) { idev->dead = 1; /* protected by rtnl_lock */ RCU_INIT_POINTER(dev->ip6_ptr, NULL); /* Step 1.5: remove snmp6 entry */ snmp6_unregister_dev(idev); } /* Step 2: clear hash table */ for (i = 0; i < IN6_ADDR_HSIZE; i++) { struct hlist_head *h = &inet6_addr_lst[i]; spin_lock_bh(&addrconf_hash_lock); restart: hlist_for_each_entry_rcu(ifa, h, addr_lst) { if (ifa->idev == idev) { hlist_del_init_rcu(&ifa->addr_lst); addrconf_del_dad_work(ifa); goto restart; } } spin_unlock_bh(&addrconf_hash_lock); } write_lock_bh(&idev->lock); addrconf_del_rs_timer(idev); /* Step 2: clear flags for stateless addrconf */ if (!how) idev->if_flags &= ~(IF_RS_SENT|IF_RA_RCVD|IF_READY); if (how && del_timer(&idev->regen_timer)) in6_dev_put(idev); /* Step 3: clear tempaddr list */ while (!list_empty(&idev->tempaddr_list)) { ifa = list_first_entry(&idev->tempaddr_list, struct inet6_ifaddr, tmp_list); list_del(&ifa->tmp_list); write_unlock_bh(&idev->lock); spin_lock_bh(&ifa->lock); if (ifa->ifpub) { in6_ifa_put(ifa->ifpub); ifa->ifpub = NULL; } spin_unlock_bh(&ifa->lock); in6_ifa_put(ifa); write_lock_bh(&idev->lock); } while (!list_empty(&idev->addr_list)) { ifa = list_first_entry(&idev->addr_list, struct inet6_ifaddr, if_list); addrconf_del_dad_work(ifa); list_del(&ifa->if_list); write_unlock_bh(&idev->lock); spin_lock_bh(&ifa->state_lock); state = ifa->state; ifa->state = INET6_IFADDR_STATE_DEAD; spin_unlock_bh(&ifa->state_lock); if (state != INET6_IFADDR_STATE_DEAD) { __ipv6_ifa_notify(RTM_DELADDR, ifa); inet6addr_notifier_call_chain(NETDEV_DOWN, ifa); } in6_ifa_put(ifa); write_lock_bh(&idev->lock); } write_unlock_bh(&idev->lock); /* Step 5: Discard anycast and multicast list */ if (how) { ipv6_ac_destroy_dev(idev); ipv6_mc_destroy_dev(idev); } else { ipv6_mc_down(idev); } idev->tstamp = jiffies; /* Last: Shot the device (if unregistered) */ if (how) { addrconf_sysctl_unregister(idev); neigh_parms_release(&nd_tbl, idev->nd_parms); neigh_ifdown(&nd_tbl, dev); in6_dev_put(idev); } return 0; } static void addrconf_rs_timer(unsigned long data) { struct inet6_dev *idev = (struct inet6_dev *)data; struct net_device *dev = idev->dev; struct in6_addr lladdr; write_lock(&idev->lock); if (idev->dead || !(idev->if_flags & IF_READY)) goto out; if (!ipv6_accept_ra(idev)) goto out; /* Announcement received after solicitation was sent */ if (idev->if_flags & IF_RA_RCVD) goto out; if (idev->rs_probes++ < idev->cnf.rtr_solicits) { write_unlock(&idev->lock); if (!ipv6_get_lladdr(dev, &lladdr, IFA_F_TENTATIVE)) ndisc_send_rs(dev, &lladdr, &in6addr_linklocal_allrouters); else goto put; write_lock(&idev->lock); /* The wait after the last probe can be shorter */ addrconf_mod_rs_timer(idev, (idev->rs_probes == idev->cnf.rtr_solicits) ? idev->cnf.rtr_solicit_delay : idev->cnf.rtr_solicit_interval); } else { /* * Note: we do not support deprecated "all on-link" * assumption any longer. */ pr_debug("%s: no IPv6 routers present\n", idev->dev->name); } out: write_unlock(&idev->lock); put: in6_dev_put(idev); } /* * Duplicate Address Detection */ static void addrconf_dad_kick(struct inet6_ifaddr *ifp) { unsigned long rand_num; struct inet6_dev *idev = ifp->idev; if (ifp->flags & IFA_F_OPTIMISTIC) rand_num = 0; else rand_num = prandom_u32() % (idev->cnf.rtr_solicit_delay ? : 1); ifp->dad_probes = idev->cnf.dad_transmits; addrconf_mod_dad_work(ifp, rand_num); } static void addrconf_dad_begin(struct inet6_ifaddr *ifp) { struct inet6_dev *idev = ifp->idev; struct net_device *dev = idev->dev; addrconf_join_solict(dev, &ifp->addr); prandom_seed((__force u32) ifp->addr.s6_addr32[3]); read_lock_bh(&idev->lock); spin_lock(&ifp->lock); if (ifp->state == INET6_IFADDR_STATE_DEAD) goto out; if (dev->flags&(IFF_NOARP|IFF_LOOPBACK) || idev->cnf.accept_dad < 1 || !(ifp->flags&IFA_F_TENTATIVE) || ifp->flags & IFA_F_NODAD) { ifp->flags &= ~(IFA_F_TENTATIVE|IFA_F_OPTIMISTIC|IFA_F_DADFAILED); spin_unlock(&ifp->lock); read_unlock_bh(&idev->lock); addrconf_dad_completed(ifp); return; } if (!(idev->if_flags & IF_READY)) { spin_unlock(&ifp->lock); read_unlock_bh(&idev->lock); /* * If the device is not ready: * - keep it tentative if it is a permanent address. * - otherwise, kill it. */ in6_ifa_hold(ifp); addrconf_dad_stop(ifp, 0); return; } /* * Optimistic nodes can start receiving * Frames right away */ if (ifp->flags & IFA_F_OPTIMISTIC) { ip6_ins_rt(ifp->rt); if (ipv6_use_optimistic_addr(idev)) { /* Because optimistic nodes can use this address, * notify listeners. If DAD fails, RTM_DELADDR is sent. */ ipv6_ifa_notify(RTM_NEWADDR, ifp); } } addrconf_dad_kick(ifp); out: spin_unlock(&ifp->lock); read_unlock_bh(&idev->lock); } static void addrconf_dad_start(struct inet6_ifaddr *ifp) { bool begin_dad = false; spin_lock_bh(&ifp->state_lock); if (ifp->state != INET6_IFADDR_STATE_DEAD) { ifp->state = INET6_IFADDR_STATE_PREDAD; begin_dad = true; } spin_unlock_bh(&ifp->state_lock); if (begin_dad) addrconf_mod_dad_work(ifp, 0); } static void addrconf_dad_work(struct work_struct *w) { struct inet6_ifaddr *ifp = container_of(to_delayed_work(w), struct inet6_ifaddr, dad_work); struct inet6_dev *idev = ifp->idev; struct in6_addr mcaddr; enum { DAD_PROCESS, DAD_BEGIN, DAD_ABORT, } action = DAD_PROCESS; rtnl_lock(); spin_lock_bh(&ifp->state_lock); if (ifp->state == INET6_IFADDR_STATE_PREDAD) { action = DAD_BEGIN; ifp->state = INET6_IFADDR_STATE_DAD; } else if (ifp->state == INET6_IFADDR_STATE_ERRDAD) { action = DAD_ABORT; ifp->state = INET6_IFADDR_STATE_POSTDAD; } spin_unlock_bh(&ifp->state_lock); if (action == DAD_BEGIN) { addrconf_dad_begin(ifp); goto out; } else if (action == DAD_ABORT) { addrconf_dad_stop(ifp, 1); goto out; } if (!ifp->dad_probes && addrconf_dad_end(ifp)) goto out; write_lock_bh(&idev->lock); if (idev->dead || !(idev->if_flags & IF_READY)) { write_unlock_bh(&idev->lock); goto out; } spin_lock(&ifp->lock); if (ifp->state == INET6_IFADDR_STATE_DEAD) { spin_unlock(&ifp->lock); write_unlock_bh(&idev->lock); goto out; } if (ifp->dad_probes == 0) { /* * DAD was successful */ ifp->flags &= ~(IFA_F_TENTATIVE|IFA_F_OPTIMISTIC|IFA_F_DADFAILED); spin_unlock(&ifp->lock); write_unlock_bh(&idev->lock); addrconf_dad_completed(ifp); goto out; } ifp->dad_probes--; addrconf_mod_dad_work(ifp, NEIGH_VAR(ifp->idev->nd_parms, RETRANS_TIME)); spin_unlock(&ifp->lock); write_unlock_bh(&idev->lock); /* send a neighbour solicitation for our addr */ addrconf_addr_solict_mult(&ifp->addr, &mcaddr); ndisc_send_ns(ifp->idev->dev, NULL, &ifp->addr, &mcaddr, &in6addr_any); out: in6_ifa_put(ifp); rtnl_unlock(); } /* ifp->idev must be at least read locked */ static bool ipv6_lonely_lladdr(struct inet6_ifaddr *ifp) { struct inet6_ifaddr *ifpiter; struct inet6_dev *idev = ifp->idev; list_for_each_entry_reverse(ifpiter, &idev->addr_list, if_list) { if (ifpiter->scope > IFA_LINK) break; if (ifp != ifpiter && ifpiter->scope == IFA_LINK && (ifpiter->flags & (IFA_F_PERMANENT|IFA_F_TENTATIVE| IFA_F_OPTIMISTIC|IFA_F_DADFAILED)) == IFA_F_PERMANENT) return false; } return true; } static void addrconf_dad_completed(struct inet6_ifaddr *ifp) { struct net_device *dev = ifp->idev->dev; struct in6_addr lladdr; bool send_rs, send_mld; addrconf_del_dad_work(ifp); /* * Configure the address for reception. Now it is valid. */ ipv6_ifa_notify(RTM_NEWADDR, ifp); /* If added prefix is link local and we are prepared to process router advertisements, start sending router solicitations. */ read_lock_bh(&ifp->idev->lock); send_mld = ifp->scope == IFA_LINK && ipv6_lonely_lladdr(ifp); send_rs = send_mld && ipv6_accept_ra(ifp->idev) && ifp->idev->cnf.rtr_solicits > 0 && (dev->flags&IFF_LOOPBACK) == 0; read_unlock_bh(&ifp->idev->lock); /* While dad is in progress mld report's source address is in6_addrany. * Resend with proper ll now. */ if (send_mld) ipv6_mc_dad_complete(ifp->idev); if (send_rs) { /* * If a host as already performed a random delay * [...] as part of DAD [...] there is no need * to delay again before sending the first RS */ if (ipv6_get_lladdr(dev, &lladdr, IFA_F_TENTATIVE)) return; ndisc_send_rs(dev, &lladdr, &in6addr_linklocal_allrouters); write_lock_bh(&ifp->idev->lock); spin_lock(&ifp->lock); ifp->idev->rs_probes = 1; ifp->idev->if_flags |= IF_RS_SENT; addrconf_mod_rs_timer(ifp->idev, ifp->idev->cnf.rtr_solicit_interval); spin_unlock(&ifp->lock); write_unlock_bh(&ifp->idev->lock); } } static void addrconf_dad_run(struct inet6_dev *idev) { struct inet6_ifaddr *ifp; read_lock_bh(&idev->lock); list_for_each_entry(ifp, &idev->addr_list, if_list) { spin_lock(&ifp->lock); if (ifp->flags & IFA_F_TENTATIVE && ifp->state == INET6_IFADDR_STATE_DAD) addrconf_dad_kick(ifp); spin_unlock(&ifp->lock); } read_unlock_bh(&idev->lock); } #ifdef CONFIG_PROC_FS struct if6_iter_state { struct seq_net_private p; int bucket; int offset; }; static struct inet6_ifaddr *if6_get_first(struct seq_file *seq, loff_t pos) { struct inet6_ifaddr *ifa = NULL; struct if6_iter_state *state = seq->private; struct net *net = seq_file_net(seq); int p = 0; /* initial bucket if pos is 0 */ if (pos == 0) { state->bucket = 0; state->offset = 0; } for (; state->bucket < IN6_ADDR_HSIZE; ++state->bucket) { hlist_for_each_entry_rcu_bh(ifa, &inet6_addr_lst[state->bucket], addr_lst) { if (!net_eq(dev_net(ifa->idev->dev), net)) continue; /* sync with offset */ if (p < state->offset) { p++; continue; } state->offset++; return ifa; } /* prepare for next bucket */ state->offset = 0; p = 0; } return NULL; } static struct inet6_ifaddr *if6_get_next(struct seq_file *seq, struct inet6_ifaddr *ifa) { struct if6_iter_state *state = seq->private; struct net *net = seq_file_net(seq); hlist_for_each_entry_continue_rcu_bh(ifa, addr_lst) { if (!net_eq(dev_net(ifa->idev->dev), net)) continue; state->offset++; return ifa; } while (++state->bucket < IN6_ADDR_HSIZE) { state->offset = 0; hlist_for_each_entry_rcu_bh(ifa, &inet6_addr_lst[state->bucket], addr_lst) { if (!net_eq(dev_net(ifa->idev->dev), net)) continue; state->offset++; return ifa; } } return NULL; } static void *if6_seq_start(struct seq_file *seq, loff_t *pos) __acquires(rcu_bh) { rcu_read_lock_bh(); return if6_get_first(seq, *pos); } static void *if6_seq_next(struct seq_file *seq, void *v, loff_t *pos) { struct inet6_ifaddr *ifa; ifa = if6_get_next(seq, v); ++*pos; return ifa; } static void if6_seq_stop(struct seq_file *seq, void *v) __releases(rcu_bh) { rcu_read_unlock_bh(); } static int if6_seq_show(struct seq_file *seq, void *v) { struct inet6_ifaddr *ifp = (struct inet6_ifaddr *)v; seq_printf(seq, "%pi6 %02x %02x %02x %02x %8s\n", &ifp->addr, ifp->idev->dev->ifindex, ifp->prefix_len, ifp->scope, (u8) ifp->flags, ifp->idev->dev->name); return 0; } static const struct seq_operations if6_seq_ops = { .start = if6_seq_start, .next = if6_seq_next, .show = if6_seq_show, .stop = if6_seq_stop, }; static int if6_seq_open(struct inode *inode, struct file *file) { return seq_open_net(inode, file, &if6_seq_ops, sizeof(struct if6_iter_state)); } static const struct file_operations if6_fops = { .owner = THIS_MODULE, .open = if6_seq_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release_net, }; static int __net_init if6_proc_net_init(struct net *net) { if (!proc_create("if_inet6", S_IRUGO, net->proc_net, &if6_fops)) return -ENOMEM; return 0; } static void __net_exit if6_proc_net_exit(struct net *net) { remove_proc_entry("if_inet6", net->proc_net); } static struct pernet_operations if6_proc_net_ops = { .init = if6_proc_net_init, .exit = if6_proc_net_exit, }; int __init if6_proc_init(void) { return register_pernet_subsys(&if6_proc_net_ops); } void if6_proc_exit(void) { unregister_pernet_subsys(&if6_proc_net_ops); } #endif /* CONFIG_PROC_FS */ #if IS_ENABLED(CONFIG_IPV6_MIP6) /* Check if address is a home address configured on any interface. */ int ipv6_chk_home_addr(struct net *net, const struct in6_addr *addr) { int ret = 0; struct inet6_ifaddr *ifp = NULL; unsigned int hash = inet6_addr_hash(addr); rcu_read_lock_bh(); hlist_for_each_entry_rcu_bh(ifp, &inet6_addr_lst[hash], addr_lst) { if (!net_eq(dev_net(ifp->idev->dev), net)) continue; if (ipv6_addr_equal(&ifp->addr, addr) && (ifp->flags & IFA_F_HOMEADDRESS)) { ret = 1; break; } } rcu_read_unlock_bh(); return ret; } #endif /* * Periodic address status verification */ static void addrconf_verify_rtnl(void) { unsigned long now, next, next_sec, next_sched; struct inet6_ifaddr *ifp; int i; ASSERT_RTNL(); rcu_read_lock_bh(); now = jiffies; next = round_jiffies_up(now + ADDR_CHECK_FREQUENCY); cancel_delayed_work(&addr_chk_work); for (i = 0; i < IN6_ADDR_HSIZE; i++) { restart: hlist_for_each_entry_rcu_bh(ifp, &inet6_addr_lst[i], addr_lst) { unsigned long age; /* When setting preferred_lft to a value not zero or * infinity, while valid_lft is infinity * IFA_F_PERMANENT has a non-infinity life time. */ if ((ifp->flags & IFA_F_PERMANENT) && (ifp->prefered_lft == INFINITY_LIFE_TIME)) continue; spin_lock(&ifp->lock); /* We try to batch several events at once. */ age = (now - ifp->tstamp + ADDRCONF_TIMER_FUZZ_MINUS) / HZ; if (ifp->valid_lft != INFINITY_LIFE_TIME && age >= ifp->valid_lft) { spin_unlock(&ifp->lock); in6_ifa_hold(ifp); ipv6_del_addr(ifp); goto restart; } else if (ifp->prefered_lft == INFINITY_LIFE_TIME) { spin_unlock(&ifp->lock); continue; } else if (age >= ifp->prefered_lft) { /* jiffies - ifp->tstamp > age >= ifp->prefered_lft */ int deprecate = 0; if (!(ifp->flags&IFA_F_DEPRECATED)) { deprecate = 1; ifp->flags |= IFA_F_DEPRECATED; } if ((ifp->valid_lft != INFINITY_LIFE_TIME) && (time_before(ifp->tstamp + ifp->valid_lft * HZ, next))) next = ifp->tstamp + ifp->valid_lft * HZ; spin_unlock(&ifp->lock); if (deprecate) { in6_ifa_hold(ifp); ipv6_ifa_notify(0, ifp); in6_ifa_put(ifp); goto restart; } } else if ((ifp->flags&IFA_F_TEMPORARY) && !(ifp->flags&IFA_F_TENTATIVE)) { unsigned long regen_advance = ifp->idev->cnf.regen_max_retry * ifp->idev->cnf.dad_transmits * NEIGH_VAR(ifp->idev->nd_parms, RETRANS_TIME) / HZ; if (age >= ifp->prefered_lft - regen_advance) { struct inet6_ifaddr *ifpub = ifp->ifpub; if (time_before(ifp->tstamp + ifp->prefered_lft * HZ, next)) next = ifp->tstamp + ifp->prefered_lft * HZ; if (!ifp->regen_count && ifpub) { ifp->regen_count++; in6_ifa_hold(ifp); in6_ifa_hold(ifpub); spin_unlock(&ifp->lock); spin_lock(&ifpub->lock); ifpub->regen_count = 0; spin_unlock(&ifpub->lock); ipv6_create_tempaddr(ifpub, ifp); in6_ifa_put(ifpub); in6_ifa_put(ifp); goto restart; } } else if (time_before(ifp->tstamp + ifp->prefered_lft * HZ - regen_advance * HZ, next)) next = ifp->tstamp + ifp->prefered_lft * HZ - regen_advance * HZ; spin_unlock(&ifp->lock); } else { /* ifp->prefered_lft <= ifp->valid_lft */ if (time_before(ifp->tstamp + ifp->prefered_lft * HZ, next)) next = ifp->tstamp + ifp->prefered_lft * HZ; spin_unlock(&ifp->lock); } } } next_sec = round_jiffies_up(next); next_sched = next; /* If rounded timeout is accurate enough, accept it. */ if (time_before(next_sec, next + ADDRCONF_TIMER_FUZZ)) next_sched = next_sec; /* And minimum interval is ADDRCONF_TIMER_FUZZ_MAX. */ if (time_before(next_sched, jiffies + ADDRCONF_TIMER_FUZZ_MAX)) next_sched = jiffies + ADDRCONF_TIMER_FUZZ_MAX; ADBG(KERN_DEBUG "now = %lu, schedule = %lu, rounded schedule = %lu => %lu\n", now, next, next_sec, next_sched); mod_delayed_work(addrconf_wq, &addr_chk_work, next_sched - now); rcu_read_unlock_bh(); } static void addrconf_verify_work(struct work_struct *w) { rtnl_lock(); addrconf_verify_rtnl(); rtnl_unlock(); } static void addrconf_verify(void) { mod_delayed_work(addrconf_wq, &addr_chk_work, 0); } static struct in6_addr *extract_addr(struct nlattr *addr, struct nlattr *local, struct in6_addr **peer_pfx) { struct in6_addr *pfx = NULL; *peer_pfx = NULL; if (addr) pfx = nla_data(addr); if (local) { if (pfx && nla_memcmp(local, pfx, sizeof(*pfx))) *peer_pfx = pfx; pfx = nla_data(local); } return pfx; } static const struct nla_policy ifa_ipv6_policy[IFA_MAX+1] = { [IFA_ADDRESS] = { .len = sizeof(struct in6_addr) }, [IFA_LOCAL] = { .len = sizeof(struct in6_addr) }, [IFA_CACHEINFO] = { .len = sizeof(struct ifa_cacheinfo) }, [IFA_FLAGS] = { .len = sizeof(u32) }, }; static int inet6_rtm_deladdr(struct sk_buff *skb, struct nlmsghdr *nlh) { struct net *net = sock_net(skb->sk); struct ifaddrmsg *ifm; struct nlattr *tb[IFA_MAX+1]; struct in6_addr *pfx, *peer_pfx; u32 ifa_flags; int err; err = nlmsg_parse(nlh, sizeof(*ifm), tb, IFA_MAX, ifa_ipv6_policy); if (err < 0) return err; ifm = nlmsg_data(nlh); pfx = extract_addr(tb[IFA_ADDRESS], tb[IFA_LOCAL], &peer_pfx); if (pfx == NULL) return -EINVAL; ifa_flags = tb[IFA_FLAGS] ? nla_get_u32(tb[IFA_FLAGS]) : ifm->ifa_flags; /* We ignore other flags so far. */ ifa_flags &= IFA_F_MANAGETEMPADDR; return inet6_addr_del(net, ifm->ifa_index, ifa_flags, pfx, ifm->ifa_prefixlen); } static int inet6_addr_modify(struct inet6_ifaddr *ifp, u32 ifa_flags, u32 prefered_lft, u32 valid_lft) { u32 flags; clock_t expires; unsigned long timeout; bool was_managetempaddr; bool had_prefixroute; ASSERT_RTNL(); if (!valid_lft || (prefered_lft > valid_lft)) return -EINVAL; if (ifa_flags & IFA_F_MANAGETEMPADDR && (ifp->flags & IFA_F_TEMPORARY || ifp->prefix_len != 64)) return -EINVAL; timeout = addrconf_timeout_fixup(valid_lft, HZ); if (addrconf_finite_timeout(timeout)) { expires = jiffies_to_clock_t(timeout * HZ); valid_lft = timeout; flags = RTF_EXPIRES; } else { expires = 0; flags = 0; ifa_flags |= IFA_F_PERMANENT; } timeout = addrconf_timeout_fixup(prefered_lft, HZ); if (addrconf_finite_timeout(timeout)) { if (timeout == 0) ifa_flags |= IFA_F_DEPRECATED; prefered_lft = timeout; } spin_lock_bh(&ifp->lock); was_managetempaddr = ifp->flags & IFA_F_MANAGETEMPADDR; had_prefixroute = ifp->flags & IFA_F_PERMANENT && !(ifp->flags & IFA_F_NOPREFIXROUTE); ifp->flags &= ~(IFA_F_DEPRECATED | IFA_F_PERMANENT | IFA_F_NODAD | IFA_F_HOMEADDRESS | IFA_F_MANAGETEMPADDR | IFA_F_NOPREFIXROUTE); ifp->flags |= ifa_flags; ifp->tstamp = jiffies; ifp->valid_lft = valid_lft; ifp->prefered_lft = prefered_lft; spin_unlock_bh(&ifp->lock); if (!(ifp->flags&IFA_F_TENTATIVE)) ipv6_ifa_notify(0, ifp); if (!(ifa_flags & IFA_F_NOPREFIXROUTE)) { addrconf_prefix_route(&ifp->addr, ifp->prefix_len, ifp->idev->dev, expires, flags); } else if (had_prefixroute) { enum cleanup_prefix_rt_t action; unsigned long rt_expires; write_lock_bh(&ifp->idev->lock); action = check_cleanup_prefix_route(ifp, &rt_expires); write_unlock_bh(&ifp->idev->lock); if (action != CLEANUP_PREFIX_RT_NOP) { cleanup_prefix_route(ifp, rt_expires, action == CLEANUP_PREFIX_RT_DEL); } } if (was_managetempaddr || ifp->flags & IFA_F_MANAGETEMPADDR) { if (was_managetempaddr && !(ifp->flags & IFA_F_MANAGETEMPADDR)) valid_lft = prefered_lft = 0; manage_tempaddrs(ifp->idev, ifp, valid_lft, prefered_lft, !was_managetempaddr, jiffies); } addrconf_verify_rtnl(); return 0; } static int inet6_rtm_newaddr(struct sk_buff *skb, struct nlmsghdr *nlh) { struct net *net = sock_net(skb->sk); struct ifaddrmsg *ifm; struct nlattr *tb[IFA_MAX+1]; struct in6_addr *pfx, *peer_pfx; struct inet6_ifaddr *ifa; struct net_device *dev; u32 valid_lft = INFINITY_LIFE_TIME, preferred_lft = INFINITY_LIFE_TIME; u32 ifa_flags; int err; err = nlmsg_parse(nlh, sizeof(*ifm), tb, IFA_MAX, ifa_ipv6_policy); if (err < 0) return err; ifm = nlmsg_data(nlh); pfx = extract_addr(tb[IFA_ADDRESS], tb[IFA_LOCAL], &peer_pfx); if (pfx == NULL) return -EINVAL; if (tb[IFA_CACHEINFO]) { struct ifa_cacheinfo *ci; ci = nla_data(tb[IFA_CACHEINFO]); valid_lft = ci->ifa_valid; preferred_lft = ci->ifa_prefered; } else { preferred_lft = INFINITY_LIFE_TIME; valid_lft = INFINITY_LIFE_TIME; } dev = __dev_get_by_index(net, ifm->ifa_index); if (dev == NULL) return -ENODEV; ifa_flags = tb[IFA_FLAGS] ? nla_get_u32(tb[IFA_FLAGS]) : ifm->ifa_flags; /* We ignore other flags so far. */ ifa_flags &= IFA_F_NODAD | IFA_F_HOMEADDRESS | IFA_F_MANAGETEMPADDR | IFA_F_NOPREFIXROUTE; ifa = ipv6_get_ifaddr(net, pfx, dev, 1); if (ifa == NULL) { /* * It would be best to check for !NLM_F_CREATE here but * userspace already relies on not having to provide this. */ return inet6_addr_add(net, ifm->ifa_index, pfx, peer_pfx, ifm->ifa_prefixlen, ifa_flags, preferred_lft, valid_lft); } if (nlh->nlmsg_flags & NLM_F_EXCL || !(nlh->nlmsg_flags & NLM_F_REPLACE)) err = -EEXIST; else err = inet6_addr_modify(ifa, ifa_flags, preferred_lft, valid_lft); in6_ifa_put(ifa); return err; } static void put_ifaddrmsg(struct nlmsghdr *nlh, u8 prefixlen, u32 flags, u8 scope, int ifindex) { struct ifaddrmsg *ifm; ifm = nlmsg_data(nlh); ifm->ifa_family = AF_INET6; ifm->ifa_prefixlen = prefixlen; ifm->ifa_flags = flags; ifm->ifa_scope = scope; ifm->ifa_index = ifindex; } static int put_cacheinfo(struct sk_buff *skb, unsigned long cstamp, unsigned long tstamp, u32 preferred, u32 valid) { struct ifa_cacheinfo ci; ci.cstamp = cstamp_delta(cstamp); ci.tstamp = cstamp_delta(tstamp); ci.ifa_prefered = preferred; ci.ifa_valid = valid; return nla_put(skb, IFA_CACHEINFO, sizeof(ci), &ci); } static inline int rt_scope(int ifa_scope) { if (ifa_scope & IFA_HOST) return RT_SCOPE_HOST; else if (ifa_scope & IFA_LINK) return RT_SCOPE_LINK; else if (ifa_scope & IFA_SITE) return RT_SCOPE_SITE; else return RT_SCOPE_UNIVERSE; } static inline int inet6_ifaddr_msgsize(void) { return NLMSG_ALIGN(sizeof(struct ifaddrmsg)) + nla_total_size(16) /* IFA_LOCAL */ + nla_total_size(16) /* IFA_ADDRESS */ + nla_total_size(sizeof(struct ifa_cacheinfo)) + nla_total_size(4) /* IFA_FLAGS */; } static int inet6_fill_ifaddr(struct sk_buff *skb, struct inet6_ifaddr *ifa, u32 portid, u32 seq, int event, unsigned int flags) { struct nlmsghdr *nlh; u32 preferred, valid; nlh = nlmsg_put(skb, portid, seq, event, sizeof(struct ifaddrmsg), flags); if (nlh == NULL) return -EMSGSIZE; put_ifaddrmsg(nlh, ifa->prefix_len, ifa->flags, rt_scope(ifa->scope), ifa->idev->dev->ifindex); if (!((ifa->flags&IFA_F_PERMANENT) && (ifa->prefered_lft == INFINITY_LIFE_TIME))) { preferred = ifa->prefered_lft; valid = ifa->valid_lft; if (preferred != INFINITY_LIFE_TIME) { long tval = (jiffies - ifa->tstamp)/HZ; if (preferred > tval) preferred -= tval; else preferred = 0; if (valid != INFINITY_LIFE_TIME) { if (valid > tval) valid -= tval; else valid = 0; } } } else { preferred = INFINITY_LIFE_TIME; valid = INFINITY_LIFE_TIME; } if (!ipv6_addr_any(&ifa->peer_addr)) { if (nla_put(skb, IFA_LOCAL, 16, &ifa->addr) < 0 || nla_put(skb, IFA_ADDRESS, 16, &ifa->peer_addr) < 0) goto error; } else if (nla_put(skb, IFA_ADDRESS, 16, &ifa->addr) < 0) goto error; if (put_cacheinfo(skb, ifa->cstamp, ifa->tstamp, preferred, valid) < 0) goto error; if (nla_put_u32(skb, IFA_FLAGS, ifa->flags) < 0) goto error; nlmsg_end(skb, nlh); return 0; error: nlmsg_cancel(skb, nlh); return -EMSGSIZE; } static int inet6_fill_ifmcaddr(struct sk_buff *skb, struct ifmcaddr6 *ifmca, u32 portid, u32 seq, int event, u16 flags) { struct nlmsghdr *nlh; u8 scope = RT_SCOPE_UNIVERSE; int ifindex = ifmca->idev->dev->ifindex; if (ipv6_addr_scope(&ifmca->mca_addr) & IFA_SITE) scope = RT_SCOPE_SITE; nlh = nlmsg_put(skb, portid, seq, event, sizeof(struct ifaddrmsg), flags); if (nlh == NULL) return -EMSGSIZE; put_ifaddrmsg(nlh, 128, IFA_F_PERMANENT, scope, ifindex); if (nla_put(skb, IFA_MULTICAST, 16, &ifmca->mca_addr) < 0 || put_cacheinfo(skb, ifmca->mca_cstamp, ifmca->mca_tstamp, INFINITY_LIFE_TIME, INFINITY_LIFE_TIME) < 0) { nlmsg_cancel(skb, nlh); return -EMSGSIZE; } nlmsg_end(skb, nlh); return 0; } static int inet6_fill_ifacaddr(struct sk_buff *skb, struct ifacaddr6 *ifaca, u32 portid, u32 seq, int event, unsigned int flags) { struct nlmsghdr *nlh; u8 scope = RT_SCOPE_UNIVERSE; int ifindex = ifaca->aca_idev->dev->ifindex; if (ipv6_addr_scope(&ifaca->aca_addr) & IFA_SITE) scope = RT_SCOPE_SITE; nlh = nlmsg_put(skb, portid, seq, event, sizeof(struct ifaddrmsg), flags); if (nlh == NULL) return -EMSGSIZE; put_ifaddrmsg(nlh, 128, IFA_F_PERMANENT, scope, ifindex); if (nla_put(skb, IFA_ANYCAST, 16, &ifaca->aca_addr) < 0 || put_cacheinfo(skb, ifaca->aca_cstamp, ifaca->aca_tstamp, INFINITY_LIFE_TIME, INFINITY_LIFE_TIME) < 0) { nlmsg_cancel(skb, nlh); return -EMSGSIZE; } nlmsg_end(skb, nlh); return 0; } enum addr_type_t { UNICAST_ADDR, MULTICAST_ADDR, ANYCAST_ADDR, }; /* called with rcu_read_lock() */ static int in6_dump_addrs(struct inet6_dev *idev, struct sk_buff *skb, struct netlink_callback *cb, enum addr_type_t type, int s_ip_idx, int *p_ip_idx) { struct ifmcaddr6 *ifmca; struct ifacaddr6 *ifaca; int err = 1; int ip_idx = *p_ip_idx; read_lock_bh(&idev->lock); switch (type) { case UNICAST_ADDR: { struct inet6_ifaddr *ifa; /* unicast address incl. temp addr */ list_for_each_entry(ifa, &idev->addr_list, if_list) { if (++ip_idx < s_ip_idx) continue; err = inet6_fill_ifaddr(skb, ifa, NETLINK_CB(cb->skb).portid, cb->nlh->nlmsg_seq, RTM_NEWADDR, NLM_F_MULTI); if (err < 0) break; nl_dump_check_consistent(cb, nlmsg_hdr(skb)); } break; } case MULTICAST_ADDR: /* multicast address */ for (ifmca = idev->mc_list; ifmca; ifmca = ifmca->next, ip_idx++) { if (ip_idx < s_ip_idx) continue; err = inet6_fill_ifmcaddr(skb, ifmca, NETLINK_CB(cb->skb).portid, cb->nlh->nlmsg_seq, RTM_GETMULTICAST, NLM_F_MULTI); if (err < 0) break; } break; case ANYCAST_ADDR: /* anycast address */ for (ifaca = idev->ac_list; ifaca; ifaca = ifaca->aca_next, ip_idx++) { if (ip_idx < s_ip_idx) continue; err = inet6_fill_ifacaddr(skb, ifaca, NETLINK_CB(cb->skb).portid, cb->nlh->nlmsg_seq, RTM_GETANYCAST, NLM_F_MULTI); if (err < 0) break; } break; default: break; } read_unlock_bh(&idev->lock); *p_ip_idx = ip_idx; return err; } static int inet6_dump_addr(struct sk_buff *skb, struct netlink_callback *cb, enum addr_type_t type) { struct net *net = sock_net(skb->sk); int h, s_h; int idx, ip_idx; int s_idx, s_ip_idx; struct net_device *dev; struct inet6_dev *idev; struct hlist_head *head; s_h = cb->args[0]; s_idx = idx = cb->args[1]; s_ip_idx = ip_idx = cb->args[2]; rcu_read_lock(); cb->seq = atomic_read(&net->ipv6.dev_addr_genid) ^ net->dev_base_seq; for (h = s_h; h < NETDEV_HASHENTRIES; h++, s_idx = 0) { idx = 0; head = &net->dev_index_head[h]; hlist_for_each_entry_rcu(dev, head, index_hlist) { if (idx < s_idx) goto cont; if (h > s_h || idx > s_idx) s_ip_idx = 0; ip_idx = 0; idev = __in6_dev_get(dev); if (!idev) goto cont; if (in6_dump_addrs(idev, skb, cb, type, s_ip_idx, &ip_idx) < 0) goto done; cont: idx++; } } done: rcu_read_unlock(); cb->args[0] = h; cb->args[1] = idx; cb->args[2] = ip_idx; return skb->len; } static int inet6_dump_ifaddr(struct sk_buff *skb, struct netlink_callback *cb) { enum addr_type_t type = UNICAST_ADDR; return inet6_dump_addr(skb, cb, type); } static int inet6_dump_ifmcaddr(struct sk_buff *skb, struct netlink_callback *cb) { enum addr_type_t type = MULTICAST_ADDR; return inet6_dump_addr(skb, cb, type); } static int inet6_dump_ifacaddr(struct sk_buff *skb, struct netlink_callback *cb) { enum addr_type_t type = ANYCAST_ADDR; return inet6_dump_addr(skb, cb, type); } static int inet6_rtm_getaddr(struct sk_buff *in_skb, struct nlmsghdr *nlh) { struct net *net = sock_net(in_skb->sk); struct ifaddrmsg *ifm; struct nlattr *tb[IFA_MAX+1]; struct in6_addr *addr = NULL, *peer; struct net_device *dev = NULL; struct inet6_ifaddr *ifa; struct sk_buff *skb; int err; err = nlmsg_parse(nlh, sizeof(*ifm), tb, IFA_MAX, ifa_ipv6_policy); if (err < 0) goto errout; addr = extract_addr(tb[IFA_ADDRESS], tb[IFA_LOCAL], &peer); if (addr == NULL) { err = -EINVAL; goto errout; } ifm = nlmsg_data(nlh); if (ifm->ifa_index) dev = __dev_get_by_index(net, ifm->ifa_index); ifa = ipv6_get_ifaddr(net, addr, dev, 1); if (!ifa) { err = -EADDRNOTAVAIL; goto errout; } skb = nlmsg_new(inet6_ifaddr_msgsize(), GFP_KERNEL); if (!skb) { err = -ENOBUFS; goto errout_ifa; } err = inet6_fill_ifaddr(skb, ifa, NETLINK_CB(in_skb).portid, nlh->nlmsg_seq, RTM_NEWADDR, 0); if (err < 0) { /* -EMSGSIZE implies BUG in inet6_ifaddr_msgsize() */ WARN_ON(err == -EMSGSIZE); kfree_skb(skb); goto errout_ifa; } err = rtnl_unicast(skb, net, NETLINK_CB(in_skb).portid); errout_ifa: in6_ifa_put(ifa); errout: return err; } static void inet6_ifa_notify(int event, struct inet6_ifaddr *ifa) { struct sk_buff *skb; struct net *net = dev_net(ifa->idev->dev); int err = -ENOBUFS; skb = nlmsg_new(inet6_ifaddr_msgsize(), GFP_ATOMIC); if (skb == NULL) goto errout; err = inet6_fill_ifaddr(skb, ifa, 0, 0, event, 0); if (err < 0) { /* -EMSGSIZE implies BUG in inet6_ifaddr_msgsize() */ WARN_ON(err == -EMSGSIZE); kfree_skb(skb); goto errout; } rtnl_notify(skb, net, 0, RTNLGRP_IPV6_IFADDR, NULL, GFP_ATOMIC); return; errout: if (err < 0) rtnl_set_sk_err(net, RTNLGRP_IPV6_IFADDR, err); } static inline void ipv6_store_devconf(struct ipv6_devconf *cnf, __s32 *array, int bytes) { BUG_ON(bytes < (DEVCONF_MAX * 4)); memset(array, 0, bytes); array[DEVCONF_FORWARDING] = cnf->forwarding; array[DEVCONF_HOPLIMIT] = cnf->hop_limit; array[DEVCONF_MTU6] = cnf->mtu6; array[DEVCONF_ACCEPT_RA] = cnf->accept_ra; array[DEVCONF_ACCEPT_REDIRECTS] = cnf->accept_redirects; array[DEVCONF_AUTOCONF] = cnf->autoconf; array[DEVCONF_DAD_TRANSMITS] = cnf->dad_transmits; array[DEVCONF_RTR_SOLICITS] = cnf->rtr_solicits; array[DEVCONF_RTR_SOLICIT_INTERVAL] = jiffies_to_msecs(cnf->rtr_solicit_interval); array[DEVCONF_RTR_SOLICIT_DELAY] = jiffies_to_msecs(cnf->rtr_solicit_delay); array[DEVCONF_FORCE_MLD_VERSION] = cnf->force_mld_version; array[DEVCONF_MLDV1_UNSOLICITED_REPORT_INTERVAL] = jiffies_to_msecs(cnf->mldv1_unsolicited_report_interval); array[DEVCONF_MLDV2_UNSOLICITED_REPORT_INTERVAL] = jiffies_to_msecs(cnf->mldv2_unsolicited_report_interval); array[DEVCONF_USE_TEMPADDR] = cnf->use_tempaddr; array[DEVCONF_TEMP_VALID_LFT] = cnf->temp_valid_lft; array[DEVCONF_TEMP_PREFERED_LFT] = cnf->temp_prefered_lft; array[DEVCONF_REGEN_MAX_RETRY] = cnf->regen_max_retry; array[DEVCONF_MAX_DESYNC_FACTOR] = cnf->max_desync_factor; array[DEVCONF_MAX_ADDRESSES] = cnf->max_addresses; array[DEVCONF_ACCEPT_RA_DEFRTR] = cnf->accept_ra_defrtr; array[DEVCONF_ACCEPT_RA_PINFO] = cnf->accept_ra_pinfo; #ifdef CONFIG_IPV6_ROUTER_PREF array[DEVCONF_ACCEPT_RA_RTR_PREF] = cnf->accept_ra_rtr_pref; array[DEVCONF_RTR_PROBE_INTERVAL] = jiffies_to_msecs(cnf->rtr_probe_interval); #ifdef CONFIG_IPV6_ROUTE_INFO array[DEVCONF_ACCEPT_RA_RT_INFO_MAX_PLEN] = cnf->accept_ra_rt_info_max_plen; #endif #endif array[DEVCONF_PROXY_NDP] = cnf->proxy_ndp; array[DEVCONF_ACCEPT_SOURCE_ROUTE] = cnf->accept_source_route; #ifdef CONFIG_IPV6_OPTIMISTIC_DAD array[DEVCONF_OPTIMISTIC_DAD] = cnf->optimistic_dad; array[DEVCONF_USE_OPTIMISTIC] = cnf->use_optimistic; #endif #ifdef CONFIG_IPV6_MROUTE array[DEVCONF_MC_FORWARDING] = cnf->mc_forwarding; #endif array[DEVCONF_DISABLE_IPV6] = cnf->disable_ipv6; array[DEVCONF_ACCEPT_DAD] = cnf->accept_dad; array[DEVCONF_FORCE_TLLAO] = cnf->force_tllao; array[DEVCONF_NDISC_NOTIFY] = cnf->ndisc_notify; array[DEVCONF_SUPPRESS_FRAG_NDISC] = cnf->suppress_frag_ndisc; array[DEVCONF_ACCEPT_RA_FROM_LOCAL] = cnf->accept_ra_from_local; array[DEVCONF_ACCEPT_RA_MTU] = cnf->accept_ra_mtu; } static inline size_t inet6_ifla6_size(void) { return nla_total_size(4) /* IFLA_INET6_FLAGS */ + nla_total_size(sizeof(struct ifla_cacheinfo)) + nla_total_size(DEVCONF_MAX * 4) /* IFLA_INET6_CONF */ + nla_total_size(IPSTATS_MIB_MAX * 8) /* IFLA_INET6_STATS */ + nla_total_size(ICMP6_MIB_MAX * 8) /* IFLA_INET6_ICMP6STATS */ + nla_total_size(sizeof(struct in6_addr)); /* IFLA_INET6_TOKEN */ } static inline size_t inet6_if_nlmsg_size(void) { return NLMSG_ALIGN(sizeof(struct ifinfomsg)) + nla_total_size(IFNAMSIZ) /* IFLA_IFNAME */ + nla_total_size(MAX_ADDR_LEN) /* IFLA_ADDRESS */ + nla_total_size(4) /* IFLA_MTU */ + nla_total_size(4) /* IFLA_LINK */ + nla_total_size(inet6_ifla6_size()); /* IFLA_PROTINFO */ } static inline void __snmp6_fill_statsdev(u64 *stats, atomic_long_t *mib, int items, int bytes) { int i; int pad = bytes - sizeof(u64) * items; BUG_ON(pad < 0); /* Use put_unaligned() because stats may not be aligned for u64. */ put_unaligned(items, &stats[0]); for (i = 1; i < items; i++) put_unaligned(atomic_long_read(&mib[i]), &stats[i]); memset(&stats[items], 0, pad); } static inline void __snmp6_fill_stats64(u64 *stats, void __percpu *mib, int items, int bytes, size_t syncpoff) { int i; int pad = bytes - sizeof(u64) * items; BUG_ON(pad < 0); /* Use put_unaligned() because stats may not be aligned for u64. */ put_unaligned(items, &stats[0]); for (i = 1; i < items; i++) put_unaligned(snmp_fold_field64(mib, i, syncpoff), &stats[i]); memset(&stats[items], 0, pad); } static void snmp6_fill_stats(u64 *stats, struct inet6_dev *idev, int attrtype, int bytes) { switch (attrtype) { case IFLA_INET6_STATS: __snmp6_fill_stats64(stats, idev->stats.ipv6, IPSTATS_MIB_MAX, bytes, offsetof(struct ipstats_mib, syncp)); break; case IFLA_INET6_ICMP6STATS: __snmp6_fill_statsdev(stats, idev->stats.icmpv6dev->mibs, ICMP6_MIB_MAX, bytes); break; } } static int inet6_fill_ifla6_attrs(struct sk_buff *skb, struct inet6_dev *idev) { struct nlattr *nla; struct ifla_cacheinfo ci; if (nla_put_u32(skb, IFLA_INET6_FLAGS, idev->if_flags)) goto nla_put_failure; ci.max_reasm_len = IPV6_MAXPLEN; ci.tstamp = cstamp_delta(idev->tstamp); ci.reachable_time = jiffies_to_msecs(idev->nd_parms->reachable_time); ci.retrans_time = jiffies_to_msecs(NEIGH_VAR(idev->nd_parms, RETRANS_TIME)); if (nla_put(skb, IFLA_INET6_CACHEINFO, sizeof(ci), &ci)) goto nla_put_failure; nla = nla_reserve(skb, IFLA_INET6_CONF, DEVCONF_MAX * sizeof(s32)); if (nla == NULL) goto nla_put_failure; ipv6_store_devconf(&idev->cnf, nla_data(nla), nla_len(nla)); /* XXX - MC not implemented */ nla = nla_reserve(skb, IFLA_INET6_STATS, IPSTATS_MIB_MAX * sizeof(u64)); if (nla == NULL) goto nla_put_failure; snmp6_fill_stats(nla_data(nla), idev, IFLA_INET6_STATS, nla_len(nla)); nla = nla_reserve(skb, IFLA_INET6_ICMP6STATS, ICMP6_MIB_MAX * sizeof(u64)); if (nla == NULL) goto nla_put_failure; snmp6_fill_stats(nla_data(nla), idev, IFLA_INET6_ICMP6STATS, nla_len(nla)); nla = nla_reserve(skb, IFLA_INET6_TOKEN, sizeof(struct in6_addr)); if (nla == NULL) goto nla_put_failure; if (nla_put_u8(skb, IFLA_INET6_ADDR_GEN_MODE, idev->addr_gen_mode)) goto nla_put_failure; read_lock_bh(&idev->lock); memcpy(nla_data(nla), idev->token.s6_addr, nla_len(nla)); read_unlock_bh(&idev->lock); return 0; nla_put_failure: return -EMSGSIZE; } static size_t inet6_get_link_af_size(const struct net_device *dev) { if (!__in6_dev_get(dev)) return 0; return inet6_ifla6_size(); } static int inet6_fill_link_af(struct sk_buff *skb, const struct net_device *dev) { struct inet6_dev *idev = __in6_dev_get(dev); if (!idev) return -ENODATA; if (inet6_fill_ifla6_attrs(skb, idev) < 0) return -EMSGSIZE; return 0; } static int inet6_set_iftoken(struct inet6_dev *idev, struct in6_addr *token) { struct inet6_ifaddr *ifp; struct net_device *dev = idev->dev; bool update_rs = false; struct in6_addr ll_addr; ASSERT_RTNL(); if (token == NULL) return -EINVAL; if (ipv6_addr_any(token)) return -EINVAL; if (dev->flags & (IFF_LOOPBACK | IFF_NOARP)) return -EINVAL; if (!ipv6_accept_ra(idev)) return -EINVAL; if (idev->cnf.rtr_solicits <= 0) return -EINVAL; write_lock_bh(&idev->lock); BUILD_BUG_ON(sizeof(token->s6_addr) != 16); memcpy(idev->token.s6_addr + 8, token->s6_addr + 8, 8); write_unlock_bh(&idev->lock); if (!idev->dead && (idev->if_flags & IF_READY) && !ipv6_get_lladdr(dev, &ll_addr, IFA_F_TENTATIVE | IFA_F_OPTIMISTIC)) { /* If we're not ready, then normal ifup will take care * of this. Otherwise, we need to request our rs here. */ ndisc_send_rs(dev, &ll_addr, &in6addr_linklocal_allrouters); update_rs = true; } write_lock_bh(&idev->lock); if (update_rs) { idev->if_flags |= IF_RS_SENT; idev->rs_probes = 1; addrconf_mod_rs_timer(idev, idev->cnf.rtr_solicit_interval); } /* Well, that's kinda nasty ... */ list_for_each_entry(ifp, &idev->addr_list, if_list) { spin_lock(&ifp->lock); if (ifp->tokenized) { ifp->valid_lft = 0; ifp->prefered_lft = 0; } spin_unlock(&ifp->lock); } write_unlock_bh(&idev->lock); inet6_ifinfo_notify(RTM_NEWLINK, idev); addrconf_verify_rtnl(); return 0; } static const struct nla_policy inet6_af_policy[IFLA_INET6_MAX + 1] = { [IFLA_INET6_ADDR_GEN_MODE] = { .type = NLA_U8 }, [IFLA_INET6_TOKEN] = { .len = sizeof(struct in6_addr) }, }; static int inet6_validate_link_af(const struct net_device *dev, const struct nlattr *nla) { struct nlattr *tb[IFLA_INET6_MAX + 1]; if (dev && !__in6_dev_get(dev)) return -EAFNOSUPPORT; return nla_parse_nested(tb, IFLA_INET6_MAX, nla, inet6_af_policy); } static int inet6_set_link_af(struct net_device *dev, const struct nlattr *nla) { int err = -EINVAL; struct inet6_dev *idev = __in6_dev_get(dev); struct nlattr *tb[IFLA_INET6_MAX + 1]; if (!idev) return -EAFNOSUPPORT; if (nla_parse_nested(tb, IFLA_INET6_MAX, nla, NULL) < 0) BUG(); if (tb[IFLA_INET6_TOKEN]) { err = inet6_set_iftoken(idev, nla_data(tb[IFLA_INET6_TOKEN])); if (err) return err; } if (tb[IFLA_INET6_ADDR_GEN_MODE]) { u8 mode = nla_get_u8(tb[IFLA_INET6_ADDR_GEN_MODE]); if (mode != IN6_ADDR_GEN_MODE_EUI64 && mode != IN6_ADDR_GEN_MODE_NONE) return -EINVAL; idev->addr_gen_mode = mode; err = 0; } return err; } static int inet6_fill_ifinfo(struct sk_buff *skb, struct inet6_dev *idev, u32 portid, u32 seq, int event, unsigned int flags) { struct net_device *dev = idev->dev; struct ifinfomsg *hdr; struct nlmsghdr *nlh; void *protoinfo; nlh = nlmsg_put(skb, portid, seq, event, sizeof(*hdr), flags); if (nlh == NULL) return -EMSGSIZE; hdr = nlmsg_data(nlh); hdr->ifi_family = AF_INET6; hdr->__ifi_pad = 0; hdr->ifi_type = dev->type; hdr->ifi_index = dev->ifindex; hdr->ifi_flags = dev_get_flags(dev); hdr->ifi_change = 0; if (nla_put_string(skb, IFLA_IFNAME, dev->name) || (dev->addr_len && nla_put(skb, IFLA_ADDRESS, dev->addr_len, dev->dev_addr)) || nla_put_u32(skb, IFLA_MTU, dev->mtu) || (dev->ifindex != dev->iflink && nla_put_u32(skb, IFLA_LINK, dev->iflink))) goto nla_put_failure; protoinfo = nla_nest_start(skb, IFLA_PROTINFO); if (protoinfo == NULL) goto nla_put_failure; if (inet6_fill_ifla6_attrs(skb, idev) < 0) goto nla_put_failure; nla_nest_end(skb, protoinfo); nlmsg_end(skb, nlh); return 0; nla_put_failure: nlmsg_cancel(skb, nlh); return -EMSGSIZE; } static int inet6_dump_ifinfo(struct sk_buff *skb, struct netlink_callback *cb) { struct net *net = sock_net(skb->sk); int h, s_h; int idx = 0, s_idx; struct net_device *dev; struct inet6_dev *idev; struct hlist_head *head; s_h = cb->args[0]; s_idx = cb->args[1]; rcu_read_lock(); for (h = s_h; h < NETDEV_HASHENTRIES; h++, s_idx = 0) { idx = 0; head = &net->dev_index_head[h]; hlist_for_each_entry_rcu(dev, head, index_hlist) { if (idx < s_idx) goto cont; idev = __in6_dev_get(dev); if (!idev) goto cont; if (inet6_fill_ifinfo(skb, idev, NETLINK_CB(cb->skb).portid, cb->nlh->nlmsg_seq, RTM_NEWLINK, NLM_F_MULTI) < 0) goto out; cont: idx++; } } out: rcu_read_unlock(); cb->args[1] = idx; cb->args[0] = h; return skb->len; } void inet6_ifinfo_notify(int event, struct inet6_dev *idev) { struct sk_buff *skb; struct net *net = dev_net(idev->dev); int err = -ENOBUFS; skb = nlmsg_new(inet6_if_nlmsg_size(), GFP_ATOMIC); if (skb == NULL) goto errout; err = inet6_fill_ifinfo(skb, idev, 0, 0, event, 0); if (err < 0) { /* -EMSGSIZE implies BUG in inet6_if_nlmsg_size() */ WARN_ON(err == -EMSGSIZE); kfree_skb(skb); goto errout; } rtnl_notify(skb, net, 0, RTNLGRP_IPV6_IFINFO, NULL, GFP_ATOMIC); return; errout: if (err < 0) rtnl_set_sk_err(net, RTNLGRP_IPV6_IFINFO, err); } static inline size_t inet6_prefix_nlmsg_size(void) { return NLMSG_ALIGN(sizeof(struct prefixmsg)) + nla_total_size(sizeof(struct in6_addr)) + nla_total_size(sizeof(struct prefix_cacheinfo)); } static int inet6_fill_prefix(struct sk_buff *skb, struct inet6_dev *idev, struct prefix_info *pinfo, u32 portid, u32 seq, int event, unsigned int flags) { struct prefixmsg *pmsg; struct nlmsghdr *nlh; struct prefix_cacheinfo ci; nlh = nlmsg_put(skb, portid, seq, event, sizeof(*pmsg), flags); if (nlh == NULL) return -EMSGSIZE; pmsg = nlmsg_data(nlh); pmsg->prefix_family = AF_INET6; pmsg->prefix_pad1 = 0; pmsg->prefix_pad2 = 0; pmsg->prefix_ifindex = idev->dev->ifindex; pmsg->prefix_len = pinfo->prefix_len; pmsg->prefix_type = pinfo->type; pmsg->prefix_pad3 = 0; pmsg->prefix_flags = 0; if (pinfo->onlink) pmsg->prefix_flags |= IF_PREFIX_ONLINK; if (pinfo->autoconf) pmsg->prefix_flags |= IF_PREFIX_AUTOCONF; if (nla_put(skb, PREFIX_ADDRESS, sizeof(pinfo->prefix), &pinfo->prefix)) goto nla_put_failure; ci.preferred_time = ntohl(pinfo->prefered); ci.valid_time = ntohl(pinfo->valid); if (nla_put(skb, PREFIX_CACHEINFO, sizeof(ci), &ci)) goto nla_put_failure; nlmsg_end(skb, nlh); return 0; nla_put_failure: nlmsg_cancel(skb, nlh); return -EMSGSIZE; } static void inet6_prefix_notify(int event, struct inet6_dev *idev, struct prefix_info *pinfo) { struct sk_buff *skb; struct net *net = dev_net(idev->dev); int err = -ENOBUFS; skb = nlmsg_new(inet6_prefix_nlmsg_size(), GFP_ATOMIC); if (skb == NULL) goto errout; err = inet6_fill_prefix(skb, idev, pinfo, 0, 0, event, 0); if (err < 0) { /* -EMSGSIZE implies BUG in inet6_prefix_nlmsg_size() */ WARN_ON(err == -EMSGSIZE); kfree_skb(skb); goto errout; } rtnl_notify(skb, net, 0, RTNLGRP_IPV6_PREFIX, NULL, GFP_ATOMIC); return; errout: if (err < 0) rtnl_set_sk_err(net, RTNLGRP_IPV6_PREFIX, err); } static void __ipv6_ifa_notify(int event, struct inet6_ifaddr *ifp) { struct net *net = dev_net(ifp->idev->dev); if (event) ASSERT_RTNL(); inet6_ifa_notify(event ? : RTM_NEWADDR, ifp); switch (event) { case RTM_NEWADDR: /* * If the address was optimistic * we inserted the route at the start of * our DAD process, so we don't need * to do it again */ if (!(ifp->rt->rt6i_node)) ip6_ins_rt(ifp->rt); if (ifp->idev->cnf.forwarding) addrconf_join_anycast(ifp); if (!ipv6_addr_any(&ifp->peer_addr)) addrconf_prefix_route(&ifp->peer_addr, 128, ifp->idev->dev, 0, 0); break; case RTM_DELADDR: if (ifp->idev->cnf.forwarding) addrconf_leave_anycast(ifp); addrconf_leave_solict(ifp->idev, &ifp->addr); if (!ipv6_addr_any(&ifp->peer_addr)) { struct rt6_info *rt; rt = addrconf_get_prefix_route(&ifp->peer_addr, 128, ifp->idev->dev, 0, 0); if (rt && ip6_del_rt(rt)) dst_free(&rt->dst); } dst_hold(&ifp->rt->dst); if (ip6_del_rt(ifp->rt)) dst_free(&ifp->rt->dst); rt_genid_bump_ipv6(net); break; } atomic_inc(&net->ipv6.dev_addr_genid); } static void ipv6_ifa_notify(int event, struct inet6_ifaddr *ifp) { rcu_read_lock_bh(); if (likely(ifp->idev->dead == 0)) __ipv6_ifa_notify(event, ifp); rcu_read_unlock_bh(); } #ifdef CONFIG_SYSCTL static int addrconf_sysctl_forward(struct ctl_table *ctl, int write, void __user *buffer, size_t *lenp, loff_t *ppos) { int *valp = ctl->data; int val = *valp; loff_t pos = *ppos; struct ctl_table lctl; int ret; /* * ctl->data points to idev->cnf.forwarding, we should * not modify it until we get the rtnl lock. */ lctl = *ctl; lctl.data = &val; ret = proc_dointvec(&lctl, write, buffer, lenp, ppos); if (write) ret = addrconf_fixup_forwarding(ctl, valp, val); if (ret) *ppos = pos; return ret; } static int addrconf_sysctl_mtu(struct ctl_table *ctl, int write, void __user *buffer, size_t *lenp, loff_t *ppos) { struct inet6_dev *idev = ctl->extra1; int min_mtu = IPV6_MIN_MTU; struct ctl_table lctl; lctl = *ctl; lctl.extra1 = &min_mtu; lctl.extra2 = idev ? &idev->dev->mtu : NULL; return proc_dointvec_minmax(&lctl, write, buffer, lenp, ppos); } static void dev_disable_change(struct inet6_dev *idev) { struct netdev_notifier_info info; if (!idev || !idev->dev) return; netdev_notifier_info_init(&info, idev->dev); if (idev->cnf.disable_ipv6) addrconf_notify(NULL, NETDEV_DOWN, &info); else addrconf_notify(NULL, NETDEV_UP, &info); } static void addrconf_disable_change(struct net *net, __s32 newf) { struct net_device *dev; struct inet6_dev *idev; rcu_read_lock(); for_each_netdev_rcu(net, dev) { idev = __in6_dev_get(dev); if (idev) { int changed = (!idev->cnf.disable_ipv6) ^ (!newf); idev->cnf.disable_ipv6 = newf; if (changed) dev_disable_change(idev); } } rcu_read_unlock(); } static int addrconf_disable_ipv6(struct ctl_table *table, int *p, int newf) { struct net *net; int old; if (!rtnl_trylock()) return restart_syscall(); net = (struct net *)table->extra2; old = *p; *p = newf; if (p == &net->ipv6.devconf_dflt->disable_ipv6) { rtnl_unlock(); return 0; } if (p == &net->ipv6.devconf_all->disable_ipv6) { net->ipv6.devconf_dflt->disable_ipv6 = newf; addrconf_disable_change(net, newf); } else if ((!newf) ^ (!old)) dev_disable_change((struct inet6_dev *)table->extra1); rtnl_unlock(); return 0; } static int addrconf_sysctl_disable(struct ctl_table *ctl, int write, void __user *buffer, size_t *lenp, loff_t *ppos) { int *valp = ctl->data; int val = *valp; loff_t pos = *ppos; struct ctl_table lctl; int ret; /* * ctl->data points to idev->cnf.disable_ipv6, we should * not modify it until we get the rtnl lock. */ lctl = *ctl; lctl.data = &val; ret = proc_dointvec(&lctl, write, buffer, lenp, ppos); if (write) ret = addrconf_disable_ipv6(ctl, valp, val); if (ret) *ppos = pos; return ret; } static int addrconf_sysctl_proxy_ndp(struct ctl_table *ctl, int write, void __user *buffer, size_t *lenp, loff_t *ppos) { int *valp = ctl->data; int ret; int old, new; old = *valp; ret = proc_dointvec(ctl, write, buffer, lenp, ppos); new = *valp; if (write && old != new) { struct net *net = ctl->extra2; if (!rtnl_trylock()) return restart_syscall(); if (valp == &net->ipv6.devconf_dflt->proxy_ndp) inet6_netconf_notify_devconf(net, NETCONFA_PROXY_NEIGH, NETCONFA_IFINDEX_DEFAULT, net->ipv6.devconf_dflt); else if (valp == &net->ipv6.devconf_all->proxy_ndp) inet6_netconf_notify_devconf(net, NETCONFA_PROXY_NEIGH, NETCONFA_IFINDEX_ALL, net->ipv6.devconf_all); else { struct inet6_dev *idev = ctl->extra1; inet6_netconf_notify_devconf(net, NETCONFA_PROXY_NEIGH, idev->dev->ifindex, &idev->cnf); } rtnl_unlock(); } return ret; } static struct addrconf_sysctl_table { struct ctl_table_header *sysctl_header; struct ctl_table addrconf_vars[DEVCONF_MAX+1]; } addrconf_sysctl __read_mostly = { .sysctl_header = NULL, .addrconf_vars = { { .procname = "forwarding", .data = &ipv6_devconf.forwarding, .maxlen = sizeof(int), .mode = 0644, .proc_handler = addrconf_sysctl_forward, }, { .procname = "hop_limit", .data = &ipv6_devconf.hop_limit, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "mtu", .data = &ipv6_devconf.mtu6, .maxlen = sizeof(int), .mode = 0644, .proc_handler = addrconf_sysctl_mtu, }, { .procname = "accept_ra", .data = &ipv6_devconf.accept_ra, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "accept_redirects", .data = &ipv6_devconf.accept_redirects, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "autoconf", .data = &ipv6_devconf.autoconf, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "dad_transmits", .data = &ipv6_devconf.dad_transmits, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "router_solicitations", .data = &ipv6_devconf.rtr_solicits, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "router_solicitation_interval", .data = &ipv6_devconf.rtr_solicit_interval, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec_jiffies, }, { .procname = "router_solicitation_delay", .data = &ipv6_devconf.rtr_solicit_delay, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec_jiffies, }, { .procname = "force_mld_version", .data = &ipv6_devconf.force_mld_version, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "mldv1_unsolicited_report_interval", .data = &ipv6_devconf.mldv1_unsolicited_report_interval, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec_ms_jiffies, }, { .procname = "mldv2_unsolicited_report_interval", .data = &ipv6_devconf.mldv2_unsolicited_report_interval, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec_ms_jiffies, }, { .procname = "use_tempaddr", .data = &ipv6_devconf.use_tempaddr, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "temp_valid_lft", .data = &ipv6_devconf.temp_valid_lft, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "temp_prefered_lft", .data = &ipv6_devconf.temp_prefered_lft, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "regen_max_retry", .data = &ipv6_devconf.regen_max_retry, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "max_desync_factor", .data = &ipv6_devconf.max_desync_factor, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "max_addresses", .data = &ipv6_devconf.max_addresses, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "accept_ra_defrtr", .data = &ipv6_devconf.accept_ra_defrtr, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "accept_ra_pinfo", .data = &ipv6_devconf.accept_ra_pinfo, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, #ifdef CONFIG_IPV6_ROUTER_PREF { .procname = "accept_ra_rtr_pref", .data = &ipv6_devconf.accept_ra_rtr_pref, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "router_probe_interval", .data = &ipv6_devconf.rtr_probe_interval, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec_jiffies, }, #ifdef CONFIG_IPV6_ROUTE_INFO { .procname = "accept_ra_rt_info_max_plen", .data = &ipv6_devconf.accept_ra_rt_info_max_plen, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, #endif #endif { .procname = "proxy_ndp", .data = &ipv6_devconf.proxy_ndp, .maxlen = sizeof(int), .mode = 0644, .proc_handler = addrconf_sysctl_proxy_ndp, }, { .procname = "accept_source_route", .data = &ipv6_devconf.accept_source_route, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, #ifdef CONFIG_IPV6_OPTIMISTIC_DAD { .procname = "optimistic_dad", .data = &ipv6_devconf.optimistic_dad, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "use_optimistic", .data = &ipv6_devconf.use_optimistic, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, #endif #ifdef CONFIG_IPV6_MROUTE { .procname = "mc_forwarding", .data = &ipv6_devconf.mc_forwarding, .maxlen = sizeof(int), .mode = 0444, .proc_handler = proc_dointvec, }, #endif { .procname = "disable_ipv6", .data = &ipv6_devconf.disable_ipv6, .maxlen = sizeof(int), .mode = 0644, .proc_handler = addrconf_sysctl_disable, }, { .procname = "accept_dad", .data = &ipv6_devconf.accept_dad, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "force_tllao", .data = &ipv6_devconf.force_tllao, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec }, { .procname = "ndisc_notify", .data = &ipv6_devconf.ndisc_notify, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec }, { .procname = "suppress_frag_ndisc", .data = &ipv6_devconf.suppress_frag_ndisc, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec }, { .procname = "accept_ra_from_local", .data = &ipv6_devconf.accept_ra_from_local, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "accept_ra_mtu", .data = &ipv6_devconf.accept_ra_mtu, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { /* sentinel */ } }, }; static int __addrconf_sysctl_register(struct net *net, char *dev_name, struct inet6_dev *idev, struct ipv6_devconf *p) { int i; struct addrconf_sysctl_table *t; char path[sizeof("net/ipv6/conf/") + IFNAMSIZ]; t = kmemdup(&addrconf_sysctl, sizeof(*t), GFP_KERNEL); if (t == NULL) goto out; for (i = 0; t->addrconf_vars[i].data; i++) { t->addrconf_vars[i].data += (char *)p - (char *)&ipv6_devconf; t->addrconf_vars[i].extra1 = idev; /* embedded; no ref */ t->addrconf_vars[i].extra2 = net; } snprintf(path, sizeof(path), "net/ipv6/conf/%s", dev_name); t->sysctl_header = register_net_sysctl(net, path, t->addrconf_vars); if (t->sysctl_header == NULL) goto free; p->sysctl = t; return 0; free: kfree(t); out: return -ENOBUFS; } static void __addrconf_sysctl_unregister(struct ipv6_devconf *p) { struct addrconf_sysctl_table *t; if (p->sysctl == NULL) return; t = p->sysctl; p->sysctl = NULL; unregister_net_sysctl_table(t->sysctl_header); kfree(t); } static int addrconf_sysctl_register(struct inet6_dev *idev) { int err; if (!sysctl_dev_name_is_allowed(idev->dev->name)) return -EINVAL; err = neigh_sysctl_register(idev->dev, idev->nd_parms, &ndisc_ifinfo_sysctl_change); if (err) return err; err = __addrconf_sysctl_register(dev_net(idev->dev), idev->dev->name, idev, &idev->cnf); if (err) neigh_sysctl_unregister(idev->nd_parms); return err; } static void addrconf_sysctl_unregister(struct inet6_dev *idev) { __addrconf_sysctl_unregister(&idev->cnf); neigh_sysctl_unregister(idev->nd_parms); } #endif static int __net_init addrconf_init_net(struct net *net) { int err = -ENOMEM; struct ipv6_devconf *all, *dflt; all = kmemdup(&ipv6_devconf, sizeof(ipv6_devconf), GFP_KERNEL); if (all == NULL) goto err_alloc_all; dflt = kmemdup(&ipv6_devconf_dflt, sizeof(ipv6_devconf_dflt), GFP_KERNEL); if (dflt == NULL) goto err_alloc_dflt; /* these will be inherited by all namespaces */ dflt->autoconf = ipv6_defaults.autoconf; dflt->disable_ipv6 = ipv6_defaults.disable_ipv6; net->ipv6.devconf_all = all; net->ipv6.devconf_dflt = dflt; #ifdef CONFIG_SYSCTL err = __addrconf_sysctl_register(net, "all", NULL, all); if (err < 0) goto err_reg_all; err = __addrconf_sysctl_register(net, "default", NULL, dflt); if (err < 0) goto err_reg_dflt; #endif return 0; #ifdef CONFIG_SYSCTL err_reg_dflt: __addrconf_sysctl_unregister(all); err_reg_all: kfree(dflt); #endif err_alloc_dflt: kfree(all); err_alloc_all: return err; } static void __net_exit addrconf_exit_net(struct net *net) { #ifdef CONFIG_SYSCTL __addrconf_sysctl_unregister(net->ipv6.devconf_dflt); __addrconf_sysctl_unregister(net->ipv6.devconf_all); #endif kfree(net->ipv6.devconf_dflt); kfree(net->ipv6.devconf_all); } static struct pernet_operations addrconf_ops = { .init = addrconf_init_net, .exit = addrconf_exit_net, }; static struct rtnl_af_ops inet6_ops __read_mostly = { .family = AF_INET6, .fill_link_af = inet6_fill_link_af, .get_link_af_size = inet6_get_link_af_size, .validate_link_af = inet6_validate_link_af, .set_link_af = inet6_set_link_af, }; /* * Init / cleanup code */ int __init addrconf_init(void) { struct inet6_dev *idev; int i, err; err = ipv6_addr_label_init(); if (err < 0) { pr_crit("%s: cannot initialize default policy table: %d\n", __func__, err); goto out; } err = register_pernet_subsys(&addrconf_ops); if (err < 0) goto out_addrlabel; addrconf_wq = create_workqueue("ipv6_addrconf"); if (!addrconf_wq) { err = -ENOMEM; goto out_nowq; } /* The addrconf netdev notifier requires that loopback_dev * has it's ipv6 private information allocated and setup * before it can bring up and give link-local addresses * to other devices which are up. * * Unfortunately, loopback_dev is not necessarily the first * entry in the global dev_base list of net devices. In fact, * it is likely to be the very last entry on that list. * So this causes the notifier registry below to try and * give link-local addresses to all devices besides loopback_dev * first, then loopback_dev, which cases all the non-loopback_dev * devices to fail to get a link-local address. * * So, as a temporary fix, allocate the ipv6 structure for * loopback_dev first by hand. * Longer term, all of the dependencies ipv6 has upon the loopback * device and it being up should be removed. */ rtnl_lock(); idev = ipv6_add_dev(init_net.loopback_dev); rtnl_unlock(); if (IS_ERR(idev)) { err = PTR_ERR(idev); goto errlo; } for (i = 0; i < IN6_ADDR_HSIZE; i++) INIT_HLIST_HEAD(&inet6_addr_lst[i]); register_netdevice_notifier(&ipv6_dev_notf); addrconf_verify(); rtnl_af_register(&inet6_ops); err = __rtnl_register(PF_INET6, RTM_GETLINK, NULL, inet6_dump_ifinfo, NULL); if (err < 0) goto errout; /* Only the first call to __rtnl_register can fail */ __rtnl_register(PF_INET6, RTM_NEWADDR, inet6_rtm_newaddr, NULL, NULL); __rtnl_register(PF_INET6, RTM_DELADDR, inet6_rtm_deladdr, NULL, NULL); __rtnl_register(PF_INET6, RTM_GETADDR, inet6_rtm_getaddr, inet6_dump_ifaddr, NULL); __rtnl_register(PF_INET6, RTM_GETMULTICAST, NULL, inet6_dump_ifmcaddr, NULL); __rtnl_register(PF_INET6, RTM_GETANYCAST, NULL, inet6_dump_ifacaddr, NULL); __rtnl_register(PF_INET6, RTM_GETNETCONF, inet6_netconf_get_devconf, inet6_netconf_dump_devconf, NULL); ipv6_addr_label_rtnl_register(); return 0; errout: rtnl_af_unregister(&inet6_ops); unregister_netdevice_notifier(&ipv6_dev_notf); errlo: destroy_workqueue(addrconf_wq); out_nowq: unregister_pernet_subsys(&addrconf_ops); out_addrlabel: ipv6_addr_label_cleanup(); out: return err; } void addrconf_cleanup(void) { struct net_device *dev; int i; unregister_netdevice_notifier(&ipv6_dev_notf); unregister_pernet_subsys(&addrconf_ops); ipv6_addr_label_cleanup(); rtnl_lock(); __rtnl_af_unregister(&inet6_ops); /* clean dev list */ for_each_netdev(&init_net, dev) { if (__in6_dev_get(dev) == NULL) continue; addrconf_ifdown(dev, 1); } addrconf_ifdown(init_net.loopback_dev, 2); /* * Check hash table. */ spin_lock_bh(&addrconf_hash_lock); for (i = 0; i < IN6_ADDR_HSIZE; i++) WARN_ON(!hlist_empty(&inet6_addr_lst[i])); spin_unlock_bh(&addrconf_hash_lock); cancel_delayed_work(&addr_chk_work); rtnl_unlock(); destroy_workqueue(addrconf_wq); }
./CrossVul/dataset_final_sorted/CWE-20/c/good_1776_0
crossvul-cpp_data_bad_3195_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % TTTTT GGGG AAA % % T G A A % % T G GG AAAAA % % T G G A A % % T GGG A A % % % % % % Read/Write Truevision Targa Image Format % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2017 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/artifact.h" #include "magick/attribute.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/cache.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/option.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" /* Enumerated declaractions. */ typedef enum { TGAColormap = 1, TGARGB = 2, TGAMonochrome = 3, TGARLEColormap = 9, TGARLERGB = 10, TGARLEMonochrome = 11 } TGAImageType; /* Typedef declaractions. */ typedef struct _TGAInfo { TGAImageType image_type; unsigned char id_length, colormap_type; unsigned short colormap_index, colormap_length; unsigned char colormap_size; unsigned short x_origin, y_origin, width, height; unsigned char bits_per_pixel, attributes; } TGAInfo; /* Forward declarations. */ static MagickBooleanType WriteTGAImage(const ImageInfo *,Image *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d T G A I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadTGAImage() reads a Truevision TGA 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 ReadTGAImage method is: % % Image *ReadTGAImage(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 *ReadTGAImage(const ImageInfo *image_info, ExceptionInfo *exception) { Image *image; IndexPacket index; MagickBooleanType status; PixelPacket pixel; register IndexPacket *indexes; register PixelPacket *q; register ssize_t i, x; size_t base, flag, offset, real, skip; ssize_t count, y; TGAInfo tga_info; unsigned char j, k, pixels[4], runlength; unsigned int alpha_bits; /* 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 TGA header information. */ count=ReadBlob(image,1,&tga_info.id_length); tga_info.colormap_type=(unsigned char) ReadBlobByte(image); tga_info.image_type=(TGAImageType) ReadBlobByte(image); if ((count != 1) || ((tga_info.image_type != TGAColormap) && (tga_info.image_type != TGARGB) && (tga_info.image_type != TGAMonochrome) && (tga_info.image_type != TGARLEColormap) && (tga_info.image_type != TGARLERGB) && (tga_info.image_type != TGARLEMonochrome)) || (((tga_info.image_type == TGAColormap) || (tga_info.image_type == TGARLEColormap)) && (tga_info.colormap_type == 0))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); tga_info.colormap_index=ReadBlobLSBShort(image); tga_info.colormap_length=ReadBlobLSBShort(image); tga_info.colormap_size=(unsigned char) ReadBlobByte(image); tga_info.x_origin=ReadBlobLSBShort(image); tga_info.y_origin=ReadBlobLSBShort(image); tga_info.width=(unsigned short) ReadBlobLSBShort(image); tga_info.height=(unsigned short) ReadBlobLSBShort(image); tga_info.bits_per_pixel=(unsigned char) ReadBlobByte(image); tga_info.attributes=(unsigned char) ReadBlobByte(image); if (EOFBlob(image) != MagickFalse) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); if ((((tga_info.bits_per_pixel <= 1) || (tga_info.bits_per_pixel >= 17)) && (tga_info.bits_per_pixel != 24) && (tga_info.bits_per_pixel != 32))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* Initialize image structure. */ image->columns=tga_info.width; image->rows=tga_info.height; alpha_bits=(tga_info.attributes & 0x0FU); image->matte=(alpha_bits > 0) || (tga_info.bits_per_pixel == 32) || (tga_info.colormap_size == 32) ? MagickTrue : MagickFalse; if ((tga_info.image_type != TGAColormap) && (tga_info.image_type != TGARLEColormap)) image->depth=(size_t) ((tga_info.bits_per_pixel <= 8) ? 8 : (tga_info.bits_per_pixel <= 16) ? 5 : 8); else image->depth=(size_t) ((tga_info.colormap_size <= 8) ? 8 : (tga_info.colormap_size <= 16) ? 5 : 8); if ((tga_info.image_type == TGAColormap) || (tga_info.image_type == TGAMonochrome) || (tga_info.image_type == TGARLEColormap) || (tga_info.image_type == TGARLEMonochrome)) image->storage_class=PseudoClass; image->compression=NoCompression; if ((tga_info.image_type == TGARLEColormap) || (tga_info.image_type == TGARLEMonochrome) || (tga_info.image_type == TGARLERGB)) image->compression=RLECompression; if (image->storage_class == PseudoClass) { if (tga_info.colormap_type != 0) image->colors=tga_info.colormap_index+tga_info.colormap_length; else { size_t one; one=1; image->colors=one << tga_info.bits_per_pixel; if (AcquireImageColormap(image,image->colors) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } } if (tga_info.id_length != 0) { char *comment; size_t length; /* TGA image comment. */ length=(size_t) tga_info.id_length; comment=(char *) NULL; if (~length >= (MaxTextExtent-1)) comment=(char *) AcquireQuantumMemory(length+MaxTextExtent, sizeof(*comment)); if (comment == (char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); (void) ReadBlob(image,tga_info.id_length,(unsigned char *) comment); comment[tga_info.id_length]='\0'; (void) SetImageProperty(image,"comment",comment); comment=DestroyString(comment); } if (tga_info.attributes & (1UL << 4)) { if (tga_info.attributes & (1UL << 5)) SetImageArtifact(image,"tga:image-origin","TopRight"); else SetImageArtifact(image,"tga:image-origin","BottomRight"); } else { if (tga_info.attributes & (1UL << 5)) SetImageArtifact(image,"tga:image-origin","TopLeft"); else SetImageArtifact(image,"tga:image-origin","BottomLeft"); } if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(image); } status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } (void) ResetMagickMemory(&pixel,0,sizeof(pixel)); pixel.opacity=(Quantum) OpaqueOpacity; if (tga_info.colormap_type != 0) { /* Read TGA raster colormap. */ if (image->colors < tga_info.colormap_index) image->colors=tga_info.colormap_index; if (AcquireImageColormap(image,image->colors) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) tga_info.colormap_index; i++) image->colormap[i]=pixel; for ( ; i < (ssize_t) image->colors; i++) { switch (tga_info.colormap_size) { case 8: default: { /* Gray scale. */ pixel.red=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); pixel.green=pixel.red; pixel.blue=pixel.red; break; } case 15: case 16: { QuantumAny range; /* 5 bits each of red green and blue. */ j=(unsigned char) ReadBlobByte(image); k=(unsigned char) ReadBlobByte(image); range=GetQuantumRange(5UL); pixel.red=ScaleAnyToQuantum(1UL*(k & 0x7c) >> 2,range); pixel.green=ScaleAnyToQuantum((1UL*(k & 0x03) << 3)+ (1UL*(j & 0xe0) >> 5),range); pixel.blue=ScaleAnyToQuantum(1UL*(j & 0x1f),range); break; } case 24: { /* 8 bits each of blue, green and red. */ pixel.blue=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); pixel.green=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); pixel.red=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); break; } case 32: { /* 8 bits each of blue, green, red, and alpha. */ pixel.blue=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); pixel.green=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); pixel.red=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); pixel.opacity=(Quantum) (QuantumRange-ScaleCharToQuantum( (unsigned char) ReadBlobByte(image))); break; } } image->colormap[i]=pixel; } } /* Convert TGA pixels to pixel packets. */ base=0; flag=0; skip=MagickFalse; real=0; index=(IndexPacket) 0; runlength=0; offset=0; for (y=0; y < (ssize_t) image->rows; y++) { real=offset; if (((unsigned char) (tga_info.attributes & 0x20) >> 5) == 0) real=image->rows-real-1; q=QueueAuthenticPixels(image,0,(ssize_t) real,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { if ((tga_info.image_type == TGARLEColormap) || (tga_info.image_type == TGARLERGB) || (tga_info.image_type == TGARLEMonochrome)) { if (runlength != 0) { runlength--; skip=flag != 0; } else { count=ReadBlob(image,1,&runlength); if (count != 1) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); flag=runlength & 0x80; if (flag != 0) runlength-=128; skip=MagickFalse; } } if (skip == MagickFalse) switch (tga_info.bits_per_pixel) { case 8: default: { /* Gray scale. */ index=(IndexPacket) ReadBlobByte(image); if (tga_info.colormap_type != 0) pixel=image->colormap[(ssize_t) ConstrainColormapIndex(image, 1UL*index)]; else { pixel.red=ScaleCharToQuantum((unsigned char) index); pixel.green=ScaleCharToQuantum((unsigned char) index); pixel.blue=ScaleCharToQuantum((unsigned char) index); } break; } case 15: case 16: { QuantumAny range; /* 5 bits each of RGB; */ if (ReadBlob(image,2,pixels) != 2) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); j=pixels[0]; k=pixels[1]; range=GetQuantumRange(5UL); pixel.red=ScaleAnyToQuantum(1UL*(k & 0x7c) >> 2,range); pixel.green=ScaleAnyToQuantum((1UL*(k & 0x03) << 3)+ (1UL*(j & 0xe0) >> 5),range); pixel.blue=ScaleAnyToQuantum(1UL*(j & 0x1f),range); if (image->matte != MagickFalse) pixel.opacity=(k & 0x80) == 0 ? (Quantum) TransparentOpacity : (Quantum) OpaqueOpacity; if (image->storage_class == PseudoClass) index=ConstrainColormapIndex(image,((size_t) k << 8)+j); break; } case 24: { /* BGR pixels. */ if (ReadBlob(image,3,pixels) != 3) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); pixel.blue=ScaleCharToQuantum(pixels[0]); pixel.green=ScaleCharToQuantum(pixels[1]); pixel.red=ScaleCharToQuantum(pixels[2]); break; } case 32: { /* BGRA pixels. */ if (ReadBlob(image,4,pixels) != 4) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); pixel.blue=ScaleCharToQuantum(pixels[0]); pixel.green=ScaleCharToQuantum(pixels[1]); pixel.red=ScaleCharToQuantum(pixels[2]); pixel.opacity=(Quantum) (QuantumRange-ScaleCharToQuantum( pixels[3])); break; } } if (status == MagickFalse) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); if (image->storage_class == PseudoClass) SetPixelIndex(indexes+x,index); SetPixelRed(q,pixel.red); SetPixelGreen(q,pixel.green); SetPixelBlue(q,pixel.blue); if (image->matte != MagickFalse) SetPixelOpacity(q,pixel.opacity); q++; } /* if (((unsigned char) (tga_info.attributes & 0xc0) >> 6) == 4) offset+=4; else */ if (((unsigned char) (tga_info.attributes & 0xc0) >> 6) == 2) offset+=2; else offset++; if (offset >= image->rows) { base++; offset=base; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (EOFBlob(image) != MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r T G A I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterTGAImage() adds properties for the TGA 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 RegisterTGAImage method is: % % size_t RegisterTGAImage(void) % */ ModuleExport size_t RegisterTGAImage(void) { MagickInfo *entry; entry=SetMagickInfo("ICB"); entry->decoder=(DecodeImageHandler *) ReadTGAImage; entry->encoder=(EncodeImageHandler *) WriteTGAImage; entry->adjoin=MagickFalse; entry->description=ConstantString("Truevision Targa image"); entry->module=ConstantString("TGA"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("TGA"); entry->decoder=(DecodeImageHandler *) ReadTGAImage; entry->encoder=(EncodeImageHandler *) WriteTGAImage; entry->adjoin=MagickFalse; entry->description=ConstantString("Truevision Targa image"); entry->module=ConstantString("TGA"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("VDA"); entry->decoder=(DecodeImageHandler *) ReadTGAImage; entry->encoder=(EncodeImageHandler *) WriteTGAImage; entry->adjoin=MagickFalse; entry->description=ConstantString("Truevision Targa image"); entry->module=ConstantString("TGA"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("VST"); entry->decoder=(DecodeImageHandler *) ReadTGAImage; entry->encoder=(EncodeImageHandler *) WriteTGAImage; entry->adjoin=MagickFalse; entry->description=ConstantString("Truevision Targa image"); entry->module=ConstantString("TGA"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r T G A I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterTGAImage() removes format registrations made by the % TGA module from the list of supported formats. % % The format of the UnregisterTGAImage method is: % % UnregisterTGAImage(void) % */ ModuleExport void UnregisterTGAImage(void) { (void) UnregisterMagickInfo("ICB"); (void) UnregisterMagickInfo("TGA"); (void) UnregisterMagickInfo("VDA"); (void) UnregisterMagickInfo("VST"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e T G A I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteTGAImage() writes a image in the Truevision Targa rasterfile % format. % % The format of the WriteTGAImage method is: % % MagickBooleanType WriteTGAImage(const ImageInfo *image_info,Image *image) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % */ static inline void WriteTGAPixel(Image *image,TGAImageType image_type, const IndexPacket *indexes,const PixelPacket *p,const QuantumAny range, const double midpoint) { if (image_type == TGAColormap || image_type == TGARLEColormap) (void) WriteBlobByte(image,(unsigned char) GetPixelIndex(indexes)); else { if (image_type == TGAMonochrome || image_type == TGARLEMonochrome) (void) WriteBlobByte(image,ScaleQuantumToChar(ClampToQuantum( GetPixelLuma(image,p)))); else if (image->depth == 5) { unsigned char green, value; green=(unsigned char) ScaleQuantumToAny(GetPixelGreen(p),range); value=((unsigned char) ScaleQuantumToAny(GetPixelBlue(p),range)) | ((green & 0x07) << 5); (void) WriteBlobByte(image,value); value=(unsigned char) ((((image->matte != MagickFalse) && ((double) GetPixelOpacity(p) < midpoint)) ? 0x80 : 0) | ((unsigned char) ScaleQuantumToAny(GetPixelRed(p),range) << 2) | ((green & 0x18) >> 3)); (void) WriteBlobByte(image,value); } else { (void) WriteBlobByte(image,ScaleQuantumToChar(GetPixelBlue(p))); (void) WriteBlobByte(image,ScaleQuantumToChar(GetPixelGreen(p))); (void) WriteBlobByte(image,ScaleQuantumToChar(GetPixelRed(p))); if (image->matte != MagickFalse) (void) WriteBlobByte(image,ScaleQuantumToChar(GetPixelAlpha(p))); } } } static MagickBooleanType WriteTGAImage(const ImageInfo *image_info,Image *image) { CompressionType compression; const char *value; const double midpoint = QuantumRange/2.0; MagickBooleanType status; QuantumAny range; register const IndexPacket *indexes; register const PixelPacket *p; register ssize_t x; register ssize_t i; register unsigned char *q; ssize_t count, y; TGAInfo tga_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); /* Initialize TGA raster file header. */ if ((image->columns > 65535L) || (image->rows > 65535L)) ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit"); (void) TransformImageColorspace(image,sRGBColorspace); compression=image->compression; if (image_info->compression != UndefinedCompression) compression=image_info->compression; range=GetQuantumRange(5UL); tga_info.id_length=0; value=GetImageProperty(image,"comment"); if (value != (const char *) NULL) tga_info.id_length=(unsigned char) MagickMin(strlen(value),255); tga_info.colormap_type=0; tga_info.colormap_index=0; tga_info.colormap_length=0; tga_info.colormap_size=0; tga_info.x_origin=0; tga_info.y_origin=0; tga_info.width=(unsigned short) image->columns; tga_info.height=(unsigned short) image->rows; tga_info.bits_per_pixel=8; tga_info.attributes=0; if ((image_info->type != TrueColorType) && (image_info->type != TrueColorMatteType) && (image_info->type != PaletteType) && (image->matte == MagickFalse) && (SetImageGray(image,&image->exception) != MagickFalse)) tga_info.image_type=compression == RLECompression ? TGARLEMonochrome : TGAMonochrome; else if ((image->storage_class == DirectClass) || (image->colors > 256)) { /* Full color TGA raster. */ tga_info.image_type=compression == RLECompression ? TGARLERGB : TGARGB; if (image_info->depth == 5) { tga_info.bits_per_pixel=16; if (image->matte != MagickFalse) tga_info.attributes=1; /* # of alpha bits */ } else { tga_info.bits_per_pixel=24; if (image->matte != MagickFalse) { tga_info.bits_per_pixel=32; tga_info.attributes=8; /* # of alpha bits */ } } } else { /* Colormapped TGA raster. */ tga_info.image_type=compression == RLECompression ? TGARLEColormap : TGAColormap; tga_info.colormap_type=1; tga_info.colormap_length=(unsigned short) image->colors; if (image_info->depth == 5) tga_info.colormap_size=16; else tga_info.colormap_size=24; } value=GetImageArtifact(image,"tga:image-origin"); if (value != (const char *) NULL) { OrientationType origin; origin=(OrientationType) ParseCommandOption(MagickOrientationOptions, MagickFalse,value); if (origin == BottomRightOrientation || origin == TopRightOrientation) tga_info.attributes|=(1UL << 4); if (origin == TopLeftOrientation || origin == TopRightOrientation) tga_info.attributes|=(1UL << 5); } /* Write TGA header. */ (void) WriteBlobByte(image,tga_info.id_length); (void) WriteBlobByte(image,tga_info.colormap_type); (void) WriteBlobByte(image,(unsigned char) tga_info.image_type); (void) WriteBlobLSBShort(image,tga_info.colormap_index); (void) WriteBlobLSBShort(image,tga_info.colormap_length); (void) WriteBlobByte(image,tga_info.colormap_size); (void) WriteBlobLSBShort(image,tga_info.x_origin); (void) WriteBlobLSBShort(image,tga_info.y_origin); (void) WriteBlobLSBShort(image,tga_info.width); (void) WriteBlobLSBShort(image,tga_info.height); (void) WriteBlobByte(image,tga_info.bits_per_pixel); (void) WriteBlobByte(image,tga_info.attributes); if (tga_info.id_length != 0) (void) WriteBlob(image,tga_info.id_length,(unsigned char *) value); if (tga_info.colormap_type != 0) { unsigned char green, *targa_colormap; /* Dump colormap to file (blue, green, red byte order). */ targa_colormap=(unsigned char *) AcquireQuantumMemory((size_t) tga_info.colormap_length,(tga_info.colormap_size/8)*sizeof( *targa_colormap)); if (targa_colormap == (unsigned char *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); q=targa_colormap; for (i=0; i < (ssize_t) image->colors; i++) { if (image_info->depth == 5) { green=(unsigned char) ScaleQuantumToAny(image->colormap[i].green, range); *q++=((unsigned char) ScaleQuantumToAny(image->colormap[i].blue, range)) | ((green & 0x07) << 5); *q++=(((image->matte != MagickFalse) && ( (double) image->colormap[i].opacity < midpoint)) ? 0x80 : 0) | ((unsigned char) ScaleQuantumToAny(image->colormap[i].red, range) << 2) | ((green & 0x18) >> 3); } else { *q++=ScaleQuantumToChar(image->colormap[i].blue); *q++=ScaleQuantumToChar(image->colormap[i].green); *q++=ScaleQuantumToChar(image->colormap[i].red); } } (void) WriteBlob(image,(size_t) ((tga_info.colormap_size/8)* tga_info.colormap_length),targa_colormap); targa_colormap=(unsigned char *) RelinquishMagickMemory(targa_colormap); } /* Convert MIFF to TGA raster pixels. */ for (y=(ssize_t) (image->rows-1); y >= 0; y--) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); if (compression == RLECompression) { x=0; count=0; while (x < (ssize_t) image->columns) { i=1; while ((i < 128) && (count + i < 128) && ((x + i) < (ssize_t) image->columns)) { if (tga_info.image_type == TGARLEColormap) { if (GetPixelIndex(indexes+i) != GetPixelIndex(indexes+(i-1))) break; } else if (tga_info.image_type == TGARLEMonochrome) { if (GetPixelLuma(image,p+i) != GetPixelLuma(image,p+(i-1))) break; } else { if ((GetPixelBlue(p+i) != GetPixelBlue(p+(i-1))) || (GetPixelGreen(p+i) != GetPixelGreen(p+(i-1))) || (GetPixelRed(p+i) != GetPixelRed(p+(i-1)))) break; if ((image->matte != MagickFalse) && (GetPixelAlpha(p+i) != GetPixelAlpha(p+(i-1)))) break; } i++; } if (i < 3) { count+=i; p+=i; indexes+=i; } if ((i >= 3) || (count == 128) || ((x + i) == (ssize_t) image->columns)) { if (count > 0) { (void) WriteBlobByte(image,(unsigned char) (--count)); while (count >= 0) { WriteTGAPixel(image,tga_info.image_type,indexes-(count+1), p-(count+1),range,midpoint); count--; } count=0; } } if (i >= 3) { (void) WriteBlobByte(image,(unsigned char) ((i-1) | 0x80)); WriteTGAPixel(image,tga_info.image_type,indexes,p,range,midpoint); p+=i; indexes+=i; } x+=i; } } else { for (x=0; x < (ssize_t) image->columns; x++) WriteTGAPixel(image,tga_info.image_type,indexes+x,p++,range,midpoint); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } (void) CloseBlob(image); return(MagickTrue); }
./CrossVul/dataset_final_sorted/CWE-20/c/bad_3195_0
crossvul-cpp_data_bad_5844_3
/* * INET An implementation of the TCP/IP protocol suite for the LINUX * operating system. INET is implemented using the BSD Socket * interface as the means of communication with the user level. * * The User Datagram Protocol (UDP). * * Authors: Ross Biro * Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG> * Arnt Gulbrandsen, <agulbra@nvg.unit.no> * Alan Cox, <alan@lxorguk.ukuu.org.uk> * Hirokazu Takahashi, <taka@valinux.co.jp> * * Fixes: * Alan Cox : verify_area() calls * Alan Cox : stopped close while in use off icmp * messages. Not a fix but a botch that * for udp at least is 'valid'. * Alan Cox : Fixed icmp handling properly * Alan Cox : Correct error for oversized datagrams * Alan Cox : Tidied select() semantics. * Alan Cox : udp_err() fixed properly, also now * select and read wake correctly on errors * Alan Cox : udp_send verify_area moved to avoid mem leak * Alan Cox : UDP can count its memory * Alan Cox : send to an unknown connection causes * an ECONNREFUSED off the icmp, but * does NOT close. * Alan Cox : Switched to new sk_buff handlers. No more backlog! * Alan Cox : Using generic datagram code. Even smaller and the PEEK * bug no longer crashes it. * Fred Van Kempen : Net2e support for sk->broadcast. * Alan Cox : Uses skb_free_datagram * Alan Cox : Added get/set sockopt support. * Alan Cox : Broadcasting without option set returns EACCES. * Alan Cox : No wakeup calls. Instead we now use the callbacks. * Alan Cox : Use ip_tos and ip_ttl * Alan Cox : SNMP Mibs * Alan Cox : MSG_DONTROUTE, and 0.0.0.0 support. * Matt Dillon : UDP length checks. * Alan Cox : Smarter af_inet used properly. * Alan Cox : Use new kernel side addressing. * Alan Cox : Incorrect return on truncated datagram receive. * Arnt Gulbrandsen : New udp_send and stuff * Alan Cox : Cache last socket * Alan Cox : Route cache * Jon Peatfield : Minor efficiency fix to sendto(). * Mike Shaver : RFC1122 checks. * Alan Cox : Nonblocking error fix. * Willy Konynenberg : Transparent proxying support. * Mike McLagan : Routing by source * David S. Miller : New socket lookup architecture. * Last socket cache retained as it * does have a high hit rate. * Olaf Kirch : Don't linearise iovec on sendmsg. * Andi Kleen : Some cleanups, cache destination entry * for connect. * Vitaly E. Lavrov : Transparent proxy revived after year coma. * Melvin Smith : Check msg_name not msg_namelen in sendto(), * return ENOTCONN for unconnected sockets (POSIX) * Janos Farkas : don't deliver multi/broadcasts to a different * bound-to-device socket * Hirokazu Takahashi : HW checksumming for outgoing UDP * datagrams. * Hirokazu Takahashi : sendfile() on UDP works now. * Arnaldo C. Melo : convert /proc/net/udp to seq_file * YOSHIFUJI Hideaki @USAGI and: Support IPV6_V6ONLY socket option, which * Alexey Kuznetsov: allow both IPv4 and IPv6 sockets to bind * a single port at the same time. * Derek Atkins <derek@ihtfp.com>: Add Encapulation Support * James Chapman : Add L2TP encapsulation type. * * * 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. */ #define pr_fmt(fmt) "UDP: " fmt #include <asm/uaccess.h> #include <asm/ioctls.h> #include <linux/bootmem.h> #include <linux/highmem.h> #include <linux/swap.h> #include <linux/types.h> #include <linux/fcntl.h> #include <linux/module.h> #include <linux/socket.h> #include <linux/sockios.h> #include <linux/igmp.h> #include <linux/in.h> #include <linux/errno.h> #include <linux/timer.h> #include <linux/mm.h> #include <linux/inet.h> #include <linux/netdevice.h> #include <linux/slab.h> #include <net/tcp_states.h> #include <linux/skbuff.h> #include <linux/proc_fs.h> #include <linux/seq_file.h> #include <net/net_namespace.h> #include <net/icmp.h> #include <net/inet_hashtables.h> #include <net/route.h> #include <net/checksum.h> #include <net/xfrm.h> #include <trace/events/udp.h> #include <linux/static_key.h> #include <trace/events/skb.h> #include <net/busy_poll.h> #include "udp_impl.h" struct udp_table udp_table __read_mostly; EXPORT_SYMBOL(udp_table); long sysctl_udp_mem[3] __read_mostly; EXPORT_SYMBOL(sysctl_udp_mem); int sysctl_udp_rmem_min __read_mostly; EXPORT_SYMBOL(sysctl_udp_rmem_min); int sysctl_udp_wmem_min __read_mostly; EXPORT_SYMBOL(sysctl_udp_wmem_min); atomic_long_t udp_memory_allocated; EXPORT_SYMBOL(udp_memory_allocated); #define MAX_UDP_PORTS 65536 #define PORTS_PER_CHAIN (MAX_UDP_PORTS / UDP_HTABLE_SIZE_MIN) static int udp_lib_lport_inuse(struct net *net, __u16 num, const struct udp_hslot *hslot, unsigned long *bitmap, struct sock *sk, int (*saddr_comp)(const struct sock *sk1, const struct sock *sk2), unsigned int log) { struct sock *sk2; struct hlist_nulls_node *node; kuid_t uid = sock_i_uid(sk); sk_nulls_for_each(sk2, node, &hslot->head) if (net_eq(sock_net(sk2), net) && sk2 != sk && (bitmap || udp_sk(sk2)->udp_port_hash == num) && (!sk2->sk_reuse || !sk->sk_reuse) && (!sk2->sk_bound_dev_if || !sk->sk_bound_dev_if || sk2->sk_bound_dev_if == sk->sk_bound_dev_if) && (!sk2->sk_reuseport || !sk->sk_reuseport || !uid_eq(uid, sock_i_uid(sk2))) && (*saddr_comp)(sk, sk2)) { if (bitmap) __set_bit(udp_sk(sk2)->udp_port_hash >> log, bitmap); else return 1; } return 0; } /* * Note: we still hold spinlock of primary hash chain, so no other writer * can insert/delete a socket with local_port == num */ static int udp_lib_lport_inuse2(struct net *net, __u16 num, struct udp_hslot *hslot2, struct sock *sk, int (*saddr_comp)(const struct sock *sk1, const struct sock *sk2)) { struct sock *sk2; struct hlist_nulls_node *node; kuid_t uid = sock_i_uid(sk); int res = 0; spin_lock(&hslot2->lock); udp_portaddr_for_each_entry(sk2, node, &hslot2->head) if (net_eq(sock_net(sk2), net) && sk2 != sk && (udp_sk(sk2)->udp_port_hash == num) && (!sk2->sk_reuse || !sk->sk_reuse) && (!sk2->sk_bound_dev_if || !sk->sk_bound_dev_if || sk2->sk_bound_dev_if == sk->sk_bound_dev_if) && (!sk2->sk_reuseport || !sk->sk_reuseport || !uid_eq(uid, sock_i_uid(sk2))) && (*saddr_comp)(sk, sk2)) { res = 1; break; } spin_unlock(&hslot2->lock); return res; } /** * udp_lib_get_port - UDP/-Lite port lookup for IPv4 and IPv6 * * @sk: socket struct in question * @snum: port number to look up * @saddr_comp: AF-dependent comparison of bound local IP addresses * @hash2_nulladdr: AF-dependent hash value in secondary hash chains, * with NULL address */ int udp_lib_get_port(struct sock *sk, unsigned short snum, int (*saddr_comp)(const struct sock *sk1, const struct sock *sk2), unsigned int hash2_nulladdr) { struct udp_hslot *hslot, *hslot2; struct udp_table *udptable = sk->sk_prot->h.udp_table; int error = 1; struct net *net = sock_net(sk); if (!snum) { int low, high, remaining; unsigned int rand; unsigned short first, last; DECLARE_BITMAP(bitmap, PORTS_PER_CHAIN); inet_get_local_port_range(net, &low, &high); remaining = (high - low) + 1; rand = net_random(); first = (((u64)rand * remaining) >> 32) + low; /* * force rand to be an odd multiple of UDP_HTABLE_SIZE */ rand = (rand | 1) * (udptable->mask + 1); last = first + udptable->mask + 1; do { hslot = udp_hashslot(udptable, net, first); bitmap_zero(bitmap, PORTS_PER_CHAIN); spin_lock_bh(&hslot->lock); udp_lib_lport_inuse(net, snum, hslot, bitmap, sk, saddr_comp, udptable->log); snum = first; /* * Iterate on all possible values of snum for this hash. * Using steps of an odd multiple of UDP_HTABLE_SIZE * give us randomization and full range coverage. */ do { if (low <= snum && snum <= high && !test_bit(snum >> udptable->log, bitmap) && !inet_is_reserved_local_port(snum)) goto found; snum += rand; } while (snum != first); spin_unlock_bh(&hslot->lock); } while (++first != last); goto fail; } else { hslot = udp_hashslot(udptable, net, snum); spin_lock_bh(&hslot->lock); if (hslot->count > 10) { int exist; unsigned int slot2 = udp_sk(sk)->udp_portaddr_hash ^ snum; slot2 &= udptable->mask; hash2_nulladdr &= udptable->mask; hslot2 = udp_hashslot2(udptable, slot2); if (hslot->count < hslot2->count) goto scan_primary_hash; exist = udp_lib_lport_inuse2(net, snum, hslot2, sk, saddr_comp); if (!exist && (hash2_nulladdr != slot2)) { hslot2 = udp_hashslot2(udptable, hash2_nulladdr); exist = udp_lib_lport_inuse2(net, snum, hslot2, sk, saddr_comp); } if (exist) goto fail_unlock; else goto found; } scan_primary_hash: if (udp_lib_lport_inuse(net, snum, hslot, NULL, sk, saddr_comp, 0)) goto fail_unlock; } found: inet_sk(sk)->inet_num = snum; udp_sk(sk)->udp_port_hash = snum; udp_sk(sk)->udp_portaddr_hash ^= snum; if (sk_unhashed(sk)) { sk_nulls_add_node_rcu(sk, &hslot->head); hslot->count++; sock_prot_inuse_add(sock_net(sk), sk->sk_prot, 1); hslot2 = udp_hashslot2(udptable, udp_sk(sk)->udp_portaddr_hash); spin_lock(&hslot2->lock); hlist_nulls_add_head_rcu(&udp_sk(sk)->udp_portaddr_node, &hslot2->head); hslot2->count++; spin_unlock(&hslot2->lock); } error = 0; fail_unlock: spin_unlock_bh(&hslot->lock); fail: return error; } EXPORT_SYMBOL(udp_lib_get_port); static int ipv4_rcv_saddr_equal(const struct sock *sk1, const struct sock *sk2) { struct inet_sock *inet1 = inet_sk(sk1), *inet2 = inet_sk(sk2); return (!ipv6_only_sock(sk2) && (!inet1->inet_rcv_saddr || !inet2->inet_rcv_saddr || inet1->inet_rcv_saddr == inet2->inet_rcv_saddr)); } static unsigned int udp4_portaddr_hash(struct net *net, __be32 saddr, unsigned int port) { return jhash_1word((__force u32)saddr, net_hash_mix(net)) ^ port; } int udp_v4_get_port(struct sock *sk, unsigned short snum) { unsigned int hash2_nulladdr = udp4_portaddr_hash(sock_net(sk), htonl(INADDR_ANY), snum); unsigned int hash2_partial = udp4_portaddr_hash(sock_net(sk), inet_sk(sk)->inet_rcv_saddr, 0); /* precompute partial secondary hash */ udp_sk(sk)->udp_portaddr_hash = hash2_partial; return udp_lib_get_port(sk, snum, ipv4_rcv_saddr_equal, hash2_nulladdr); } static inline int compute_score(struct sock *sk, struct net *net, __be32 saddr, unsigned short hnum, __be16 sport, __be32 daddr, __be16 dport, int dif) { int score = -1; if (net_eq(sock_net(sk), net) && udp_sk(sk)->udp_port_hash == hnum && !ipv6_only_sock(sk)) { struct inet_sock *inet = inet_sk(sk); score = (sk->sk_family == PF_INET ? 2 : 1); if (inet->inet_rcv_saddr) { if (inet->inet_rcv_saddr != daddr) return -1; score += 4; } if (inet->inet_daddr) { if (inet->inet_daddr != saddr) return -1; score += 4; } if (inet->inet_dport) { if (inet->inet_dport != sport) return -1; score += 4; } if (sk->sk_bound_dev_if) { if (sk->sk_bound_dev_if != dif) return -1; score += 4; } } return score; } /* * In this second variant, we check (daddr, dport) matches (inet_rcv_sadd, inet_num) */ static inline int compute_score2(struct sock *sk, struct net *net, __be32 saddr, __be16 sport, __be32 daddr, unsigned int hnum, int dif) { int score = -1; if (net_eq(sock_net(sk), net) && !ipv6_only_sock(sk)) { struct inet_sock *inet = inet_sk(sk); if (inet->inet_rcv_saddr != daddr) return -1; if (inet->inet_num != hnum) return -1; score = (sk->sk_family == PF_INET ? 2 : 1); if (inet->inet_daddr) { if (inet->inet_daddr != saddr) return -1; score += 4; } if (inet->inet_dport) { if (inet->inet_dport != sport) return -1; score += 4; } if (sk->sk_bound_dev_if) { if (sk->sk_bound_dev_if != dif) return -1; score += 4; } } return score; } static unsigned int udp_ehashfn(struct net *net, const __be32 laddr, const __u16 lport, const __be32 faddr, const __be16 fport) { static u32 udp_ehash_secret __read_mostly; net_get_random_once(&udp_ehash_secret, sizeof(udp_ehash_secret)); return __inet_ehashfn(laddr, lport, faddr, fport, udp_ehash_secret + net_hash_mix(net)); } /* called with read_rcu_lock() */ static struct sock *udp4_lib_lookup2(struct net *net, __be32 saddr, __be16 sport, __be32 daddr, unsigned int hnum, int dif, struct udp_hslot *hslot2, unsigned int slot2) { struct sock *sk, *result; struct hlist_nulls_node *node; int score, badness, matches = 0, reuseport = 0; u32 hash = 0; begin: result = NULL; badness = 0; udp_portaddr_for_each_entry_rcu(sk, node, &hslot2->head) { score = compute_score2(sk, net, saddr, sport, daddr, hnum, dif); if (score > badness) { result = sk; badness = score; reuseport = sk->sk_reuseport; if (reuseport) { hash = udp_ehashfn(net, daddr, hnum, saddr, sport); matches = 1; } } else if (score == badness && reuseport) { matches++; if (((u64)hash * matches) >> 32 == 0) result = sk; hash = next_pseudo_random32(hash); } } /* * if the nulls value we got at the end of this lookup is * not the expected one, we must restart lookup. * We probably met an item that was moved to another chain. */ if (get_nulls_value(node) != slot2) goto begin; if (result) { if (unlikely(!atomic_inc_not_zero_hint(&result->sk_refcnt, 2))) result = NULL; else if (unlikely(compute_score2(result, net, saddr, sport, daddr, hnum, dif) < badness)) { sock_put(result); goto begin; } } return result; } /* UDP is nearly always wildcards out the wazoo, it makes no sense to try * harder than this. -DaveM */ struct sock *__udp4_lib_lookup(struct net *net, __be32 saddr, __be16 sport, __be32 daddr, __be16 dport, int dif, struct udp_table *udptable) { struct sock *sk, *result; struct hlist_nulls_node *node; unsigned short hnum = ntohs(dport); unsigned int hash2, slot2, slot = udp_hashfn(net, hnum, udptable->mask); struct udp_hslot *hslot2, *hslot = &udptable->hash[slot]; int score, badness, matches = 0, reuseport = 0; u32 hash = 0; rcu_read_lock(); if (hslot->count > 10) { hash2 = udp4_portaddr_hash(net, daddr, hnum); slot2 = hash2 & udptable->mask; hslot2 = &udptable->hash2[slot2]; if (hslot->count < hslot2->count) goto begin; result = udp4_lib_lookup2(net, saddr, sport, daddr, hnum, dif, hslot2, slot2); if (!result) { hash2 = udp4_portaddr_hash(net, htonl(INADDR_ANY), hnum); slot2 = hash2 & udptable->mask; hslot2 = &udptable->hash2[slot2]; if (hslot->count < hslot2->count) goto begin; result = udp4_lib_lookup2(net, saddr, sport, htonl(INADDR_ANY), hnum, dif, hslot2, slot2); } rcu_read_unlock(); return result; } begin: result = NULL; badness = 0; sk_nulls_for_each_rcu(sk, node, &hslot->head) { score = compute_score(sk, net, saddr, hnum, sport, daddr, dport, dif); if (score > badness) { result = sk; badness = score; reuseport = sk->sk_reuseport; if (reuseport) { hash = udp_ehashfn(net, daddr, hnum, saddr, sport); matches = 1; } } else if (score == badness && reuseport) { matches++; if (((u64)hash * matches) >> 32 == 0) result = sk; hash = next_pseudo_random32(hash); } } /* * if the nulls value we got at the end of this lookup is * not the expected one, we must restart lookup. * We probably met an item that was moved to another chain. */ if (get_nulls_value(node) != slot) goto begin; if (result) { if (unlikely(!atomic_inc_not_zero_hint(&result->sk_refcnt, 2))) result = NULL; else if (unlikely(compute_score(result, net, saddr, hnum, sport, daddr, dport, dif) < badness)) { sock_put(result); goto begin; } } rcu_read_unlock(); return result; } EXPORT_SYMBOL_GPL(__udp4_lib_lookup); static inline struct sock *__udp4_lib_lookup_skb(struct sk_buff *skb, __be16 sport, __be16 dport, struct udp_table *udptable) { struct sock *sk; const struct iphdr *iph = ip_hdr(skb); if (unlikely(sk = skb_steal_sock(skb))) return sk; else return __udp4_lib_lookup(dev_net(skb_dst(skb)->dev), iph->saddr, sport, iph->daddr, dport, inet_iif(skb), udptable); } struct sock *udp4_lib_lookup(struct net *net, __be32 saddr, __be16 sport, __be32 daddr, __be16 dport, int dif) { return __udp4_lib_lookup(net, saddr, sport, daddr, dport, dif, &udp_table); } EXPORT_SYMBOL_GPL(udp4_lib_lookup); static inline bool __udp_is_mcast_sock(struct net *net, struct sock *sk, __be16 loc_port, __be32 loc_addr, __be16 rmt_port, __be32 rmt_addr, int dif, unsigned short hnum) { struct inet_sock *inet = inet_sk(sk); if (!net_eq(sock_net(sk), net) || udp_sk(sk)->udp_port_hash != hnum || (inet->inet_daddr && inet->inet_daddr != rmt_addr) || (inet->inet_dport != rmt_port && inet->inet_dport) || (inet->inet_rcv_saddr && inet->inet_rcv_saddr != loc_addr) || ipv6_only_sock(sk) || (sk->sk_bound_dev_if && sk->sk_bound_dev_if != dif)) return false; if (!ip_mc_sf_allow(sk, loc_addr, rmt_addr, dif)) return false; return true; } static inline struct sock *udp_v4_mcast_next(struct net *net, struct sock *sk, __be16 loc_port, __be32 loc_addr, __be16 rmt_port, __be32 rmt_addr, int dif) { struct hlist_nulls_node *node; struct sock *s = sk; unsigned short hnum = ntohs(loc_port); sk_nulls_for_each_from(s, node) { if (__udp_is_mcast_sock(net, s, loc_port, loc_addr, rmt_port, rmt_addr, dif, hnum)) goto found; } s = NULL; found: return s; } /* * This routine is called by the ICMP module when it gets some * sort of error condition. If err < 0 then the socket should * be closed and the error returned to the user. If err > 0 * it's just the icmp type << 8 | icmp code. * Header points to the ip header of the error packet. We move * on past this. Then (as it used to claim before adjustment) * header points to the first 8 bytes of the udp header. We need * to find the appropriate port. */ void __udp4_lib_err(struct sk_buff *skb, u32 info, struct udp_table *udptable) { struct inet_sock *inet; const struct iphdr *iph = (const struct iphdr *)skb->data; struct udphdr *uh = (struct udphdr *)(skb->data+(iph->ihl<<2)); const int type = icmp_hdr(skb)->type; const int code = icmp_hdr(skb)->code; struct sock *sk; int harderr; int err; struct net *net = dev_net(skb->dev); sk = __udp4_lib_lookup(net, iph->daddr, uh->dest, iph->saddr, uh->source, skb->dev->ifindex, udptable); if (sk == NULL) { ICMP_INC_STATS_BH(net, ICMP_MIB_INERRORS); return; /* No socket for error */ } err = 0; harderr = 0; inet = inet_sk(sk); switch (type) { default: case ICMP_TIME_EXCEEDED: err = EHOSTUNREACH; break; case ICMP_SOURCE_QUENCH: goto out; case ICMP_PARAMETERPROB: err = EPROTO; harderr = 1; break; case ICMP_DEST_UNREACH: if (code == ICMP_FRAG_NEEDED) { /* Path MTU discovery */ ipv4_sk_update_pmtu(skb, sk, info); if (inet->pmtudisc != IP_PMTUDISC_DONT) { err = EMSGSIZE; harderr = 1; break; } goto out; } err = EHOSTUNREACH; if (code <= NR_ICMP_UNREACH) { harderr = icmp_err_convert[code].fatal; err = icmp_err_convert[code].errno; } break; case ICMP_REDIRECT: ipv4_sk_redirect(skb, sk); goto out; } /* * RFC1122: OK. Passes ICMP errors back to application, as per * 4.1.3.3. */ if (!inet->recverr) { if (!harderr || sk->sk_state != TCP_ESTABLISHED) goto out; } else ip_icmp_error(sk, skb, err, uh->dest, info, (u8 *)(uh+1)); sk->sk_err = err; sk->sk_error_report(sk); out: sock_put(sk); } void udp_err(struct sk_buff *skb, u32 info) { __udp4_lib_err(skb, info, &udp_table); } /* * Throw away all pending data and cancel the corking. Socket is locked. */ void udp_flush_pending_frames(struct sock *sk) { struct udp_sock *up = udp_sk(sk); if (up->pending) { up->len = 0; up->pending = 0; ip_flush_pending_frames(sk); } } EXPORT_SYMBOL(udp_flush_pending_frames); /** * udp4_hwcsum - handle outgoing HW checksumming * @skb: sk_buff containing the filled-in UDP header * (checksum field must be zeroed out) * @src: source IP address * @dst: destination IP address */ void udp4_hwcsum(struct sk_buff *skb, __be32 src, __be32 dst) { struct udphdr *uh = udp_hdr(skb); struct sk_buff *frags = skb_shinfo(skb)->frag_list; int offset = skb_transport_offset(skb); int len = skb->len - offset; int hlen = len; __wsum csum = 0; if (!frags) { /* * Only one fragment on the socket. */ skb->csum_start = skb_transport_header(skb) - skb->head; skb->csum_offset = offsetof(struct udphdr, check); uh->check = ~csum_tcpudp_magic(src, dst, len, IPPROTO_UDP, 0); } else { /* * HW-checksum won't work as there are two or more * fragments on the socket so that all csums of sk_buffs * should be together */ do { csum = csum_add(csum, frags->csum); hlen -= frags->len; } while ((frags = frags->next)); csum = skb_checksum(skb, offset, hlen, csum); skb->ip_summed = CHECKSUM_NONE; uh->check = csum_tcpudp_magic(src, dst, len, IPPROTO_UDP, csum); if (uh->check == 0) uh->check = CSUM_MANGLED_0; } } EXPORT_SYMBOL_GPL(udp4_hwcsum); static int udp_send_skb(struct sk_buff *skb, struct flowi4 *fl4) { struct sock *sk = skb->sk; struct inet_sock *inet = inet_sk(sk); struct udphdr *uh; int err = 0; int is_udplite = IS_UDPLITE(sk); int offset = skb_transport_offset(skb); int len = skb->len - offset; __wsum csum = 0; /* * Create a UDP header */ uh = udp_hdr(skb); uh->source = inet->inet_sport; uh->dest = fl4->fl4_dport; uh->len = htons(len); uh->check = 0; if (is_udplite) /* UDP-Lite */ csum = udplite_csum(skb); else if (sk->sk_no_check == UDP_CSUM_NOXMIT) { /* UDP csum disabled */ skb->ip_summed = CHECKSUM_NONE; goto send; } else if (skb->ip_summed == CHECKSUM_PARTIAL) { /* UDP hardware csum */ udp4_hwcsum(skb, fl4->saddr, fl4->daddr); goto send; } else csum = udp_csum(skb); /* add protocol-dependent pseudo-header */ uh->check = csum_tcpudp_magic(fl4->saddr, fl4->daddr, len, sk->sk_protocol, csum); if (uh->check == 0) uh->check = CSUM_MANGLED_0; send: err = ip_send_skb(sock_net(sk), skb); if (err) { if (err == -ENOBUFS && !inet->recverr) { UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_SNDBUFERRORS, is_udplite); err = 0; } } else UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_OUTDATAGRAMS, is_udplite); return err; } /* * Push out all pending data as one UDP datagram. Socket is locked. */ int udp_push_pending_frames(struct sock *sk) { struct udp_sock *up = udp_sk(sk); struct inet_sock *inet = inet_sk(sk); struct flowi4 *fl4 = &inet->cork.fl.u.ip4; struct sk_buff *skb; int err = 0; skb = ip_finish_skb(sk, fl4); if (!skb) goto out; err = udp_send_skb(skb, fl4); out: up->len = 0; up->pending = 0; return err; } EXPORT_SYMBOL(udp_push_pending_frames); int udp_sendmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg, size_t len) { struct inet_sock *inet = inet_sk(sk); struct udp_sock *up = udp_sk(sk); struct flowi4 fl4_stack; struct flowi4 *fl4; int ulen = len; struct ipcm_cookie ipc; struct rtable *rt = NULL; int free = 0; int connected = 0; __be32 daddr, faddr, saddr; __be16 dport; u8 tos; int err, is_udplite = IS_UDPLITE(sk); int corkreq = up->corkflag || msg->msg_flags&MSG_MORE; int (*getfrag)(void *, char *, int, int, int, struct sk_buff *); struct sk_buff *skb; struct ip_options_data opt_copy; if (len > 0xFFFF) return -EMSGSIZE; /* * Check the flags. */ if (msg->msg_flags & MSG_OOB) /* Mirror BSD error message compatibility */ return -EOPNOTSUPP; ipc.opt = NULL; ipc.tx_flags = 0; ipc.ttl = 0; ipc.tos = -1; getfrag = is_udplite ? udplite_getfrag : ip_generic_getfrag; fl4 = &inet->cork.fl.u.ip4; if (up->pending) { /* * There are pending frames. * The socket lock must be held while it's corked. */ lock_sock(sk); if (likely(up->pending)) { if (unlikely(up->pending != AF_INET)) { release_sock(sk); return -EINVAL; } goto do_append_data; } release_sock(sk); } ulen += sizeof(struct udphdr); /* * Get and verify the address. */ if (msg->msg_name) { struct sockaddr_in *usin = (struct sockaddr_in *)msg->msg_name; if (msg->msg_namelen < sizeof(*usin)) return -EINVAL; if (usin->sin_family != AF_INET) { if (usin->sin_family != AF_UNSPEC) return -EAFNOSUPPORT; } daddr = usin->sin_addr.s_addr; dport = usin->sin_port; if (dport == 0) return -EINVAL; } else { if (sk->sk_state != TCP_ESTABLISHED) return -EDESTADDRREQ; daddr = inet->inet_daddr; dport = inet->inet_dport; /* Open fast path for connected socket. Route will not be used, if at least one option is set. */ connected = 1; } ipc.addr = inet->inet_saddr; ipc.oif = sk->sk_bound_dev_if; sock_tx_timestamp(sk, &ipc.tx_flags); if (msg->msg_controllen) { err = ip_cmsg_send(sock_net(sk), msg, &ipc); if (err) return err; if (ipc.opt) free = 1; connected = 0; } if (!ipc.opt) { struct ip_options_rcu *inet_opt; rcu_read_lock(); inet_opt = rcu_dereference(inet->inet_opt); if (inet_opt) { memcpy(&opt_copy, inet_opt, sizeof(*inet_opt) + inet_opt->opt.optlen); ipc.opt = &opt_copy.opt; } rcu_read_unlock(); } saddr = ipc.addr; ipc.addr = faddr = daddr; if (ipc.opt && ipc.opt->opt.srr) { if (!daddr) return -EINVAL; faddr = ipc.opt->opt.faddr; connected = 0; } tos = get_rttos(&ipc, inet); if (sock_flag(sk, SOCK_LOCALROUTE) || (msg->msg_flags & MSG_DONTROUTE) || (ipc.opt && ipc.opt->opt.is_strictroute)) { tos |= RTO_ONLINK; connected = 0; } if (ipv4_is_multicast(daddr)) { if (!ipc.oif) ipc.oif = inet->mc_index; if (!saddr) saddr = inet->mc_addr; connected = 0; } else if (!ipc.oif) ipc.oif = inet->uc_index; if (connected) rt = (struct rtable *)sk_dst_check(sk, 0); if (rt == NULL) { struct net *net = sock_net(sk); fl4 = &fl4_stack; flowi4_init_output(fl4, ipc.oif, sk->sk_mark, tos, RT_SCOPE_UNIVERSE, sk->sk_protocol, inet_sk_flowi_flags(sk)|FLOWI_FLAG_CAN_SLEEP, faddr, saddr, dport, inet->inet_sport); security_sk_classify_flow(sk, flowi4_to_flowi(fl4)); rt = ip_route_output_flow(net, fl4, sk); if (IS_ERR(rt)) { err = PTR_ERR(rt); rt = NULL; if (err == -ENETUNREACH) IP_INC_STATS_BH(net, IPSTATS_MIB_OUTNOROUTES); goto out; } err = -EACCES; if ((rt->rt_flags & RTCF_BROADCAST) && !sock_flag(sk, SOCK_BROADCAST)) goto out; if (connected) sk_dst_set(sk, dst_clone(&rt->dst)); } if (msg->msg_flags&MSG_CONFIRM) goto do_confirm; back_from_confirm: saddr = fl4->saddr; if (!ipc.addr) daddr = ipc.addr = fl4->daddr; /* Lockless fast path for the non-corking case. */ if (!corkreq) { skb = ip_make_skb(sk, fl4, getfrag, msg->msg_iov, ulen, sizeof(struct udphdr), &ipc, &rt, msg->msg_flags); err = PTR_ERR(skb); if (!IS_ERR_OR_NULL(skb)) err = udp_send_skb(skb, fl4); goto out; } lock_sock(sk); if (unlikely(up->pending)) { /* The socket is already corked while preparing it. */ /* ... which is an evident application bug. --ANK */ release_sock(sk); LIMIT_NETDEBUG(KERN_DEBUG pr_fmt("cork app bug 2\n")); err = -EINVAL; goto out; } /* * Now cork the socket to pend data. */ fl4 = &inet->cork.fl.u.ip4; fl4->daddr = daddr; fl4->saddr = saddr; fl4->fl4_dport = dport; fl4->fl4_sport = inet->inet_sport; up->pending = AF_INET; do_append_data: up->len += ulen; err = ip_append_data(sk, fl4, getfrag, msg->msg_iov, ulen, sizeof(struct udphdr), &ipc, &rt, corkreq ? msg->msg_flags|MSG_MORE : msg->msg_flags); if (err) udp_flush_pending_frames(sk); else if (!corkreq) err = udp_push_pending_frames(sk); else if (unlikely(skb_queue_empty(&sk->sk_write_queue))) up->pending = 0; release_sock(sk); out: ip_rt_put(rt); if (free) kfree(ipc.opt); if (!err) return len; /* * ENOBUFS = no kernel mem, SOCK_NOSPACE = no sndbuf space. Reporting * ENOBUFS might not be good (it's not tunable per se), but otherwise * we don't have a good statistic (IpOutDiscards but it can be too many * things). We could add another new stat but at least for now that * seems like overkill. */ if (err == -ENOBUFS || test_bit(SOCK_NOSPACE, &sk->sk_socket->flags)) { UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_SNDBUFERRORS, is_udplite); } return err; do_confirm: dst_confirm(&rt->dst); if (!(msg->msg_flags&MSG_PROBE) || len) goto back_from_confirm; err = 0; goto out; } EXPORT_SYMBOL(udp_sendmsg); int udp_sendpage(struct sock *sk, struct page *page, int offset, size_t size, int flags) { struct inet_sock *inet = inet_sk(sk); struct udp_sock *up = udp_sk(sk); int ret; if (!up->pending) { struct msghdr msg = { .msg_flags = flags|MSG_MORE }; /* Call udp_sendmsg to specify destination address which * sendpage interface can't pass. * This will succeed only when the socket is connected. */ ret = udp_sendmsg(NULL, sk, &msg, 0); if (ret < 0) return ret; } lock_sock(sk); if (unlikely(!up->pending)) { release_sock(sk); LIMIT_NETDEBUG(KERN_DEBUG pr_fmt("udp cork app bug 3\n")); return -EINVAL; } ret = ip_append_page(sk, &inet->cork.fl.u.ip4, page, offset, size, flags); if (ret == -EOPNOTSUPP) { release_sock(sk); return sock_no_sendpage(sk->sk_socket, page, offset, size, flags); } if (ret < 0) { udp_flush_pending_frames(sk); goto out; } up->len += size; if (!(up->corkflag || (flags&MSG_MORE))) ret = udp_push_pending_frames(sk); if (!ret) ret = size; out: release_sock(sk); return ret; } /** * first_packet_length - return length of first packet in receive queue * @sk: socket * * Drops all bad checksum frames, until a valid one is found. * Returns the length of found skb, or 0 if none is found. */ static unsigned int first_packet_length(struct sock *sk) { struct sk_buff_head list_kill, *rcvq = &sk->sk_receive_queue; struct sk_buff *skb; unsigned int res; __skb_queue_head_init(&list_kill); spin_lock_bh(&rcvq->lock); while ((skb = skb_peek(rcvq)) != NULL && udp_lib_checksum_complete(skb)) { UDP_INC_STATS_BH(sock_net(sk), UDP_MIB_CSUMERRORS, IS_UDPLITE(sk)); UDP_INC_STATS_BH(sock_net(sk), UDP_MIB_INERRORS, IS_UDPLITE(sk)); atomic_inc(&sk->sk_drops); __skb_unlink(skb, rcvq); __skb_queue_tail(&list_kill, skb); } res = skb ? skb->len : 0; spin_unlock_bh(&rcvq->lock); if (!skb_queue_empty(&list_kill)) { bool slow = lock_sock_fast(sk); __skb_queue_purge(&list_kill); sk_mem_reclaim_partial(sk); unlock_sock_fast(sk, slow); } return res; } /* * IOCTL requests applicable to the UDP protocol */ int udp_ioctl(struct sock *sk, int cmd, unsigned long arg) { switch (cmd) { case SIOCOUTQ: { int amount = sk_wmem_alloc_get(sk); return put_user(amount, (int __user *)arg); } case SIOCINQ: { unsigned int amount = first_packet_length(sk); if (amount) /* * We will only return the amount * of this packet since that is all * that will be read. */ amount -= sizeof(struct udphdr); return put_user(amount, (int __user *)arg); } default: return -ENOIOCTLCMD; } return 0; } EXPORT_SYMBOL(udp_ioctl); /* * This should be easy, if there is something there we * return it, otherwise we block. */ int udp_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg, size_t len, int noblock, int flags, int *addr_len) { struct inet_sock *inet = inet_sk(sk); struct sockaddr_in *sin = (struct sockaddr_in *)msg->msg_name; struct sk_buff *skb; unsigned int ulen, copied; int peeked, off = 0; int err; int is_udplite = IS_UDPLITE(sk); bool slow; /* * Check any passed addresses */ if (addr_len) *addr_len = sizeof(*sin); if (flags & MSG_ERRQUEUE) return ip_recv_error(sk, msg, len); try_again: skb = __skb_recv_datagram(sk, flags | (noblock ? MSG_DONTWAIT : 0), &peeked, &off, &err); if (!skb) goto out; ulen = skb->len - sizeof(struct udphdr); copied = len; if (copied > ulen) copied = ulen; else if (copied < ulen) msg->msg_flags |= MSG_TRUNC; /* * If checksum is needed at all, try to do it while copying the * data. If the data is truncated, or if we only want a partial * coverage checksum (UDP-Lite), do it before the copy. */ if (copied < ulen || UDP_SKB_CB(skb)->partial_cov) { if (udp_lib_checksum_complete(skb)) goto csum_copy_err; } if (skb_csum_unnecessary(skb)) err = skb_copy_datagram_iovec(skb, sizeof(struct udphdr), msg->msg_iov, copied); else { err = skb_copy_and_csum_datagram_iovec(skb, sizeof(struct udphdr), msg->msg_iov); if (err == -EINVAL) goto csum_copy_err; } if (unlikely(err)) { trace_kfree_skb(skb, udp_recvmsg); if (!peeked) { atomic_inc(&sk->sk_drops); UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_INERRORS, is_udplite); } goto out_free; } if (!peeked) UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_INDATAGRAMS, is_udplite); sock_recv_ts_and_drops(msg, sk, skb); /* Copy the address. */ if (sin) { sin->sin_family = AF_INET; sin->sin_port = udp_hdr(skb)->source; sin->sin_addr.s_addr = ip_hdr(skb)->saddr; memset(sin->sin_zero, 0, sizeof(sin->sin_zero)); } if (inet->cmsg_flags) ip_cmsg_recv(msg, skb); err = copied; if (flags & MSG_TRUNC) err = ulen; out_free: skb_free_datagram_locked(sk, skb); out: return err; csum_copy_err: slow = lock_sock_fast(sk); if (!skb_kill_datagram(sk, skb, flags)) { UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_CSUMERRORS, is_udplite); UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_INERRORS, is_udplite); } unlock_sock_fast(sk, slow); if (noblock) return -EAGAIN; /* starting over for a new packet */ msg->msg_flags &= ~MSG_TRUNC; goto try_again; } int udp_disconnect(struct sock *sk, int flags) { struct inet_sock *inet = inet_sk(sk); /* * 1003.1g - break association. */ sk->sk_state = TCP_CLOSE; inet->inet_daddr = 0; inet->inet_dport = 0; sock_rps_reset_rxhash(sk); sk->sk_bound_dev_if = 0; if (!(sk->sk_userlocks & SOCK_BINDADDR_LOCK)) inet_reset_saddr(sk); if (!(sk->sk_userlocks & SOCK_BINDPORT_LOCK)) { sk->sk_prot->unhash(sk); inet->inet_sport = 0; } sk_dst_reset(sk); return 0; } EXPORT_SYMBOL(udp_disconnect); void udp_lib_unhash(struct sock *sk) { if (sk_hashed(sk)) { struct udp_table *udptable = sk->sk_prot->h.udp_table; struct udp_hslot *hslot, *hslot2; hslot = udp_hashslot(udptable, sock_net(sk), udp_sk(sk)->udp_port_hash); hslot2 = udp_hashslot2(udptable, udp_sk(sk)->udp_portaddr_hash); spin_lock_bh(&hslot->lock); if (sk_nulls_del_node_init_rcu(sk)) { hslot->count--; inet_sk(sk)->inet_num = 0; sock_prot_inuse_add(sock_net(sk), sk->sk_prot, -1); spin_lock(&hslot2->lock); hlist_nulls_del_init_rcu(&udp_sk(sk)->udp_portaddr_node); hslot2->count--; spin_unlock(&hslot2->lock); } spin_unlock_bh(&hslot->lock); } } EXPORT_SYMBOL(udp_lib_unhash); /* * inet_rcv_saddr was changed, we must rehash secondary hash */ void udp_lib_rehash(struct sock *sk, u16 newhash) { if (sk_hashed(sk)) { struct udp_table *udptable = sk->sk_prot->h.udp_table; struct udp_hslot *hslot, *hslot2, *nhslot2; hslot2 = udp_hashslot2(udptable, udp_sk(sk)->udp_portaddr_hash); nhslot2 = udp_hashslot2(udptable, newhash); udp_sk(sk)->udp_portaddr_hash = newhash; if (hslot2 != nhslot2) { hslot = udp_hashslot(udptable, sock_net(sk), udp_sk(sk)->udp_port_hash); /* we must lock primary chain too */ spin_lock_bh(&hslot->lock); spin_lock(&hslot2->lock); hlist_nulls_del_init_rcu(&udp_sk(sk)->udp_portaddr_node); hslot2->count--; spin_unlock(&hslot2->lock); spin_lock(&nhslot2->lock); hlist_nulls_add_head_rcu(&udp_sk(sk)->udp_portaddr_node, &nhslot2->head); nhslot2->count++; spin_unlock(&nhslot2->lock); spin_unlock_bh(&hslot->lock); } } } EXPORT_SYMBOL(udp_lib_rehash); static void udp_v4_rehash(struct sock *sk) { u16 new_hash = udp4_portaddr_hash(sock_net(sk), inet_sk(sk)->inet_rcv_saddr, inet_sk(sk)->inet_num); udp_lib_rehash(sk, new_hash); } static int __udp_queue_rcv_skb(struct sock *sk, struct sk_buff *skb) { int rc; if (inet_sk(sk)->inet_daddr) { sock_rps_save_rxhash(sk, skb); sk_mark_napi_id(sk, skb); } rc = sock_queue_rcv_skb(sk, skb); if (rc < 0) { int is_udplite = IS_UDPLITE(sk); /* Note that an ENOMEM error is charged twice */ if (rc == -ENOMEM) UDP_INC_STATS_BH(sock_net(sk), UDP_MIB_RCVBUFERRORS, is_udplite); UDP_INC_STATS_BH(sock_net(sk), UDP_MIB_INERRORS, is_udplite); kfree_skb(skb); trace_udp_fail_queue_rcv_skb(rc, sk); return -1; } return 0; } static struct static_key udp_encap_needed __read_mostly; void udp_encap_enable(void) { if (!static_key_enabled(&udp_encap_needed)) static_key_slow_inc(&udp_encap_needed); } EXPORT_SYMBOL(udp_encap_enable); /* returns: * -1: error * 0: success * >0: "udp encap" protocol resubmission * * Note that in the success and error cases, the skb is assumed to * have either been requeued or freed. */ int udp_queue_rcv_skb(struct sock *sk, struct sk_buff *skb) { struct udp_sock *up = udp_sk(sk); int rc; int is_udplite = IS_UDPLITE(sk); /* * Charge it to the socket, dropping if the queue is full. */ if (!xfrm4_policy_check(sk, XFRM_POLICY_IN, skb)) goto drop; nf_reset(skb); if (static_key_false(&udp_encap_needed) && up->encap_type) { int (*encap_rcv)(struct sock *sk, struct sk_buff *skb); /* * This is an encapsulation socket so pass the skb to * the socket's udp_encap_rcv() hook. Otherwise, just * fall through and pass this up the UDP socket. * up->encap_rcv() returns the following value: * =0 if skb was successfully passed to the encap * handler or was discarded by it. * >0 if skb should be passed on to UDP. * <0 if skb should be resubmitted as proto -N */ /* if we're overly short, let UDP handle it */ encap_rcv = ACCESS_ONCE(up->encap_rcv); if (skb->len > sizeof(struct udphdr) && encap_rcv != NULL) { int ret; ret = encap_rcv(sk, skb); if (ret <= 0) { UDP_INC_STATS_BH(sock_net(sk), UDP_MIB_INDATAGRAMS, is_udplite); return -ret; } } /* FALLTHROUGH -- it's a UDP Packet */ } /* * UDP-Lite specific tests, ignored on UDP sockets */ if ((is_udplite & UDPLITE_RECV_CC) && UDP_SKB_CB(skb)->partial_cov) { /* * MIB statistics other than incrementing the error count are * disabled for the following two types of errors: these depend * on the application settings, not on the functioning of the * protocol stack as such. * * RFC 3828 here recommends (sec 3.3): "There should also be a * way ... to ... at least let the receiving application block * delivery of packets with coverage values less than a value * provided by the application." */ if (up->pcrlen == 0) { /* full coverage was set */ LIMIT_NETDEBUG(KERN_WARNING "UDPLite: partial coverage %d while full coverage %d requested\n", UDP_SKB_CB(skb)->cscov, skb->len); goto drop; } /* The next case involves violating the min. coverage requested * by the receiver. This is subtle: if receiver wants x and x is * greater than the buffersize/MTU then receiver will complain * that it wants x while sender emits packets of smaller size y. * Therefore the above ...()->partial_cov statement is essential. */ if (UDP_SKB_CB(skb)->cscov < up->pcrlen) { LIMIT_NETDEBUG(KERN_WARNING "UDPLite: coverage %d too small, need min %d\n", UDP_SKB_CB(skb)->cscov, up->pcrlen); goto drop; } } if (rcu_access_pointer(sk->sk_filter) && udp_lib_checksum_complete(skb)) goto csum_error; if (sk_rcvqueues_full(sk, skb, sk->sk_rcvbuf)) goto drop; rc = 0; ipv4_pktinfo_prepare(sk, skb); bh_lock_sock(sk); if (!sock_owned_by_user(sk)) rc = __udp_queue_rcv_skb(sk, skb); else if (sk_add_backlog(sk, skb, sk->sk_rcvbuf)) { bh_unlock_sock(sk); goto drop; } bh_unlock_sock(sk); return rc; csum_error: UDP_INC_STATS_BH(sock_net(sk), UDP_MIB_CSUMERRORS, is_udplite); drop: UDP_INC_STATS_BH(sock_net(sk), UDP_MIB_INERRORS, is_udplite); atomic_inc(&sk->sk_drops); kfree_skb(skb); return -1; } static void flush_stack(struct sock **stack, unsigned int count, struct sk_buff *skb, unsigned int final) { unsigned int i; struct sk_buff *skb1 = NULL; struct sock *sk; for (i = 0; i < count; i++) { sk = stack[i]; if (likely(skb1 == NULL)) skb1 = (i == final) ? skb : skb_clone(skb, GFP_ATOMIC); if (!skb1) { atomic_inc(&sk->sk_drops); UDP_INC_STATS_BH(sock_net(sk), UDP_MIB_RCVBUFERRORS, IS_UDPLITE(sk)); UDP_INC_STATS_BH(sock_net(sk), UDP_MIB_INERRORS, IS_UDPLITE(sk)); } if (skb1 && udp_queue_rcv_skb(sk, skb1) <= 0) skb1 = NULL; } if (unlikely(skb1)) kfree_skb(skb1); } static void udp_sk_rx_dst_set(struct sock *sk, const struct sk_buff *skb) { struct dst_entry *dst = skb_dst(skb); dst_hold(dst); sk->sk_rx_dst = dst; } /* * Multicasts and broadcasts go to each listener. * * Note: called only from the BH handler context. */ static int __udp4_lib_mcast_deliver(struct net *net, struct sk_buff *skb, struct udphdr *uh, __be32 saddr, __be32 daddr, struct udp_table *udptable) { struct sock *sk, *stack[256 / sizeof(struct sock *)]; struct udp_hslot *hslot = udp_hashslot(udptable, net, ntohs(uh->dest)); int dif; unsigned int i, count = 0; spin_lock(&hslot->lock); sk = sk_nulls_head(&hslot->head); dif = skb->dev->ifindex; sk = udp_v4_mcast_next(net, sk, uh->dest, daddr, uh->source, saddr, dif); while (sk) { stack[count++] = sk; sk = udp_v4_mcast_next(net, sk_nulls_next(sk), uh->dest, daddr, uh->source, saddr, dif); if (unlikely(count == ARRAY_SIZE(stack))) { if (!sk) break; flush_stack(stack, count, skb, ~0); count = 0; } } /* * before releasing chain lock, we must take a reference on sockets */ for (i = 0; i < count; i++) sock_hold(stack[i]); spin_unlock(&hslot->lock); /* * do the slow work with no lock held */ if (count) { flush_stack(stack, count, skb, count - 1); for (i = 0; i < count; i++) sock_put(stack[i]); } else { kfree_skb(skb); } return 0; } /* Initialize UDP checksum. If exited with zero value (success), * CHECKSUM_UNNECESSARY means, that no more checks are required. * Otherwise, csum completion requires chacksumming packet body, * including udp header and folding it to skb->csum. */ static inline int udp4_csum_init(struct sk_buff *skb, struct udphdr *uh, int proto) { const struct iphdr *iph; int err; UDP_SKB_CB(skb)->partial_cov = 0; UDP_SKB_CB(skb)->cscov = skb->len; if (proto == IPPROTO_UDPLITE) { err = udplite_checksum_init(skb, uh); if (err) return err; } iph = ip_hdr(skb); if (uh->check == 0) { skb->ip_summed = CHECKSUM_UNNECESSARY; } else if (skb->ip_summed == CHECKSUM_COMPLETE) { if (!csum_tcpudp_magic(iph->saddr, iph->daddr, skb->len, proto, skb->csum)) skb->ip_summed = CHECKSUM_UNNECESSARY; } if (!skb_csum_unnecessary(skb)) skb->csum = csum_tcpudp_nofold(iph->saddr, iph->daddr, skb->len, proto, 0); /* Probably, we should checksum udp header (it should be in cache * in any case) and data in tiny packets (< rx copybreak). */ return 0; } /* * All we need to do is get the socket, and then do a checksum. */ int __udp4_lib_rcv(struct sk_buff *skb, struct udp_table *udptable, int proto) { struct sock *sk; struct udphdr *uh; unsigned short ulen; struct rtable *rt = skb_rtable(skb); __be32 saddr, daddr; struct net *net = dev_net(skb->dev); /* * Validate the packet. */ if (!pskb_may_pull(skb, sizeof(struct udphdr))) goto drop; /* No space for header. */ uh = udp_hdr(skb); ulen = ntohs(uh->len); saddr = ip_hdr(skb)->saddr; daddr = ip_hdr(skb)->daddr; if (ulen > skb->len) goto short_packet; if (proto == IPPROTO_UDP) { /* UDP validates ulen. */ if (ulen < sizeof(*uh) || pskb_trim_rcsum(skb, ulen)) goto short_packet; uh = udp_hdr(skb); } if (udp4_csum_init(skb, uh, proto)) goto csum_error; if (skb->sk) { int ret; sk = skb->sk; if (unlikely(sk->sk_rx_dst == NULL)) udp_sk_rx_dst_set(sk, skb); ret = udp_queue_rcv_skb(sk, skb); /* a return value > 0 means to resubmit the input, but * it wants the return to be -protocol, or 0 */ if (ret > 0) return -ret; return 0; } else { if (rt->rt_flags & (RTCF_BROADCAST|RTCF_MULTICAST)) return __udp4_lib_mcast_deliver(net, skb, uh, saddr, daddr, udptable); sk = __udp4_lib_lookup_skb(skb, uh->source, uh->dest, udptable); } if (sk != NULL) { int ret; ret = udp_queue_rcv_skb(sk, skb); sock_put(sk); /* a return value > 0 means to resubmit the input, but * it wants the return to be -protocol, or 0 */ if (ret > 0) return -ret; return 0; } if (!xfrm4_policy_check(NULL, XFRM_POLICY_IN, skb)) goto drop; nf_reset(skb); /* No socket. Drop packet silently, if checksum is wrong */ if (udp_lib_checksum_complete(skb)) goto csum_error; UDP_INC_STATS_BH(net, UDP_MIB_NOPORTS, proto == IPPROTO_UDPLITE); icmp_send(skb, ICMP_DEST_UNREACH, ICMP_PORT_UNREACH, 0); /* * Hmm. We got an UDP packet to a port to which we * don't wanna listen. Ignore it. */ kfree_skb(skb); return 0; short_packet: LIMIT_NETDEBUG(KERN_DEBUG "UDP%s: short packet: From %pI4:%u %d/%d to %pI4:%u\n", proto == IPPROTO_UDPLITE ? "Lite" : "", &saddr, ntohs(uh->source), ulen, skb->len, &daddr, ntohs(uh->dest)); goto drop; csum_error: /* * RFC1122: OK. Discards the bad packet silently (as far as * the network is concerned, anyway) as per 4.1.3.4 (MUST). */ LIMIT_NETDEBUG(KERN_DEBUG "UDP%s: bad checksum. From %pI4:%u to %pI4:%u ulen %d\n", proto == IPPROTO_UDPLITE ? "Lite" : "", &saddr, ntohs(uh->source), &daddr, ntohs(uh->dest), ulen); UDP_INC_STATS_BH(net, UDP_MIB_CSUMERRORS, proto == IPPROTO_UDPLITE); drop: UDP_INC_STATS_BH(net, UDP_MIB_INERRORS, proto == IPPROTO_UDPLITE); kfree_skb(skb); return 0; } /* We can only early demux multicast if there is a single matching socket. * If more than one socket found returns NULL */ static struct sock *__udp4_lib_mcast_demux_lookup(struct net *net, __be16 loc_port, __be32 loc_addr, __be16 rmt_port, __be32 rmt_addr, int dif) { struct sock *sk, *result; struct hlist_nulls_node *node; unsigned short hnum = ntohs(loc_port); unsigned int count, slot = udp_hashfn(net, hnum, udp_table.mask); struct udp_hslot *hslot = &udp_table.hash[slot]; rcu_read_lock(); begin: count = 0; result = NULL; sk_nulls_for_each_rcu(sk, node, &hslot->head) { if (__udp_is_mcast_sock(net, sk, loc_port, loc_addr, rmt_port, rmt_addr, dif, hnum)) { result = sk; ++count; } } /* * if the nulls value we got at the end of this lookup is * not the expected one, we must restart lookup. * We probably met an item that was moved to another chain. */ if (get_nulls_value(node) != slot) goto begin; if (result) { if (count != 1 || unlikely(!atomic_inc_not_zero_hint(&result->sk_refcnt, 2))) result = NULL; else if (unlikely(!__udp_is_mcast_sock(net, result, loc_port, loc_addr, rmt_port, rmt_addr, dif, hnum))) { sock_put(result); result = NULL; } } rcu_read_unlock(); return result; } /* For unicast we should only early demux connected sockets or we can * break forwarding setups. The chains here can be long so only check * if the first socket is an exact match and if not move on. */ static struct sock *__udp4_lib_demux_lookup(struct net *net, __be16 loc_port, __be32 loc_addr, __be16 rmt_port, __be32 rmt_addr, int dif) { struct sock *sk, *result; struct hlist_nulls_node *node; unsigned short hnum = ntohs(loc_port); unsigned int hash2 = udp4_portaddr_hash(net, loc_addr, hnum); unsigned int slot2 = hash2 & udp_table.mask; struct udp_hslot *hslot2 = &udp_table.hash2[slot2]; INET_ADDR_COOKIE(acookie, rmt_addr, loc_addr) const __portpair ports = INET_COMBINED_PORTS(rmt_port, hnum); rcu_read_lock(); result = NULL; udp_portaddr_for_each_entry_rcu(sk, node, &hslot2->head) { if (INET_MATCH(sk, net, acookie, rmt_addr, loc_addr, ports, dif)) result = sk; /* Only check first socket in chain */ break; } if (result) { if (unlikely(!atomic_inc_not_zero_hint(&result->sk_refcnt, 2))) result = NULL; else if (unlikely(!INET_MATCH(sk, net, acookie, rmt_addr, loc_addr, ports, dif))) { sock_put(result); result = NULL; } } rcu_read_unlock(); return result; } void udp_v4_early_demux(struct sk_buff *skb) { const struct iphdr *iph = ip_hdr(skb); const struct udphdr *uh = udp_hdr(skb); struct sock *sk; struct dst_entry *dst; struct net *net = dev_net(skb->dev); int dif = skb->dev->ifindex; /* validate the packet */ if (!pskb_may_pull(skb, skb_transport_offset(skb) + sizeof(struct udphdr))) return; if (skb->pkt_type == PACKET_BROADCAST || skb->pkt_type == PACKET_MULTICAST) sk = __udp4_lib_mcast_demux_lookup(net, uh->dest, iph->daddr, uh->source, iph->saddr, dif); else if (skb->pkt_type == PACKET_HOST) sk = __udp4_lib_demux_lookup(net, uh->dest, iph->daddr, uh->source, iph->saddr, dif); else return; if (!sk) return; skb->sk = sk; skb->destructor = sock_edemux; dst = sk->sk_rx_dst; if (dst) dst = dst_check(dst, 0); if (dst) skb_dst_set_noref(skb, dst); } int udp_rcv(struct sk_buff *skb) { return __udp4_lib_rcv(skb, &udp_table, IPPROTO_UDP); } void udp_destroy_sock(struct sock *sk) { struct udp_sock *up = udp_sk(sk); bool slow = lock_sock_fast(sk); udp_flush_pending_frames(sk); unlock_sock_fast(sk, slow); if (static_key_false(&udp_encap_needed) && up->encap_type) { void (*encap_destroy)(struct sock *sk); encap_destroy = ACCESS_ONCE(up->encap_destroy); if (encap_destroy) encap_destroy(sk); } } /* * Socket option code for UDP */ int udp_lib_setsockopt(struct sock *sk, int level, int optname, char __user *optval, unsigned int optlen, int (*push_pending_frames)(struct sock *)) { struct udp_sock *up = udp_sk(sk); int val; int err = 0; int is_udplite = IS_UDPLITE(sk); if (optlen < sizeof(int)) return -EINVAL; if (get_user(val, (int __user *)optval)) return -EFAULT; switch (optname) { case UDP_CORK: if (val != 0) { up->corkflag = 1; } else { up->corkflag = 0; lock_sock(sk); (*push_pending_frames)(sk); release_sock(sk); } break; case UDP_ENCAP: switch (val) { case 0: case UDP_ENCAP_ESPINUDP: case UDP_ENCAP_ESPINUDP_NON_IKE: up->encap_rcv = xfrm4_udp_encap_rcv; /* FALLTHROUGH */ case UDP_ENCAP_L2TPINUDP: up->encap_type = val; udp_encap_enable(); break; default: err = -ENOPROTOOPT; break; } break; /* * UDP-Lite's partial checksum coverage (RFC 3828). */ /* The sender sets actual checksum coverage length via this option. * The case coverage > packet length is handled by send module. */ case UDPLITE_SEND_CSCOV: if (!is_udplite) /* Disable the option on UDP sockets */ return -ENOPROTOOPT; if (val != 0 && val < 8) /* Illegal coverage: use default (8) */ val = 8; else if (val > USHRT_MAX) val = USHRT_MAX; up->pcslen = val; up->pcflag |= UDPLITE_SEND_CC; break; /* The receiver specifies a minimum checksum coverage value. To make * sense, this should be set to at least 8 (as done below). If zero is * used, this again means full checksum coverage. */ case UDPLITE_RECV_CSCOV: if (!is_udplite) /* Disable the option on UDP sockets */ return -ENOPROTOOPT; if (val != 0 && val < 8) /* Avoid silly minimal values. */ val = 8; else if (val > USHRT_MAX) val = USHRT_MAX; up->pcrlen = val; up->pcflag |= UDPLITE_RECV_CC; break; default: err = -ENOPROTOOPT; break; } return err; } EXPORT_SYMBOL(udp_lib_setsockopt); int udp_setsockopt(struct sock *sk, int level, int optname, char __user *optval, unsigned int optlen) { if (level == SOL_UDP || level == SOL_UDPLITE) return udp_lib_setsockopt(sk, level, optname, optval, optlen, udp_push_pending_frames); return ip_setsockopt(sk, level, optname, optval, optlen); } #ifdef CONFIG_COMPAT int compat_udp_setsockopt(struct sock *sk, int level, int optname, char __user *optval, unsigned int optlen) { if (level == SOL_UDP || level == SOL_UDPLITE) return udp_lib_setsockopt(sk, level, optname, optval, optlen, udp_push_pending_frames); return compat_ip_setsockopt(sk, level, optname, optval, optlen); } #endif int udp_lib_getsockopt(struct sock *sk, int level, int optname, char __user *optval, int __user *optlen) { struct udp_sock *up = udp_sk(sk); int val, len; if (get_user(len, optlen)) return -EFAULT; len = min_t(unsigned int, len, sizeof(int)); if (len < 0) return -EINVAL; switch (optname) { case UDP_CORK: val = up->corkflag; break; case UDP_ENCAP: val = up->encap_type; break; /* The following two cannot be changed on UDP sockets, the return is * always 0 (which corresponds to the full checksum coverage of UDP). */ case UDPLITE_SEND_CSCOV: val = up->pcslen; break; case UDPLITE_RECV_CSCOV: val = up->pcrlen; break; default: return -ENOPROTOOPT; } if (put_user(len, optlen)) return -EFAULT; if (copy_to_user(optval, &val, len)) return -EFAULT; return 0; } EXPORT_SYMBOL(udp_lib_getsockopt); int udp_getsockopt(struct sock *sk, int level, int optname, char __user *optval, int __user *optlen) { if (level == SOL_UDP || level == SOL_UDPLITE) return udp_lib_getsockopt(sk, level, optname, optval, optlen); return ip_getsockopt(sk, level, optname, optval, optlen); } #ifdef CONFIG_COMPAT int compat_udp_getsockopt(struct sock *sk, int level, int optname, char __user *optval, int __user *optlen) { if (level == SOL_UDP || level == SOL_UDPLITE) return udp_lib_getsockopt(sk, level, optname, optval, optlen); return compat_ip_getsockopt(sk, level, optname, optval, optlen); } #endif /** * udp_poll - wait for a UDP event. * @file - file struct * @sock - socket * @wait - poll table * * This is same as datagram poll, except for the special case of * blocking sockets. If application is using a blocking fd * and a packet with checksum error is in the queue; * then it could get return from select indicating data available * but then block when reading it. Add special case code * to work around these arguably broken applications. */ unsigned int udp_poll(struct file *file, struct socket *sock, poll_table *wait) { unsigned int mask = datagram_poll(file, sock, wait); struct sock *sk = sock->sk; sock_rps_record_flow(sk); /* Check for false positives due to checksum errors */ if ((mask & POLLRDNORM) && !(file->f_flags & O_NONBLOCK) && !(sk->sk_shutdown & RCV_SHUTDOWN) && !first_packet_length(sk)) mask &= ~(POLLIN | POLLRDNORM); return mask; } EXPORT_SYMBOL(udp_poll); struct proto udp_prot = { .name = "UDP", .owner = THIS_MODULE, .close = udp_lib_close, .connect = ip4_datagram_connect, .disconnect = udp_disconnect, .ioctl = udp_ioctl, .destroy = udp_destroy_sock, .setsockopt = udp_setsockopt, .getsockopt = udp_getsockopt, .sendmsg = udp_sendmsg, .recvmsg = udp_recvmsg, .sendpage = udp_sendpage, .backlog_rcv = __udp_queue_rcv_skb, .release_cb = ip4_datagram_release_cb, .hash = udp_lib_hash, .unhash = udp_lib_unhash, .rehash = udp_v4_rehash, .get_port = udp_v4_get_port, .memory_allocated = &udp_memory_allocated, .sysctl_mem = sysctl_udp_mem, .sysctl_wmem = &sysctl_udp_wmem_min, .sysctl_rmem = &sysctl_udp_rmem_min, .obj_size = sizeof(struct udp_sock), .slab_flags = SLAB_DESTROY_BY_RCU, .h.udp_table = &udp_table, #ifdef CONFIG_COMPAT .compat_setsockopt = compat_udp_setsockopt, .compat_getsockopt = compat_udp_getsockopt, #endif .clear_sk = sk_prot_clear_portaddr_nulls, }; EXPORT_SYMBOL(udp_prot); /* ------------------------------------------------------------------------ */ #ifdef CONFIG_PROC_FS static struct sock *udp_get_first(struct seq_file *seq, int start) { struct sock *sk; struct udp_iter_state *state = seq->private; struct net *net = seq_file_net(seq); for (state->bucket = start; state->bucket <= state->udp_table->mask; ++state->bucket) { struct hlist_nulls_node *node; struct udp_hslot *hslot = &state->udp_table->hash[state->bucket]; if (hlist_nulls_empty(&hslot->head)) continue; spin_lock_bh(&hslot->lock); sk_nulls_for_each(sk, node, &hslot->head) { if (!net_eq(sock_net(sk), net)) continue; if (sk->sk_family == state->family) goto found; } spin_unlock_bh(&hslot->lock); } sk = NULL; found: return sk; } static struct sock *udp_get_next(struct seq_file *seq, struct sock *sk) { struct udp_iter_state *state = seq->private; struct net *net = seq_file_net(seq); do { sk = sk_nulls_next(sk); } while (sk && (!net_eq(sock_net(sk), net) || sk->sk_family != state->family)); if (!sk) { if (state->bucket <= state->udp_table->mask) spin_unlock_bh(&state->udp_table->hash[state->bucket].lock); return udp_get_first(seq, state->bucket + 1); } return sk; } static struct sock *udp_get_idx(struct seq_file *seq, loff_t pos) { struct sock *sk = udp_get_first(seq, 0); if (sk) while (pos && (sk = udp_get_next(seq, sk)) != NULL) --pos; return pos ? NULL : sk; } static void *udp_seq_start(struct seq_file *seq, loff_t *pos) { struct udp_iter_state *state = seq->private; state->bucket = MAX_UDP_PORTS; return *pos ? udp_get_idx(seq, *pos-1) : SEQ_START_TOKEN; } static void *udp_seq_next(struct seq_file *seq, void *v, loff_t *pos) { struct sock *sk; if (v == SEQ_START_TOKEN) sk = udp_get_idx(seq, 0); else sk = udp_get_next(seq, v); ++*pos; return sk; } static void udp_seq_stop(struct seq_file *seq, void *v) { struct udp_iter_state *state = seq->private; if (state->bucket <= state->udp_table->mask) spin_unlock_bh(&state->udp_table->hash[state->bucket].lock); } int udp_seq_open(struct inode *inode, struct file *file) { struct udp_seq_afinfo *afinfo = PDE_DATA(inode); struct udp_iter_state *s; int err; err = seq_open_net(inode, file, &afinfo->seq_ops, sizeof(struct udp_iter_state)); if (err < 0) return err; s = ((struct seq_file *)file->private_data)->private; s->family = afinfo->family; s->udp_table = afinfo->udp_table; return err; } EXPORT_SYMBOL(udp_seq_open); /* ------------------------------------------------------------------------ */ int udp_proc_register(struct net *net, struct udp_seq_afinfo *afinfo) { struct proc_dir_entry *p; int rc = 0; afinfo->seq_ops.start = udp_seq_start; afinfo->seq_ops.next = udp_seq_next; afinfo->seq_ops.stop = udp_seq_stop; p = proc_create_data(afinfo->name, S_IRUGO, net->proc_net, afinfo->seq_fops, afinfo); if (!p) rc = -ENOMEM; return rc; } EXPORT_SYMBOL(udp_proc_register); void udp_proc_unregister(struct net *net, struct udp_seq_afinfo *afinfo) { remove_proc_entry(afinfo->name, net->proc_net); } EXPORT_SYMBOL(udp_proc_unregister); /* ------------------------------------------------------------------------ */ static void udp4_format_sock(struct sock *sp, struct seq_file *f, int bucket, int *len) { struct inet_sock *inet = inet_sk(sp); __be32 dest = inet->inet_daddr; __be32 src = inet->inet_rcv_saddr; __u16 destp = ntohs(inet->inet_dport); __u16 srcp = ntohs(inet->inet_sport); seq_printf(f, "%5d: %08X:%04X %08X:%04X" " %02X %08X:%08X %02X:%08lX %08X %5u %8d %lu %d %pK %d%n", bucket, src, srcp, dest, destp, sp->sk_state, sk_wmem_alloc_get(sp), sk_rmem_alloc_get(sp), 0, 0L, 0, from_kuid_munged(seq_user_ns(f), sock_i_uid(sp)), 0, sock_i_ino(sp), atomic_read(&sp->sk_refcnt), sp, atomic_read(&sp->sk_drops), len); } int udp4_seq_show(struct seq_file *seq, void *v) { if (v == SEQ_START_TOKEN) seq_printf(seq, "%-127s\n", " sl local_address rem_address st tx_queue " "rx_queue tr tm->when retrnsmt uid timeout " "inode ref pointer drops"); else { struct udp_iter_state *state = seq->private; int len; udp4_format_sock(v, seq, state->bucket, &len); seq_printf(seq, "%*s\n", 127 - len, ""); } return 0; } static const struct file_operations udp_afinfo_seq_fops = { .owner = THIS_MODULE, .open = udp_seq_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release_net }; /* ------------------------------------------------------------------------ */ static struct udp_seq_afinfo udp4_seq_afinfo = { .name = "udp", .family = AF_INET, .udp_table = &udp_table, .seq_fops = &udp_afinfo_seq_fops, .seq_ops = { .show = udp4_seq_show, }, }; static int __net_init udp4_proc_init_net(struct net *net) { return udp_proc_register(net, &udp4_seq_afinfo); } static void __net_exit udp4_proc_exit_net(struct net *net) { udp_proc_unregister(net, &udp4_seq_afinfo); } static struct pernet_operations udp4_net_ops = { .init = udp4_proc_init_net, .exit = udp4_proc_exit_net, }; int __init udp4_proc_init(void) { return register_pernet_subsys(&udp4_net_ops); } void udp4_proc_exit(void) { unregister_pernet_subsys(&udp4_net_ops); } #endif /* CONFIG_PROC_FS */ static __initdata unsigned long uhash_entries; static int __init set_uhash_entries(char *str) { ssize_t ret; if (!str) return 0; ret = kstrtoul(str, 0, &uhash_entries); if (ret) return 0; if (uhash_entries && uhash_entries < UDP_HTABLE_SIZE_MIN) uhash_entries = UDP_HTABLE_SIZE_MIN; return 1; } __setup("uhash_entries=", set_uhash_entries); void __init udp_table_init(struct udp_table *table, const char *name) { unsigned int i; table->hash = alloc_large_system_hash(name, 2 * sizeof(struct udp_hslot), uhash_entries, 21, /* one slot per 2 MB */ 0, &table->log, &table->mask, UDP_HTABLE_SIZE_MIN, 64 * 1024); table->hash2 = table->hash + (table->mask + 1); for (i = 0; i <= table->mask; i++) { INIT_HLIST_NULLS_HEAD(&table->hash[i].head, i); table->hash[i].count = 0; spin_lock_init(&table->hash[i].lock); } for (i = 0; i <= table->mask; i++) { INIT_HLIST_NULLS_HEAD(&table->hash2[i].head, i); table->hash2[i].count = 0; spin_lock_init(&table->hash2[i].lock); } } void __init udp_init(void) { unsigned long limit; udp_table_init(&udp_table, "UDP"); limit = nr_free_buffer_pages() / 8; limit = max(limit, 128UL); sysctl_udp_mem[0] = limit / 4 * 3; sysctl_udp_mem[1] = limit; sysctl_udp_mem[2] = sysctl_udp_mem[0] * 2; sysctl_udp_rmem_min = SK_MEM_QUANTUM; sysctl_udp_wmem_min = SK_MEM_QUANTUM; } struct sk_buff *skb_udp_tunnel_segment(struct sk_buff *skb, netdev_features_t features) { struct sk_buff *segs = ERR_PTR(-EINVAL); int mac_len = skb->mac_len; int tnl_hlen = skb_inner_mac_header(skb) - skb_transport_header(skb); __be16 protocol = skb->protocol; netdev_features_t enc_features; int outer_hlen; if (unlikely(!pskb_may_pull(skb, tnl_hlen))) goto out; skb->encapsulation = 0; __skb_pull(skb, tnl_hlen); skb_reset_mac_header(skb); skb_set_network_header(skb, skb_inner_network_offset(skb)); skb->mac_len = skb_inner_network_offset(skb); skb->protocol = htons(ETH_P_TEB); /* segment inner packet. */ enc_features = skb->dev->hw_enc_features & netif_skb_features(skb); segs = skb_mac_gso_segment(skb, enc_features); if (!segs || IS_ERR(segs)) goto out; outer_hlen = skb_tnl_header_len(skb); skb = segs; do { struct udphdr *uh; int udp_offset = outer_hlen - tnl_hlen; skb_reset_inner_headers(skb); skb->encapsulation = 1; skb->mac_len = mac_len; skb_push(skb, outer_hlen); skb_reset_mac_header(skb); skb_set_network_header(skb, mac_len); skb_set_transport_header(skb, udp_offset); uh = udp_hdr(skb); uh->len = htons(skb->len - udp_offset); /* csum segment if tunnel sets skb with csum. */ if (protocol == htons(ETH_P_IP) && unlikely(uh->check)) { struct iphdr *iph = ip_hdr(skb); uh->check = ~csum_tcpudp_magic(iph->saddr, iph->daddr, skb->len - udp_offset, IPPROTO_UDP, 0); uh->check = csum_fold(skb_checksum(skb, udp_offset, skb->len - udp_offset, 0)); if (uh->check == 0) uh->check = CSUM_MANGLED_0; } else if (protocol == htons(ETH_P_IPV6)) { struct ipv6hdr *ipv6h = ipv6_hdr(skb); u32 len = skb->len - udp_offset; uh->check = ~csum_ipv6_magic(&ipv6h->saddr, &ipv6h->daddr, len, IPPROTO_UDP, 0); uh->check = csum_fold(skb_checksum(skb, udp_offset, len, 0)); if (uh->check == 0) uh->check = CSUM_MANGLED_0; skb->ip_summed = CHECKSUM_NONE; } skb->protocol = protocol; } while ((skb = skb->next)); out: return segs; }
./CrossVul/dataset_final_sorted/CWE-20/c/bad_5844_3
crossvul-cpp_data_bad_1564_2
/* Copyright (C) 2009 RedHat inc. 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <sys/statvfs.h> #include "internal_libabrt.h" int low_free_space(unsigned setting_MaxCrashReportsSize, const char *dump_location) { struct statvfs vfs; if (statvfs(dump_location, &vfs) != 0) { perror_msg("statvfs('%s')", dump_location); return 0; } /* Check that at least MaxCrashReportsSize/4 MBs are free */ /* fs_free_mb_x4 ~= vfs.f_bfree * vfs.f_bsize * 4, expressed in MBytes. * Need to neither overflow nor round f_bfree down too much. */ unsigned long fs_free_mb_x4 = ((unsigned long long)vfs.f_bfree / (1024/4)) * vfs.f_bsize / 1024; if (fs_free_mb_x4 < setting_MaxCrashReportsSize) { error_msg("Only %luMiB is available on %s", fs_free_mb_x4 / 4, dump_location); return 1; } return 0; } /* rhbz#539551: "abrt going crazy when crashing process is respawned". * Check total size of problem dirs, if it overflows, * delete oldest/biggest dirs. */ void trim_problem_dirs(const char *dirname, double cap_size, const char *exclude_path) { const char *excluded_basename = NULL; if (exclude_path) { unsigned len_dirname = strlen(dirname); /* Trim trailing '/'s, but dont trim name "/" to "" */ while (len_dirname > 1 && dirname[len_dirname-1] == '/') len_dirname--; if (strncmp(dirname, exclude_path, len_dirname) == 0 && exclude_path[len_dirname] == '/' ) { /* exclude_path is "dirname/something" */ excluded_basename = exclude_path + len_dirname + 1; } } log_debug("excluded_basename:'%s'", excluded_basename); int count = 20; while (--count >= 0) { /* We exclude our own dir from candidates for deletion (3rd param): */ char *worst_basename = NULL; double cur_size = get_dirsize_find_largest_dir(dirname, &worst_basename, excluded_basename); if (cur_size <= cap_size || !worst_basename) { log_info("cur_size:%.0f cap_size:%.0f, no (more) trimming", cur_size, cap_size); free(worst_basename); break; } log("%s is %.0f bytes (more than %.0fMiB), deleting '%s'", dirname, cur_size, cap_size / (1024*1024), worst_basename); char *d = concat_path_file(dirname, worst_basename); free(worst_basename); delete_dump_dir(d); free(d); } } /** * * @param[out] status See `man 2 wait` for status information. * @return Malloc'ed string */ static char* exec_vp(char **args, int redirect_stderr, int exec_timeout_sec, int *status) { /* Nuke everything which may make setlocale() switch to non-POSIX locale: * we need to avoid having gdb output in some obscure language. */ static const char *const env_vec[] = { "LANG", "LC_ALL", "LC_COLLATE", "LC_CTYPE", "LC_MESSAGES", "LC_MONETARY", "LC_NUMERIC", "LC_TIME", /* Workaround for * http://sourceware.org/bugzilla/show_bug.cgi?id=9622 * (gdb emitting ESC sequences even with -batch) */ "TERM", NULL }; int flags = EXECFLG_INPUT_NUL | EXECFLG_OUTPUT | EXECFLG_SETSID | EXECFLG_QUIET; if (redirect_stderr) flags |= EXECFLG_ERR2OUT; VERB1 flags &= ~EXECFLG_QUIET; int pipeout[2]; pid_t child = fork_execv_on_steroids(flags, args, pipeout, (char**)env_vec, /*dir:*/ NULL, /*uid(unused):*/ 0); /* We use this function to run gdb and unstrip. Bugs in gdb or corrupted * coredumps were observed to cause gdb to enter infinite loop. * Therefore we have a (largish) timeout, after which we kill the child. */ ndelay_on(pipeout[0]); int t = time(NULL); /* int is enough, no need to use time_t */ int endtime = t + exec_timeout_sec; struct strbuf *buf_out = strbuf_new(); while (1) { int timeout = endtime - t; if (timeout < 0) { kill(child, SIGKILL); strbuf_append_strf(buf_out, "\n" "Timeout exceeded: %u seconds, killing %s.\n" "Looks like gdb hung while generating backtrace.\n" "This may be a bug in gdb. Consider submitting a bug report to gdb developers.\n" "Please attach coredump from this crash to the bug report if you do.\n", exec_timeout_sec, args[0] ); break; } /* We don't check poll result - checking read result is enough */ struct pollfd pfd; pfd.fd = pipeout[0]; pfd.events = POLLIN; poll(&pfd, 1, timeout * 1000); char buff[1024]; int r = read(pipeout[0], buff, sizeof(buff) - 1); if (r <= 0) { /* I did see EAGAIN happening here */ if (r < 0 && errno == EAGAIN) goto next; break; } buff[r] = '\0'; strbuf_append_str(buf_out, buff); next: t = time(NULL); } close(pipeout[0]); /* Prevent having zombie child process, and maybe collect status * (note that status == NULL is ok too) */ safe_waitpid(child, status, 0); return strbuf_free_nobuf(buf_out); } char *run_unstrip_n(const char *dump_dir_name, unsigned timeout_sec) { int flags = EXECFLG_INPUT_NUL | EXECFLG_OUTPUT | EXECFLG_SETSID | EXECFLG_QUIET; VERB1 flags &= ~EXECFLG_QUIET; int pipeout[2]; char* args[4]; args[0] = (char*)"eu-unstrip"; args[1] = xasprintf("--core=%s/"FILENAME_COREDUMP, dump_dir_name); args[2] = (char*)"-n"; args[3] = NULL; pid_t child = fork_execv_on_steroids(flags, args, pipeout, /*env_vec:*/ NULL, /*dir:*/ NULL, /*uid(unused):*/ 0); free(args[1]); /* Bugs in unstrip or corrupted coredumps can cause it to enter infinite loop. * Therefore we have a (largish) timeout, after which we kill the child. */ ndelay_on(pipeout[0]); int t = time(NULL); /* int is enough, no need to use time_t */ int endtime = t + timeout_sec; struct strbuf *buf_out = strbuf_new(); while (1) { int timeout = endtime - t; if (timeout < 0) { kill(child, SIGKILL); strbuf_free(buf_out); buf_out = NULL; break; } /* We don't check poll result - checking read result is enough */ struct pollfd pfd; pfd.fd = pipeout[0]; pfd.events = POLLIN; poll(&pfd, 1, timeout * 1000); char buff[1024]; int r = read(pipeout[0], buff, sizeof(buff) - 1); if (r <= 0) { /* I did see EAGAIN happening here */ if (r < 0 && errno == EAGAIN) goto next; break; } buff[r] = '\0'; strbuf_append_str(buf_out, buff); next: t = time(NULL); } close(pipeout[0]); /* Prevent having zombie child process */ int status; safe_waitpid(child, &status, 0); if (status != 0 || buf_out == NULL) { /* unstrip didnt exit with exit code 0, or we timed out */ strbuf_free(buf_out); return NULL; } return strbuf_free_nobuf(buf_out); } char *get_backtrace(const char *dump_dir_name, unsigned timeout_sec, const char *debuginfo_dirs) { INITIALIZE_LIBABRT(); struct dump_dir *dd = dd_opendir(dump_dir_name, /*flags:*/ 0); if (!dd) return NULL; char *executable = dd_load_text(dd, FILENAME_EXECUTABLE); dd_close(dd); /* Let user know what's going on */ log(_("Generating backtrace")); unsigned i = 0; char *args[25]; args[i++] = (char*)"gdb"; args[i++] = (char*)"-batch"; struct strbuf *set_debug_file_directory = strbuf_new(); unsigned auto_load_base_index = 0; if(debuginfo_dirs == NULL) { // set non-existent debug file directory to prevent resolving // function names - we need offsets for core backtrace. strbuf_append_str(set_debug_file_directory, "set debug-file-directory /"); } else { strbuf_append_str(set_debug_file_directory, "set debug-file-directory /usr/lib/debug"); struct strbuf *debug_directories = strbuf_new(); const char *p = debuginfo_dirs; while (1) { while (*p == ':') p++; if (*p == '\0') break; const char *colon_or_nul = strchrnul(p, ':'); strbuf_append_strf(debug_directories, "%s%.*s/usr/lib/debug", (debug_directories->len == 0 ? "" : ":"), (int)(colon_or_nul - p), p); p = colon_or_nul; } strbuf_append_strf(set_debug_file_directory, ":%s", debug_directories->buf); args[i++] = (char*)"-iex"; auto_load_base_index = i; args[i++] = xasprintf("add-auto-load-safe-path %s", debug_directories->buf); args[i++] = (char*)"-iex"; args[i++] = xasprintf("add-auto-load-scripts-directory %s", debug_directories->buf); strbuf_free(debug_directories); } args[i++] = (char*)"-ex"; const unsigned debug_dir_cmd_index = i++; args[debug_dir_cmd_index] = strbuf_free_nobuf(set_debug_file_directory); /* "file BINARY_FILE" is needed, without it gdb cannot properly * unwind the stack. Currently the unwind information is located * in .eh_frame which is stored only in binary, not in coredump * or debuginfo. * * Fedora GDB does not strictly need it, it will find the binary * by its build-id. But for binaries either without build-id * (= built on non-Fedora GCC) or which do not have * their debuginfo rpm installed gdb would not find BINARY_FILE * so it is still makes sense to supply "file BINARY_FILE". * * Unfortunately, "file BINARY_FILE" doesn't work well if BINARY_FILE * was deleted (as often happens during system updates): * gdb uses specified BINARY_FILE * even if it is completely unrelated to the coredump. * See https://bugzilla.redhat.com/show_bug.cgi?id=525721 * * TODO: check mtimes on COREFILE and BINARY_FILE and not supply * BINARY_FILE if it is newer (to at least avoid gdb complaining). */ args[i++] = (char*)"-ex"; const unsigned file_cmd_index = i++; args[file_cmd_index] = xasprintf("file %s", executable); free(executable); args[i++] = (char*)"-ex"; const unsigned core_cmd_index = i++; args[core_cmd_index] = xasprintf("core-file %s/"FILENAME_COREDUMP, dump_dir_name); args[i++] = (char*)"-ex"; const unsigned bt_cmd_index = i++; /*args[9] = ... see below */ args[i++] = (char*)"-ex"; args[i++] = (char*)"info sharedlib"; /* glibc's abort() stores its message in __abort_msg variable */ args[i++] = (char*)"-ex"; args[i++] = (char*)"print (char*)__abort_msg"; args[i++] = (char*)"-ex"; args[i++] = (char*)"print (char*)__glib_assert_msg"; args[i++] = (char*)"-ex"; args[i++] = (char*)"info all-registers"; args[i++] = (char*)"-ex"; const unsigned dis_cmd_index = i++; args[dis_cmd_index] = (char*)"disassemble"; args[i++] = NULL; /* Get the backtrace, but try to cap its size */ /* Limit bt depth. With no limit, gdb sometimes OOMs the machine */ unsigned bt_depth = 1024; const char *thread_apply_all = "thread apply all"; const char *full = " full"; char *bt = NULL; while (1) { args[bt_cmd_index] = xasprintf("%s backtrace %u%s", thread_apply_all, bt_depth, full); bt = exec_vp(args, /*redirect_stderr:*/ 1, timeout_sec, NULL); free(args[bt_cmd_index]); if ((bt && strnlen(bt, 256*1024) < 256*1024) || bt_depth <= 32) { break; } bt_depth /= 2; if (bt) log("Backtrace is too big (%u bytes), reducing depth to %u", (unsigned)strlen(bt), bt_depth); else /* (NB: in fact, current impl. of exec_vp() never returns NULL) */ log("Failed to generate backtrace, reducing depth to %u", bt_depth); free(bt); /* Replace -ex disassemble (which disasms entire function $pc points to) * to a version which analyzes limited, small patch of code around $pc. * (Users reported a case where bare "disassemble" attempted to process * entire .bss). * TODO: what if "$pc-N" underflows? in my test, this happens: * Dump of assembler code from 0xfffffffffffffff0 to 0x30: * End of assembler dump. * (IOW: "empty" dump) */ args[dis_cmd_index] = (char*)"disassemble $pc-20, $pc+64"; if (bt_depth <= 64 && thread_apply_all[0] != '\0') { /* This program likely has gazillion threads, dont try to bt them all */ bt_depth = 128; thread_apply_all = ""; } if (bt_depth <= 64 && full[0] != '\0') { /* Looks like there are gigantic local structures or arrays, disable "full" bt */ bt_depth = 128; full = ""; } } if (auto_load_base_index > 0) { free(args[auto_load_base_index]); free(args[auto_load_base_index + 2]); } free(args[debug_dir_cmd_index]); free(args[file_cmd_index]); free(args[core_cmd_index]); return bt; } char* problem_data_save(problem_data_t *pd) { load_abrt_conf(); struct dump_dir *dd = NULL; if (g_settings_privatereports) dd = create_dump_dir_from_problem_data_ext(pd, g_settings_dump_location, 0); else dd = create_dump_dir_from_problem_data(pd, g_settings_dump_location); char *problem_id = NULL; if (dd) { problem_id = xstrdup(dd->dd_dirname); dd_close(dd); } log_info("problem id: '%s'", problem_id); return problem_id; }
./CrossVul/dataset_final_sorted/CWE-20/c/bad_1564_2
crossvul-cpp_data_good_5576_0
/* -*- mode: c; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* kdc/do_tgs_req.c - KDC Routines to deal with TGS_REQ's */ /* * Copyright 1990,1991,2001,2007,2008,2009 by the Massachusetts Institute of Technology. * All Rights Reserved. * * Export of this software from the United States of America may * require a specific license from the United States Government. * It is the responsibility of any person or organization contemplating * export to obtain such a license before exporting. * * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and * distribute this software and its documentation for any purpose and * without fee is hereby granted, provided that the above copyright * notice appear in all copies and that both that copyright notice and * this permission notice appear in supporting documentation, and that * the name of M.I.T. not be used in advertising or publicity pertaining * to distribution of the software without specific, written prior * permission. Furthermore if you modify this software you must label * your software as modified software and not distribute it in such a * fashion that it might be confused with the original M.I.T. software. * M.I.T. makes no representations about the suitability of * this software for any purpose. It is provided "as is" without express * or implied warranty. */ /* * Copyright (c) 2006-2008, Novell, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * The copyright holder's name is not used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "k5-int.h" #include <syslog.h> #ifdef HAVE_NETINET_IN_H #include <sys/types.h> #include <netinet/in.h> #ifndef hpux #include <arpa/inet.h> #endif #endif #include "kdc_util.h" #include "policy.h" #include "extern.h" #include "adm_proto.h" #include <ctype.h> static krb5_error_code find_alternate_tgs(kdc_realm_t *, krb5_principal, krb5_db_entry **, const char**); static krb5_error_code prepare_error_tgs(struct kdc_request_state *, krb5_kdc_req *,krb5_ticket *,int, krb5_principal,krb5_data **,const char *, krb5_pa_data **); static krb5_error_code decrypt_2ndtkt(kdc_realm_t *, krb5_kdc_req *, krb5_flags, krb5_db_entry **, const char **); static krb5_error_code gen_session_key(kdc_realm_t *, krb5_kdc_req *, krb5_db_entry *, krb5_keyblock *, const char **); static krb5_int32 find_referral_tgs(kdc_realm_t *, krb5_kdc_req *, krb5_principal *); static krb5_error_code db_get_svc_princ(krb5_context, krb5_principal, krb5_flags, krb5_db_entry **, const char **); static krb5_error_code search_sprinc(kdc_realm_t *, krb5_kdc_req *, krb5_flags, krb5_db_entry **, const char **); /*ARGSUSED*/ krb5_error_code process_tgs_req(struct server_handle *handle, krb5_data *pkt, const krb5_fulladdr *from, krb5_data **response) { krb5_keyblock * subkey = 0; krb5_keyblock * tgskey = 0; krb5_kdc_req *request = 0; krb5_db_entry *server = NULL; krb5_db_entry *stkt_server = NULL; krb5_kdc_rep reply; krb5_enc_kdc_rep_part reply_encpart; krb5_ticket ticket_reply, *header_ticket = 0; int st_idx = 0; krb5_enc_tkt_part enc_tkt_reply; krb5_transited enc_tkt_transited; int newtransited = 0; krb5_error_code retval = 0; krb5_keyblock encrypting_key; krb5_timestamp kdc_time, authtime = 0; krb5_keyblock session_key; krb5_timestamp rtime; krb5_keyblock *reply_key = NULL; krb5_key_data *server_key; krb5_principal cprinc = NULL, sprinc = NULL, altcprinc = NULL; krb5_last_req_entry *nolrarray[2], nolrentry; int errcode; const char *status = 0; krb5_enc_tkt_part *header_enc_tkt = NULL; /* TGT */ krb5_enc_tkt_part *subject_tkt = NULL; /* TGT or evidence ticket */ krb5_db_entry *client = NULL, *krbtgt = NULL; krb5_pa_s4u_x509_user *s4u_x509_user = NULL; /* protocol transition request */ krb5_authdata **kdc_issued_auth_data = NULL; /* auth data issued by KDC */ unsigned int c_flags = 0, s_flags = 0; /* client/server KDB flags */ krb5_boolean is_referral; const char *emsg = NULL; krb5_kvno ticket_kvno = 0; struct kdc_request_state *state = NULL; krb5_pa_data *pa_tgs_req; /*points into request*/ krb5_data scratch; krb5_pa_data **e_data = NULL; kdc_realm_t *kdc_active_realm = NULL; reply.padata = 0; /* For cleanup handler */ reply_encpart.enc_padata = 0; enc_tkt_reply.authorization_data = NULL; session_key.contents = NULL; retval = decode_krb5_tgs_req(pkt, &request); if (retval) return retval; if (request->msg_type != KRB5_TGS_REQ) { krb5_free_kdc_req(handle->kdc_err_context, request); return KRB5_BADMSGTYPE; } /* * setup_server_realm() sets up the global realm-specific data pointer. */ kdc_active_realm = setup_server_realm(handle, request->server); if (kdc_active_realm == NULL) { krb5_free_kdc_req(handle->kdc_err_context, request); return KRB5KDC_ERR_WRONG_REALM; } errcode = kdc_make_rstate(kdc_active_realm, &state); if (errcode !=0) { krb5_free_kdc_req(handle->kdc_err_context, request); return errcode; } errcode = kdc_process_tgs_req(kdc_active_realm, request, from, pkt, &header_ticket, &krbtgt, &tgskey, &subkey, &pa_tgs_req); if (header_ticket && header_ticket->enc_part2) cprinc = header_ticket->enc_part2->client; if (errcode) { status = "PROCESS_TGS"; goto cleanup; } if (!header_ticket) { errcode = KRB5_NO_TKT_SUPPLIED; /* XXX? */ status="UNEXPECTED NULL in header_ticket"; goto cleanup; } scratch.length = pa_tgs_req->length; scratch.data = (char *) pa_tgs_req->contents; errcode = kdc_find_fast(&request, &scratch, subkey, header_ticket->enc_part2->session, state, NULL); if (errcode !=0) { status = "kdc_find_fast"; goto cleanup; } /* * Pointer to the encrypted part of the header ticket, which may be * replaced to point to the encrypted part of the evidence ticket * if constrained delegation is used. This simplifies the number of * special cases for constrained delegation. */ header_enc_tkt = header_ticket->enc_part2; /* * We've already dealt with the AP_REQ authentication, so we can * use header_ticket freely. The encrypted part (if any) has been * decrypted with the session key. */ /* XXX make sure server here has the proper realm...taken from AP_REQ header? */ setflag(s_flags, KRB5_KDB_FLAG_ALIAS_OK); if (isflagset(request->kdc_options, KDC_OPT_CANONICALIZE)) { setflag(c_flags, KRB5_KDB_FLAG_CANONICALIZE); setflag(s_flags, KRB5_KDB_FLAG_CANONICALIZE); } errcode = search_sprinc(kdc_active_realm, request, s_flags, &server, &status); if (errcode != 0) goto cleanup; sprinc = server->princ; /* XXX until nothing depends on request being mutated */ krb5_free_principal(kdc_context, request->server); request->server = NULL; errcode = krb5_copy_principal(kdc_context, server->princ, &request->server); if (errcode != 0) { status = "COPYING RESOLVED SERVER"; goto cleanup; } if ((errcode = krb5_timeofday(kdc_context, &kdc_time))) { status = "TIME_OF_DAY"; goto cleanup; } if ((retval = validate_tgs_request(kdc_active_realm, request, *server, header_ticket, kdc_time, &status, &e_data))) { if (!status) status = "UNKNOWN_REASON"; errcode = retval + ERROR_TABLE_BASE_krb5; goto cleanup; } if (!is_local_principal(kdc_active_realm, header_enc_tkt->client)) setflag(c_flags, KRB5_KDB_FLAG_CROSS_REALM); is_referral = krb5_is_tgs_principal(server->princ) && !krb5_principal_compare(kdc_context, tgs_server, server->princ); /* Check for protocol transition */ errcode = kdc_process_s4u2self_req(kdc_active_realm, request, header_enc_tkt->client, server, subkey, header_enc_tkt->session, kdc_time, &s4u_x509_user, &client, &status); if (errcode) goto cleanup; if (s4u_x509_user != NULL) setflag(c_flags, KRB5_KDB_FLAG_PROTOCOL_TRANSITION); errcode = decrypt_2ndtkt(kdc_active_realm, request, c_flags, &stkt_server, &status); if (errcode) goto cleanup; if (isflagset(request->kdc_options, KDC_OPT_CNAME_IN_ADDL_TKT)) { /* Do constrained delegation protocol and authorization checks */ errcode = kdc_process_s4u2proxy_req(kdc_active_realm, request, request->second_ticket[st_idx]->enc_part2, stkt_server, header_ticket->enc_part2->client, request->server, &status); if (errcode) goto cleanup; setflag(c_flags, KRB5_KDB_FLAG_CONSTRAINED_DELEGATION); assert(krb5_is_tgs_principal(header_ticket->server)); assert(client == NULL); /* assured by kdc_process_s4u2self_req() */ client = stkt_server; stkt_server = NULL; } else if (request->kdc_options & KDC_OPT_ENC_TKT_IN_SKEY) { krb5_db_free_principal(kdc_context, stkt_server); stkt_server = NULL; } else assert(stkt_server == NULL); errcode = gen_session_key(kdc_active_realm, request, server, &session_key, &status); if (errcode) goto cleanup; /* * subject_tkt will refer to the evidence ticket (for constrained * delegation) or the TGT. The distinction from header_enc_tkt is * necessary because the TGS signature only protects some fields: * the others could be forged by a malicious server. */ if (isflagset(c_flags, KRB5_KDB_FLAG_CONSTRAINED_DELEGATION)) subject_tkt = request->second_ticket[st_idx]->enc_part2; else subject_tkt = header_enc_tkt; authtime = subject_tkt->times.authtime; if (is_referral) ticket_reply.server = server->princ; else ticket_reply.server = request->server; /* XXX careful for realm... */ enc_tkt_reply.flags = 0; enc_tkt_reply.times.starttime = 0; if (isflagset(server->attributes, KRB5_KDB_OK_AS_DELEGATE)) setflag(enc_tkt_reply.flags, TKT_FLG_OK_AS_DELEGATE); /* * Fix header_ticket's starttime; if it's zero, fill in the * authtime's value. */ if (!(header_enc_tkt->times.starttime)) header_enc_tkt->times.starttime = authtime; setflag(enc_tkt_reply.flags, TKT_FLG_ENC_PA_REP); /* don't use new addresses unless forwarded, see below */ enc_tkt_reply.caddrs = header_enc_tkt->caddrs; /* noaddrarray[0] = 0; */ reply_encpart.caddrs = 0;/* optional...don't put it in */ reply_encpart.enc_padata = NULL; /* * It should be noted that local policy may affect the * processing of any of these flags. For example, some * realms may refuse to issue renewable tickets */ if (isflagset(request->kdc_options, KDC_OPT_FORWARDABLE)) { setflag(enc_tkt_reply.flags, TKT_FLG_FORWARDABLE); if (isflagset(c_flags, KRB5_KDB_FLAG_PROTOCOL_TRANSITION)) { /* * If S4U2Self principal is not forwardable, then mark ticket as * unforwardable. This behaviour matches Windows, but it is * different to the MIT AS-REQ path, which returns an error * (KDC_ERR_POLICY) if forwardable tickets cannot be issued. * * Consider this block the S4U2Self equivalent to * validate_forwardable(). */ if (client != NULL && isflagset(client->attributes, KRB5_KDB_DISALLOW_FORWARDABLE)) clear(enc_tkt_reply.flags, TKT_FLG_FORWARDABLE); /* * Forwardable flag is propagated along referral path. */ else if (!isflagset(header_enc_tkt->flags, TKT_FLG_FORWARDABLE)) clear(enc_tkt_reply.flags, TKT_FLG_FORWARDABLE); /* * OK_TO_AUTH_AS_DELEGATE must be set on the service requesting * S4U2Self in order for forwardable tickets to be returned. */ else if (!is_referral && !isflagset(server->attributes, KRB5_KDB_OK_TO_AUTH_AS_DELEGATE)) clear(enc_tkt_reply.flags, TKT_FLG_FORWARDABLE); } } if (isflagset(request->kdc_options, KDC_OPT_FORWARDED)) { setflag(enc_tkt_reply.flags, TKT_FLG_FORWARDED); /* include new addresses in ticket & reply */ enc_tkt_reply.caddrs = request->addresses; reply_encpart.caddrs = request->addresses; } if (isflagset(header_enc_tkt->flags, TKT_FLG_FORWARDED)) setflag(enc_tkt_reply.flags, TKT_FLG_FORWARDED); if (isflagset(request->kdc_options, KDC_OPT_PROXIABLE)) setflag(enc_tkt_reply.flags, TKT_FLG_PROXIABLE); if (isflagset(request->kdc_options, KDC_OPT_PROXY)) { setflag(enc_tkt_reply.flags, TKT_FLG_PROXY); /* include new addresses in ticket & reply */ enc_tkt_reply.caddrs = request->addresses; reply_encpart.caddrs = request->addresses; } if (isflagset(request->kdc_options, KDC_OPT_ALLOW_POSTDATE)) setflag(enc_tkt_reply.flags, TKT_FLG_MAY_POSTDATE); if (isflagset(request->kdc_options, KDC_OPT_POSTDATED)) { setflag(enc_tkt_reply.flags, TKT_FLG_POSTDATED); setflag(enc_tkt_reply.flags, TKT_FLG_INVALID); enc_tkt_reply.times.starttime = request->from; } else enc_tkt_reply.times.starttime = kdc_time; if (isflagset(request->kdc_options, KDC_OPT_VALIDATE)) { assert(isflagset(c_flags, KRB5_KDB_FLAGS_S4U) == 0); /* BEWARE of allocation hanging off of ticket & enc_part2, it belongs to the caller */ ticket_reply = *(header_ticket); enc_tkt_reply = *(header_ticket->enc_part2); enc_tkt_reply.authorization_data = NULL; clear(enc_tkt_reply.flags, TKT_FLG_INVALID); } if (isflagset(request->kdc_options, KDC_OPT_RENEW)) { krb5_deltat old_life; assert(isflagset(c_flags, KRB5_KDB_FLAGS_S4U) == 0); /* BEWARE of allocation hanging off of ticket & enc_part2, it belongs to the caller */ ticket_reply = *(header_ticket); enc_tkt_reply = *(header_ticket->enc_part2); enc_tkt_reply.authorization_data = NULL; old_life = enc_tkt_reply.times.endtime - enc_tkt_reply.times.starttime; enc_tkt_reply.times.starttime = kdc_time; enc_tkt_reply.times.endtime = min(header_ticket->enc_part2->times.renew_till, kdc_time + old_life); } else { /* not a renew request */ enc_tkt_reply.times.starttime = kdc_time; kdc_get_ticket_endtime(kdc_active_realm, enc_tkt_reply.times.starttime, header_enc_tkt->times.endtime, request->till, client, server, &enc_tkt_reply.times.endtime); if (isflagset(request->kdc_options, KDC_OPT_RENEWABLE_OK) && (enc_tkt_reply.times.endtime < request->till) && isflagset(header_enc_tkt->flags, TKT_FLG_RENEWABLE)) { setflag(request->kdc_options, KDC_OPT_RENEWABLE); request->rtime = min(request->till, header_enc_tkt->times.renew_till); } } rtime = (request->rtime == 0) ? kdc_infinity : request->rtime; if (isflagset(request->kdc_options, KDC_OPT_RENEWABLE)) { /* already checked above in policy check to reject request for a renewable ticket using a non-renewable ticket */ setflag(enc_tkt_reply.flags, TKT_FLG_RENEWABLE); enc_tkt_reply.times.renew_till = min(rtime, min(header_enc_tkt->times.renew_till, enc_tkt_reply.times.starttime + min(server->max_renewable_life, max_renewable_life_for_realm))); } else { enc_tkt_reply.times.renew_till = 0; } if (isflagset(header_enc_tkt->flags, TKT_FLG_ANONYMOUS)) setflag(enc_tkt_reply.flags, TKT_FLG_ANONYMOUS); /* * Set authtime to be the same as header or evidence ticket's */ enc_tkt_reply.times.authtime = authtime; /* * Propagate the preauthentication flags through to the returned ticket. */ if (isflagset(header_enc_tkt->flags, TKT_FLG_PRE_AUTH)) setflag(enc_tkt_reply.flags, TKT_FLG_PRE_AUTH); if (isflagset(header_enc_tkt->flags, TKT_FLG_HW_AUTH)) setflag(enc_tkt_reply.flags, TKT_FLG_HW_AUTH); /* starttime is optional, and treated as authtime if not present. so we can nuke it if it matches */ if (enc_tkt_reply.times.starttime == enc_tkt_reply.times.authtime) enc_tkt_reply.times.starttime = 0; if (isflagset(c_flags, KRB5_KDB_FLAG_PROTOCOL_TRANSITION)) { altcprinc = s4u_x509_user->user_id.user; } else if (isflagset(c_flags, KRB5_KDB_FLAG_CONSTRAINED_DELEGATION)) { altcprinc = subject_tkt->client; } else { altcprinc = NULL; } if (isflagset(request->kdc_options, KDC_OPT_ENC_TKT_IN_SKEY)) { krb5_enc_tkt_part *t2enc = request->second_ticket[st_idx]->enc_part2; encrypting_key = *(t2enc->session); } else { /* * Find the server key */ if ((errcode = krb5_dbe_find_enctype(kdc_context, server, -1, /* ignore keytype */ -1, /* Ignore salttype */ 0, /* Get highest kvno */ &server_key))) { status = "FINDING_SERVER_KEY"; goto cleanup; } /* * Convert server.key into a real key * (it may be encrypted in the database) */ if ((errcode = krb5_dbe_decrypt_key_data(kdc_context, NULL, server_key, &encrypting_key, NULL))) { status = "DECRYPT_SERVER_KEY"; goto cleanup; } } if (isflagset(c_flags, KRB5_KDB_FLAG_CONSTRAINED_DELEGATION)) { /* * Don't allow authorization data to be disabled if constrained * delegation is requested. We don't want to deny the server * the ability to validate that delegation was used. */ clear(server->attributes, KRB5_KDB_NO_AUTH_DATA_REQUIRED); } if (isflagset(server->attributes, KRB5_KDB_NO_AUTH_DATA_REQUIRED) == 0) { /* * If we are not doing protocol transition/constrained delegation * try to lookup the client principal so plugins can add additional * authorization information. * * Always validate authorization data for constrained delegation * because we must validate the KDC signatures. */ if (!isflagset(c_flags, KRB5_KDB_FLAGS_S4U)) { /* Generate authorization data so we can include it in ticket */ setflag(c_flags, KRB5_KDB_FLAG_INCLUDE_PAC); /* Map principals from foreign (possibly non-AD) realms */ setflag(c_flags, KRB5_KDB_FLAG_MAP_PRINCIPALS); assert(client == NULL); /* should not have been set already */ errcode = krb5_db_get_principal(kdc_context, subject_tkt->client, c_flags, &client); } } if (isflagset(c_flags, KRB5_KDB_FLAG_PROTOCOL_TRANSITION) && !isflagset(c_flags, KRB5_KDB_FLAG_CROSS_REALM)) enc_tkt_reply.client = s4u_x509_user->user_id.user; else enc_tkt_reply.client = subject_tkt->client; enc_tkt_reply.session = &session_key; enc_tkt_reply.transited.tr_type = KRB5_DOMAIN_X500_COMPRESS; enc_tkt_reply.transited.tr_contents = empty_string; /* equivalent of "" */ errcode = handle_authdata(kdc_context, c_flags, client, server, krbtgt, subkey != NULL ? subkey : header_ticket->enc_part2->session, &encrypting_key, /* U2U or server key */ tgskey, pkt, request, s4u_x509_user ? s4u_x509_user->user_id.user : NULL, subject_tkt, &enc_tkt_reply); if (errcode) { krb5_klog_syslog(LOG_INFO, _("TGS_REQ : handle_authdata (%d)"), errcode); status = "HANDLE_AUTHDATA"; goto cleanup; } /* * Only add the realm of the presented tgt to the transited list if * it is different than the local realm (cross-realm) and it is different * than the realm of the client (since the realm of the client is already * implicitly part of the transited list and should not be explicitly * listed). */ /* realm compare is like strcmp, but knows how to deal with these args */ if (krb5_realm_compare(kdc_context, header_ticket->server, tgs_server) || krb5_realm_compare(kdc_context, header_ticket->server, enc_tkt_reply.client)) { /* tgt issued by local realm or issued by realm of client */ enc_tkt_reply.transited = header_enc_tkt->transited; } else { /* tgt issued by some other realm and not the realm of the client */ /* assemble new transited field into allocated storage */ if (header_enc_tkt->transited.tr_type != KRB5_DOMAIN_X500_COMPRESS) { status = "BAD_TRTYPE"; errcode = KRB5KDC_ERR_TRTYPE_NOSUPP; goto cleanup; } enc_tkt_transited.tr_type = KRB5_DOMAIN_X500_COMPRESS; enc_tkt_transited.magic = 0; enc_tkt_transited.tr_contents.magic = 0; enc_tkt_transited.tr_contents.data = 0; enc_tkt_transited.tr_contents.length = 0; enc_tkt_reply.transited = enc_tkt_transited; if ((errcode = add_to_transited(&header_enc_tkt->transited.tr_contents, &enc_tkt_reply.transited.tr_contents, header_ticket->server, enc_tkt_reply.client, request->server))) { status = "ADD_TR_FAIL"; goto cleanup; } newtransited = 1; } if (isflagset(c_flags, KRB5_KDB_FLAG_CROSS_REALM)) { errcode = validate_transit_path(kdc_context, header_enc_tkt->client, server, krbtgt); if (errcode) { status = "NON_TRANSITIVE"; goto cleanup; } } if (!isflagset (request->kdc_options, KDC_OPT_DISABLE_TRANSITED_CHECK)) { errcode = kdc_check_transited_list (kdc_active_realm, &enc_tkt_reply.transited.tr_contents, krb5_princ_realm (kdc_context, header_enc_tkt->client), krb5_princ_realm (kdc_context, request->server)); if (errcode == 0) { setflag (enc_tkt_reply.flags, TKT_FLG_TRANSIT_POLICY_CHECKED); } else { log_tgs_badtrans(kdc_context, cprinc, sprinc, &enc_tkt_reply.transited.tr_contents, errcode); } } else krb5_klog_syslog(LOG_INFO, _("not checking transit path")); if (reject_bad_transit && !isflagset (enc_tkt_reply.flags, TKT_FLG_TRANSIT_POLICY_CHECKED)) { errcode = KRB5KDC_ERR_POLICY; status = "BAD_TRANSIT"; goto cleanup; } ticket_reply.enc_part2 = &enc_tkt_reply; /* * If we are doing user-to-user authentication, then make sure * that the client for the second ticket matches the request * server, and then encrypt the ticket using the session key of * the second ticket. */ if (isflagset(request->kdc_options, KDC_OPT_ENC_TKT_IN_SKEY)) { /* * Make sure the client for the second ticket matches * requested server. */ krb5_enc_tkt_part *t2enc = request->second_ticket[st_idx]->enc_part2; krb5_principal client2 = t2enc->client; if (!krb5_principal_compare(kdc_context, request->server, client2)) { altcprinc = client2; errcode = KRB5KDC_ERR_SERVER_NOMATCH; status = "2ND_TKT_MISMATCH"; goto cleanup; } ticket_kvno = 0; ticket_reply.enc_part.enctype = t2enc->session->enctype; st_idx++; } else { ticket_kvno = server_key->key_data_kvno; } errcode = krb5_encrypt_tkt_part(kdc_context, &encrypting_key, &ticket_reply); if (!isflagset(request->kdc_options, KDC_OPT_ENC_TKT_IN_SKEY)) krb5_free_keyblock_contents(kdc_context, &encrypting_key); if (errcode) { status = "TKT_ENCRYPT"; goto cleanup; } ticket_reply.enc_part.kvno = ticket_kvno; /* Start assembling the response */ reply.msg_type = KRB5_TGS_REP; if (isflagset(c_flags, KRB5_KDB_FLAG_PROTOCOL_TRANSITION) && krb5int_find_pa_data(kdc_context, request->padata, KRB5_PADATA_S4U_X509_USER) != NULL) { errcode = kdc_make_s4u2self_rep(kdc_context, subkey, header_ticket->enc_part2->session, s4u_x509_user, &reply, &reply_encpart); if (errcode) { status = "KDC_RETURN_S4U2SELF_PADATA"; goto cleanup; } } reply.client = enc_tkt_reply.client; reply.enc_part.kvno = 0;/* We are using the session key */ reply.ticket = &ticket_reply; reply_encpart.session = &session_key; reply_encpart.nonce = request->nonce; /* copy the time fields */ reply_encpart.times = enc_tkt_reply.times; /* starttime is optional, and treated as authtime if not present. so we can nuke it if it matches */ if (enc_tkt_reply.times.starttime == enc_tkt_reply.times.authtime) enc_tkt_reply.times.starttime = 0; nolrentry.lr_type = KRB5_LRQ_NONE; nolrentry.value = 0; nolrarray[0] = &nolrentry; nolrarray[1] = 0; reply_encpart.last_req = nolrarray; /* not available for TGS reqs */ reply_encpart.key_exp = 0;/* ditto */ reply_encpart.flags = enc_tkt_reply.flags; reply_encpart.server = ticket_reply.server; /* use the session key in the ticket, unless there's a subsession key in the AP_REQ */ reply.enc_part.enctype = subkey ? subkey->enctype : header_ticket->enc_part2->session->enctype; errcode = kdc_fast_response_handle_padata(state, request, &reply, subkey ? subkey->enctype : header_ticket->enc_part2->session->enctype); if (errcode !=0 ) { status = "Preparing FAST padata"; goto cleanup; } errcode =kdc_fast_handle_reply_key(state, subkey?subkey:header_ticket->enc_part2->session, &reply_key); if (errcode) { status = "generating reply key"; goto cleanup; } errcode = return_enc_padata(kdc_context, pkt, request, reply_key, server, &reply_encpart, is_referral && isflagset(s_flags, KRB5_KDB_FLAG_CANONICALIZE)); if (errcode) { status = "KDC_RETURN_ENC_PADATA"; goto cleanup; } errcode = krb5_encode_kdc_rep(kdc_context, KRB5_TGS_REP, &reply_encpart, subkey ? 1 : 0, reply_key, &reply, response); if (errcode) { status = "ENCODE_KDC_REP"; } else { status = "ISSUE"; } memset(ticket_reply.enc_part.ciphertext.data, 0, ticket_reply.enc_part.ciphertext.length); free(ticket_reply.enc_part.ciphertext.data); /* these parts are left on as a courtesy from krb5_encode_kdc_rep so we can use them in raw form if needed. But, we don't... */ memset(reply.enc_part.ciphertext.data, 0, reply.enc_part.ciphertext.length); free(reply.enc_part.ciphertext.data); cleanup: assert(status != NULL); if (reply_key) krb5_free_keyblock(kdc_context, reply_key); if (errcode) emsg = krb5_get_error_message (kdc_context, errcode); log_tgs_req(kdc_context, from, request, &reply, cprinc, sprinc, altcprinc, authtime, c_flags, status, errcode, emsg); if (errcode) { krb5_free_error_message (kdc_context, emsg); emsg = NULL; } if (errcode) { int got_err = 0; if (status == 0) { status = krb5_get_error_message (kdc_context, errcode); got_err = 1; } errcode -= ERROR_TABLE_BASE_krb5; if (errcode < 0 || errcode > 128) errcode = KRB_ERR_GENERIC; retval = prepare_error_tgs(state, request, header_ticket, errcode, (server != NULL) ? server->princ : NULL, response, status, e_data); if (got_err) { krb5_free_error_message (kdc_context, status); status = 0; } } if (header_ticket != NULL) krb5_free_ticket(kdc_context, header_ticket); if (request != NULL) krb5_free_kdc_req(kdc_context, request); if (state) kdc_free_rstate(state); krb5_db_free_principal(kdc_context, server); krb5_db_free_principal(kdc_context, krbtgt); krb5_db_free_principal(kdc_context, client); if (session_key.contents != NULL) krb5_free_keyblock_contents(kdc_context, &session_key); if (newtransited) free(enc_tkt_reply.transited.tr_contents.data); if (s4u_x509_user != NULL) krb5_free_pa_s4u_x509_user(kdc_context, s4u_x509_user); if (kdc_issued_auth_data != NULL) krb5_free_authdata(kdc_context, kdc_issued_auth_data); if (subkey != NULL) krb5_free_keyblock(kdc_context, subkey); if (tgskey != NULL) krb5_free_keyblock(kdc_context, tgskey); if (reply.padata) krb5_free_pa_data(kdc_context, reply.padata); if (reply_encpart.enc_padata) krb5_free_pa_data(kdc_context, reply_encpart.enc_padata); if (enc_tkt_reply.authorization_data != NULL) krb5_free_authdata(kdc_context, enc_tkt_reply.authorization_data); krb5_free_pa_data(kdc_context, e_data); return retval; } static krb5_error_code prepare_error_tgs (struct kdc_request_state *state, krb5_kdc_req *request, krb5_ticket *ticket, int error, krb5_principal canon_server, krb5_data **response, const char *status, krb5_pa_data **e_data) { krb5_error errpkt; krb5_error_code retval = 0; krb5_data *scratch, *e_data_asn1 = NULL, *fast_edata = NULL; kdc_realm_t *kdc_active_realm = state->realm_data; errpkt.ctime = request->nonce; errpkt.cusec = 0; if ((retval = krb5_us_timeofday(kdc_context, &errpkt.stime, &errpkt.susec))) return(retval); errpkt.error = error; errpkt.server = request->server; if (ticket && ticket->enc_part2) errpkt.client = ticket->enc_part2->client; else errpkt.client = NULL; errpkt.text.length = strlen(status); if (!(errpkt.text.data = strdup(status))) return ENOMEM; if (!(scratch = (krb5_data *)malloc(sizeof(*scratch)))) { free(errpkt.text.data); return ENOMEM; } if (e_data != NULL) { retval = encode_krb5_padata_sequence(e_data, &e_data_asn1); if (retval) { free(scratch); free(errpkt.text.data); return retval; } errpkt.e_data = *e_data_asn1; } else errpkt.e_data = empty_data(); if (state) { retval = kdc_fast_handle_error(kdc_context, state, request, e_data, &errpkt, &fast_edata); } if (retval) { free(scratch); free(errpkt.text.data); krb5_free_data(kdc_context, e_data_asn1); return retval; } if (fast_edata) errpkt.e_data = *fast_edata; retval = krb5_mk_error(kdc_context, &errpkt, scratch); free(errpkt.text.data); krb5_free_data(kdc_context, e_data_asn1); krb5_free_data(kdc_context, fast_edata); if (retval) free(scratch); else *response = scratch; return retval; } /* KDC options that require a second ticket */ #define STKT_OPTIONS (KDC_OPT_CNAME_IN_ADDL_TKT | KDC_OPT_ENC_TKT_IN_SKEY) /* * Get the key for the second ticket, if any, and decrypt it. */ static krb5_error_code decrypt_2ndtkt(kdc_realm_t *kdc_active_realm, krb5_kdc_req *req, krb5_flags flags, krb5_db_entry **server_out, const char **status) { krb5_error_code retval; krb5_db_entry *server; krb5_keyblock *key; krb5_kvno kvno; krb5_ticket *stkt; if (!(req->kdc_options & STKT_OPTIONS)) return 0; stkt = req->second_ticket[0]; retval = kdc_get_server_key(kdc_context, stkt, flags, TRUE, /* match_enctype */ &server, &key, &kvno); if (retval != 0) { *status = "2ND_TKT_SERVER"; goto cleanup; } retval = krb5_decrypt_tkt_part(kdc_context, key, req->second_ticket[0]); krb5_free_keyblock(kdc_context, key); if (retval != 0) { *status = "2ND_TKT_DECRYPT"; goto cleanup; } *server_out = server; cleanup: return retval; } static krb5_error_code get_2ndtkt_enctype(kdc_realm_t *kdc_active_realm, krb5_kdc_req *req, krb5_enctype *useenctype, const char **status) { krb5_enctype etype; krb5_ticket *stkt = req->second_ticket[0]; int i; etype = stkt->enc_part2->session->enctype; if (!krb5_c_valid_enctype(etype)) { *status = "BAD_ETYPE_IN_2ND_TKT"; return KRB5KDC_ERR_ETYPE_NOSUPP; } for (i = 0; i < req->nktypes; i++) { if (req->ktype[i] == etype) { *useenctype = etype; break; } } return 0; } static krb5_error_code gen_session_key(kdc_realm_t *kdc_active_realm, krb5_kdc_req *req, krb5_db_entry *server, krb5_keyblock *skey, const char **status) { krb5_error_code retval; krb5_enctype useenctype = 0; /* * Some special care needs to be taken in the user-to-user * case, since we don't know what keytypes the application server * which is doing user-to-user authentication can support. We * know that it at least must be able to support the encryption * type of the session key in the TGT, since otherwise it won't be * able to decrypt the U2U ticket! So we use that in preference * to anything else. */ if (req->kdc_options & KDC_OPT_ENC_TKT_IN_SKEY) { retval = get_2ndtkt_enctype(kdc_active_realm, req, &useenctype, status); if (retval != 0) goto cleanup; } if (useenctype == 0) { useenctype = select_session_keytype(kdc_active_realm, server, req->nktypes, req->ktype); } if (useenctype == 0) { /* unsupported ktype */ *status = "BAD_ENCRYPTION_TYPE"; retval = KRB5KDC_ERR_ETYPE_NOSUPP; goto cleanup; } retval = krb5_c_make_random_key(kdc_context, useenctype, skey); if (retval != 0) { /* random key failed */ *status = "RANDOM_KEY_FAILED"; goto cleanup; } cleanup: return retval; } /* * The request seems to be for a ticket-granting service somewhere else, * but we don't have a ticket for the final TGS. Try to give the requestor * some intermediate realm. */ static krb5_error_code find_alternate_tgs(kdc_realm_t *kdc_active_realm, krb5_principal princ, krb5_db_entry **server_ptr, const char **status) { krb5_error_code retval; krb5_principal *plist = NULL, *pl2; krb5_data tmp; krb5_db_entry *server = NULL; *server_ptr = NULL; assert(is_cross_tgs_principal(princ)); if ((retval = krb5_walk_realm_tree(kdc_context, krb5_princ_realm(kdc_context, princ), krb5_princ_component(kdc_context, princ, 1), &plist, KRB5_REALM_BRANCH_CHAR))) { goto cleanup; } /* move to the end */ for (pl2 = plist; *pl2; pl2++); /* the first entry in this array is for krbtgt/local@local, so we ignore it */ while (--pl2 > plist) { tmp = *krb5_princ_realm(kdc_context, *pl2); krb5_princ_set_realm(kdc_context, *pl2, krb5_princ_realm(kdc_context, tgs_server)); retval = db_get_svc_princ(kdc_context, *pl2, 0, &server, status); krb5_princ_set_realm(kdc_context, *pl2, &tmp); if (retval == KRB5_KDB_NOENTRY) continue; else if (retval) goto cleanup; log_tgs_alt_tgt(kdc_context, server->princ); *server_ptr = server; server = NULL; goto cleanup; } cleanup: if (retval == 0 && server_ptr == NULL) retval = KRB5_KDB_NOENTRY; if (retval != 0) *status = "UNKNOWN_SERVER"; krb5_free_realm_tree(kdc_context, plist); krb5_db_free_principal(kdc_context, server); return retval; } /* * Check whether the request satisfies the conditions for generating a referral * TGT. The caller checks whether the hostname component looks like a FQDN. */ static krb5_boolean is_referral_req(kdc_realm_t *kdc_active_realm, krb5_kdc_req *request) { krb5_boolean ret = FALSE; char *stype = NULL; char *ref_services = kdc_active_realm->realm_host_based_services; char *nonref_services = kdc_active_realm->realm_no_host_referral; if (!(request->kdc_options & KDC_OPT_CANONICALIZE)) return FALSE; if (request->kdc_options & KDC_OPT_ENC_TKT_IN_SKEY) return FALSE; if (krb5_princ_size(kdc_context, request->server) != 2) return FALSE; stype = data2string(krb5_princ_component(kdc_context, request->server, 0)); if (stype == NULL) return FALSE; switch (krb5_princ_type(kdc_context, request->server)) { case KRB5_NT_UNKNOWN: /* Allow referrals for NT-UNKNOWN principals, if configured. */ if (kdc_active_realm->realm_host_based_services != NULL) { if (!krb5_match_config_pattern(ref_services, stype) && !krb5_match_config_pattern(ref_services, KRB5_CONF_ASTERISK)) goto cleanup; } else goto cleanup; /* FALLTHROUGH */ case KRB5_NT_SRV_HST: case KRB5_NT_SRV_INST: /* Deny referrals for specific service types, if configured. */ if (kdc_active_realm->realm_no_host_referral != NULL) { if (krb5_match_config_pattern(nonref_services, stype)) goto cleanup; if (krb5_match_config_pattern(nonref_services, KRB5_CONF_ASTERISK)) goto cleanup; } ret = TRUE; break; default: goto cleanup; } cleanup: free(stype); return ret; } /* * Find a remote realm TGS principal for an unknown host-based service * principal. */ static krb5_int32 find_referral_tgs(kdc_realm_t *kdc_active_realm, krb5_kdc_req *request, krb5_principal *krbtgt_princ) { krb5_error_code retval = KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN; char **realms = NULL, *hostname = NULL; krb5_data srealm = request->server->realm; if (!is_referral_req(kdc_active_realm, request)) goto cleanup; hostname = data2string(krb5_princ_component(kdc_context, request->server, 1)); if (hostname == NULL) { retval = ENOMEM; goto cleanup; } /* If the hostname doesn't contain a '.', it's not a FQDN. */ if (strchr(hostname, '.') == NULL) goto cleanup; retval = krb5_get_host_realm(kdc_context, hostname, &realms); if (retval) { /* no match found */ kdc_err(kdc_context, retval, "unable to find realm of host"); goto cleanup; } /* Don't return a referral to the empty realm or the service realm. */ if (realms == NULL || realms[0] == NULL || *realms[0] == '\0' || data_eq_string(srealm, realms[0])) { retval = KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN; goto cleanup; } retval = krb5_build_principal(kdc_context, krbtgt_princ, srealm.length, srealm.data, "krbtgt", realms[0], (char *)0); cleanup: krb5_free_host_realm(kdc_context, realms); free(hostname); return retval; } static krb5_error_code db_get_svc_princ(krb5_context ctx, krb5_principal princ, krb5_flags flags, krb5_db_entry **server, const char **status) { krb5_error_code ret; ret = krb5_db_get_principal(ctx, princ, flags, server); if (ret == KRB5_KDB_CANTLOCK_DB) ret = KRB5KDC_ERR_SVC_UNAVAILABLE; if (ret != 0) { *status = "LOOKING_UP_SERVER"; } return ret; } static krb5_error_code search_sprinc(kdc_realm_t *kdc_active_realm, krb5_kdc_req *req, krb5_flags flags, krb5_db_entry **server, const char **status) { krb5_error_code ret; krb5_principal princ = req->server; krb5_principal reftgs = NULL; ret = db_get_svc_princ(kdc_context, princ, flags, server, status); if (ret == 0 || ret != KRB5_KDB_NOENTRY) goto cleanup; if (!is_cross_tgs_principal(req->server)) { ret = find_referral_tgs(kdc_active_realm, req, &reftgs); if (ret != 0) goto cleanup; ret = db_get_svc_princ(kdc_context, reftgs, flags, server, status); if (ret == 0 || ret != KRB5_KDB_NOENTRY) goto cleanup; princ = reftgs; } ret = find_alternate_tgs(kdc_active_realm, princ, server, status); cleanup: if (ret != 0 && ret != KRB5KDC_ERR_SVC_UNAVAILABLE) { ret = KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN; if (*status == NULL) *status = "LOOKING_UP_SERVER"; } krb5_free_principal(kdc_context, reftgs); return ret; }
./CrossVul/dataset_final_sorted/CWE-20/c/good_5576_0
crossvul-cpp_data_bad_2253_2
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* Monkey HTTP Server * ================== * Copyright 2001-2014 Monkey Software LLC <eduardo@monkey.io> * * 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 <sys/types.h> #include <sys/stat.h> #include <sys/types.h> #include <dirent.h> #include <unistd.h> #include <pthread.h> #include <fcntl.h> #include <monkey/mk_list.h> #include <monkey/mk_vhost.h> #include <monkey/mk_utils.h> #include <monkey/mk_macros.h> #include <monkey/mk_config.h> #include <monkey/mk_string.h> #include <monkey/mk_http_status.h> #include <monkey/mk_memory.h> #include <monkey/mk_request.h> #include <monkey/mk_info.h> #include <monkey/mk_file.h> /* Initialize Virtual Host FDT mutex */ pthread_mutex_t mk_vhost_fdt_mutex = PTHREAD_MUTEX_INITIALIZER; static __thread struct mk_list *mk_vhost_fdt_key; /* * This function is triggered upon thread creation (inside the thread * context), here we configure per-thread data. */ int mk_vhost_fdt_worker_init() { int i; int j; struct host *h; struct mk_list *list; struct mk_list *head; struct vhost_fdt_host *fdt; struct vhost_fdt_hash_table *ht; struct vhost_fdt_hash_chain *hc; if (config->fdt == MK_FALSE) { return -1; } /* * We are under a thread context and the main configuration is * already in place. Now for every existent virtual host we are * going to create the File Descriptor Table (FDT) which aims to * hold references of 'open and shared' file descriptors under * the Virtual Host context. */ /* * Under an initialization context we need to protect this critical * section */ pthread_mutex_lock(&mk_vhost_fdt_mutex); /* * Initialize the thread FDT/Hosts list and create an entry per * existent virtual host */ list = mk_mem_malloc_z(sizeof(struct mk_list)); mk_list_init(list); mk_list_foreach(head, &config->hosts) { h = mk_list_entry(head, struct host, _head); fdt = mk_mem_malloc(sizeof(struct vhost_fdt_host)); fdt->host = h; /* Initialize hash table */ for (i = 0; i < VHOST_FDT_HASHTABLE_SIZE; i++) { ht = &fdt->hash_table[i]; ht->av_slots = VHOST_FDT_HASHTABLE_CHAINS; /* for each chain under the hash table, set the fd */ for (j = 0; j < VHOST_FDT_HASHTABLE_CHAINS; j++) { hc = &ht->chain[j]; hc->fd = -1; hc->hash = 0; hc->readers = 0; } } mk_list_add(&fdt->_head, list); } mk_vhost_fdt_key = list; pthread_mutex_unlock(&mk_vhost_fdt_mutex); return 0; } int mk_vhost_fdt_worker_exit() { struct mk_list *head; struct mk_list *tmp; struct vhost_fdt_host *fdt; if (config->fdt == MK_FALSE) { return -1; } mk_list_foreach_safe(head, tmp, mk_vhost_fdt_key) { fdt = mk_list_entry(head, struct vhost_fdt_host, _head); mk_list_del(&fdt->_head); mk_mem_free(fdt); } mk_mem_free(mk_vhost_fdt_key); return 0; } static inline struct vhost_fdt_hash_table *mk_vhost_fdt_table_lookup(int id, struct host *host) { struct mk_list *head; struct mk_list *vhost_list; struct vhost_fdt_host *fdt_host; struct vhost_fdt_hash_table *ht = NULL; vhost_list = mk_vhost_fdt_key; mk_list_foreach(head, vhost_list) { fdt_host = mk_list_entry(head, struct vhost_fdt_host, _head); if (fdt_host->host == host) { ht = &fdt_host->hash_table[id]; return ht; } } return ht; } static inline struct vhost_fdt_hash_chain *mk_vhost_fdt_chain_lookup(unsigned int hash, struct vhost_fdt_hash_table *ht) { int i; struct vhost_fdt_hash_chain *hc = NULL; for (i = 0; i < VHOST_FDT_HASHTABLE_CHAINS; i++) { hc = &ht->chain[i]; if (hc->hash == hash) { return hc; } } return NULL; } static inline int mk_vhost_fdt_open(int id, unsigned int hash, struct session_request *sr) { int i; int fd; struct vhost_fdt_hash_table *ht = NULL; struct vhost_fdt_hash_chain *hc; if (config->fdt == MK_FALSE) { return open(sr->real_path.data, sr->file_info.flags_read_only); } ht = mk_vhost_fdt_table_lookup(id, sr->host_conf); if (mk_unlikely(!ht)) { return open(sr->real_path.data, sr->file_info.flags_read_only); } /* We got the hash table, now look around the chains array */ hc = mk_vhost_fdt_chain_lookup(hash, ht); if (hc) { /* Increment the readers and return the shared FD */ hc->readers++; return hc->fd; } /* * Get here means that no entry exists in the hash table for the * requested file descriptor and hash, we must try to open the file * and register the entry in the table. */ fd = open(sr->real_path.data, sr->file_info.flags_read_only); if (fd == -1) { return -1; } /* If chains are full, just return the new FD, bad luck... */ if (ht->av_slots <= 0) { return fd; } /* Register the new entry in an available slot */ for (i = 0; i < VHOST_FDT_HASHTABLE_CHAINS; i++) { hc = &ht->chain[i]; if (hc->fd == -1) { hc->fd = fd; hc->hash = hash; hc->readers++; ht->av_slots--; sr->vhost_fdt_id = id; sr->vhost_fdt_hash = hash; return fd; } } return -1; } static inline int mk_vhost_fdt_close(struct session_request *sr) { int id; unsigned int hash; struct vhost_fdt_hash_table *ht = NULL; struct vhost_fdt_hash_chain *hc; if (config->fdt == MK_FALSE) { return close(sr->fd_file); } id = sr->vhost_fdt_id; hash = sr->vhost_fdt_hash; ht = mk_vhost_fdt_table_lookup(id, sr->host_conf); if (mk_unlikely(!ht)) { return close(sr->fd_file); } /* We got the hash table, now look around the chains array */ hc = mk_vhost_fdt_chain_lookup(hash, ht); if (hc) { /* Increment the readers and check if we should close */ hc->readers--; if (hc->readers == 0) { hc->fd = -1; hc->hash = 0; ht->av_slots++; return close(sr->fd_file); } else { return 0; } } return close(sr->fd_file); } int mk_vhost_open(struct session_request *sr) { int id; int off; unsigned int hash; off = sr->host_conf->documentroot.len; hash = mk_utils_gen_hash(sr->real_path.data + off, sr->real_path.len - off); id = (hash % VHOST_FDT_HASHTABLE_SIZE); return mk_vhost_fdt_open(id, hash, sr); } int mk_vhost_close(struct session_request *sr) { return mk_vhost_fdt_close(sr); } /* * Open a virtual host configuration file and return a structure with * definitions. */ struct host *mk_vhost_read(char *path) { unsigned long len = 0; char *tmp; char *host_low; struct stat checkdir; struct host *host; struct host_alias *new_alias; struct error_page *err_page; struct mk_config *cnf; struct mk_config_section *section_host; struct mk_config_section *section_ep; struct mk_config_entry *entry_ep; struct mk_string_line *entry; struct mk_list *head, *list; /* Read configuration file */ cnf = mk_config_create(path); if (!cnf) { mk_err("Configuration error, aborting."); exit(EXIT_FAILURE); } /* Read tag 'HOST' */ section_host = mk_config_section_get(cnf, "HOST"); if (!section_host) { mk_err("Invalid config file %s", path); return NULL; } /* Alloc configuration node */ host = mk_mem_malloc_z(sizeof(struct host)); host->config = cnf; host->file = mk_string_dup(path); /* Init list for custom error pages */ mk_list_init(&host->error_pages); /* Init list for host name aliases */ mk_list_init(&host->server_names); /* Lookup Servername */ list = mk_config_section_getval(section_host, "Servername", MK_CONFIG_VAL_LIST); if (!list) { mk_err("Hostname does not contain a Servername"); exit(EXIT_FAILURE); } mk_list_foreach(head, list) { entry = mk_list_entry(head, struct mk_string_line, _head); if (entry->len > MK_HOSTNAME_LEN - 1) { continue; } /* Hostname to lowercase */ host_low = mk_string_tolower(entry->val); /* Alloc node */ new_alias = mk_mem_malloc_z(sizeof(struct host_alias)); new_alias->name = mk_mem_malloc_z(entry->len + 1); strncpy(new_alias->name, host_low, entry->len); mk_mem_free(host_low); new_alias->len = entry->len; mk_list_add(&new_alias->_head, &host->server_names); } mk_string_split_free(list); /* Lookup document root handled by a mk_ptr_t */ host->documentroot.data = mk_config_section_getval(section_host, "DocumentRoot", MK_CONFIG_VAL_STR); if (!host->documentroot.data) { mk_err("Missing DocumentRoot entry on %s file", path); mk_config_free(cnf); return NULL; } host->documentroot.len = strlen(host->documentroot.data); /* Validate document root configured */ if (stat(host->documentroot.data, &checkdir) == -1) { mk_err("Invalid path to DocumentRoot in %s", path); } else if (!(checkdir.st_mode & S_IFDIR)) { mk_err("DocumentRoot variable in %s has an invalid directory path", path); } if (mk_list_is_empty(&host->server_names) == 0) { mk_config_free(cnf); return NULL; } /* Check Virtual Host redirection */ host->header_redirect.data = NULL; host->header_redirect.len = 0; tmp = mk_config_section_getval(section_host, "Redirect", MK_CONFIG_VAL_STR); if (tmp) { host->header_redirect.data = mk_string_dup(tmp); host->header_redirect.len = strlen(tmp); mk_mem_free(tmp); } /* Error Pages */ section_ep = mk_config_section_get(cnf, "ERROR_PAGES"); if (section_ep) { mk_list_foreach(head, &section_ep->entries) { entry_ep = mk_list_entry(head, struct mk_config_entry, _head); int ep_status = -1; char *ep_file = NULL; unsigned long len; ep_status = atoi(entry_ep->key); ep_file = entry_ep->val; /* Validate input values */ if (ep_status < MK_CLIENT_BAD_REQUEST || ep_status > MK_SERVER_HTTP_VERSION_UNSUP || ep_file == NULL) { continue; } /* Alloc error page node */ err_page = mk_mem_malloc_z(sizeof(struct error_page)); err_page->status = ep_status; err_page->file = mk_string_dup(ep_file); err_page->real_path = NULL; mk_string_build(&err_page->real_path, &len, "%s/%s", host->documentroot.data, err_page->file); MK_TRACE("Map error page: status %i -> %s", err_page->status, err_page->file); /* Link page to the error page list */ mk_list_add(&err_page->_head, &host->error_pages); } } /* Server Signature */ if (config->hideversion == MK_FALSE) { mk_string_build(&host->host_signature, &len, "Monkey/%s", VERSION); } else { mk_string_build(&host->host_signature, &len, "Monkey"); } mk_string_build(&host->header_host_signature.data, &host->header_host_signature.len, "Server: %s", host->host_signature); return host; } void mk_vhost_set_single(char *path) { struct host *host; struct host_alias *halias; struct stat checkdir; unsigned long len = 0; /* Set the default host */ host = mk_mem_malloc_z(sizeof(struct host)); mk_list_init(&host->error_pages); mk_list_init(&host->server_names); /* Prepare the unique alias */ halias = mk_mem_malloc_z(sizeof(struct host_alias)); halias->name = mk_string_dup("127.0.0.1"); mk_list_add(&halias->_head, &host->server_names); host->documentroot.data = mk_string_dup(path); host->documentroot.len = strlen(path); host->header_redirect.data = NULL; /* Validate document root configured */ if (stat(host->documentroot.data, &checkdir) == -1) { mk_err("Invalid path to DocumentRoot in %s", path); exit(EXIT_FAILURE); } else if (!(checkdir.st_mode & S_IFDIR)) { mk_err("DocumentRoot variable in %s has an invalid directory path", path); exit(EXIT_FAILURE); } /* Server Signature */ if (config->hideversion == MK_FALSE) { mk_string_build(&host->host_signature, &len, "Monkey/%s", VERSION); } else { mk_string_build(&host->host_signature, &len, "Monkey"); } mk_string_build(&host->header_host_signature.data, &host->header_host_signature.len, "Server: %s", host->host_signature); mk_list_add(&host->_head, &config->hosts); } /* Given a configuration directory, start reading the virtual host entries */ void mk_vhost_init(char *path) { DIR *dir; unsigned long len; char *buf = 0; char *sites = 0; char *file; struct host *p_host; /* debug */ struct dirent *ent; struct file_info f_info; int ret; /* Read default virtual host file */ mk_string_build(&sites, &len, "%s/%s/", path, config->sites_conf_dir); ret = mk_file_get_info(sites, &f_info); if (ret == -1 || f_info.is_directory == MK_FALSE) { mk_mem_free(sites); sites = config->sites_conf_dir; } mk_string_build(&buf, &len, "%s/default", sites); p_host = mk_vhost_read(buf); if (!p_host) { mk_err("Error parsing main configuration file 'default'"); } mk_list_add(&p_host->_head, &config->hosts); config->nhosts++; mk_mem_free(buf); buf = NULL; /* Read all virtual hosts defined in sites/ */ if (!(dir = opendir(sites))) { mk_mem_free(sites); mk_err("Could not open %s", sites); exit(EXIT_FAILURE); } /* Reading content */ while ((ent = readdir(dir)) != NULL) { if (ent->d_name[0] == '.') { continue; } if (strcmp((char *) ent->d_name, "..") == 0) { continue; } if (ent->d_name[strlen(ent->d_name) - 1] == '~') { continue; } if (strcasecmp((char *) ent->d_name, "default") == 0) { continue; } file = NULL; mk_string_build(&file, &len, "%s/%s", sites, ent->d_name); p_host = mk_vhost_read(file); mk_mem_free(file); if (!p_host) { continue; } else { mk_list_add(&p_host->_head, &config->hosts); config->nhosts++; } } closedir(dir); mk_mem_free(sites); } /* Lookup a registered virtual host based on the given 'host' input */ int mk_vhost_get(mk_ptr_t host, struct host **vhost, struct host_alias **alias) { struct host *entry_host; struct host_alias *entry_alias; struct mk_list *head_vhost, *head_alias; mk_list_foreach(head_vhost, &config->hosts) { entry_host = mk_list_entry(head_vhost, struct host, _head); mk_list_foreach(head_alias, &entry_host->server_names) { entry_alias = mk_list_entry(head_alias, struct host_alias, _head); if (entry_alias->len == host.len && strncmp(entry_alias->name, host.data, host.len) == 0) { *vhost = entry_host; *alias = entry_alias; return 0; } } } return -1; } void mk_vhost_free_all() { struct host *host; struct host_alias *host_alias; struct error_page *ep; struct mk_list *head_host; struct mk_list *head_alias; struct mk_list *head_error; struct mk_list *tmp1, *tmp2; mk_list_foreach_safe(head_host, tmp1, &config->hosts) { host = mk_list_entry(head_host, struct host, _head); mk_list_del(&host->_head); mk_mem_free(host->file); /* Free aliases or servernames */ mk_list_foreach_safe(head_alias, tmp2, &host->server_names) { host_alias = mk_list_entry(head_alias, struct host_alias, _head); mk_list_del(&host_alias->_head); mk_mem_free(host_alias->name); mk_mem_free(host_alias); } /* Free error pages */ mk_list_foreach_safe(head_error, tmp2, &host->error_pages) { ep = mk_list_entry(head_error, struct error_page, _head); mk_list_del(&ep->_head); mk_mem_free(ep->file); mk_mem_free(ep->real_path); mk_mem_free(ep); } mk_ptr_free(&host->documentroot); mk_mem_free(host->host_signature); mk_ptr_free(&host->header_host_signature); /* Free source configuration */ if (host->config) mk_config_free(host->config); mk_mem_free(host); } }
./CrossVul/dataset_final_sorted/CWE-20/c/bad_2253_2
crossvul-cpp_data_bad_3547_3
/* * 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. * * Copyright (C) Jonathan Naylor G4KLX (g4klx@g4klx.demon.co.uk) * Copyright (C) Terry Dawson VK2KTJ (terry@animats.net) */ #include <linux/errno.h> #include <linux/types.h> #include <linux/socket.h> #include <linux/in.h> #include <linux/kernel.h> #include <linux/timer.h> #include <linux/string.h> #include <linux/sockios.h> #include <linux/net.h> #include <linux/slab.h> #include <net/ax25.h> #include <linux/inet.h> #include <linux/netdevice.h> #include <net/arp.h> #include <linux/if_arp.h> #include <linux/skbuff.h> #include <net/sock.h> #include <net/tcp_states.h> #include <asm/system.h> #include <asm/uaccess.h> #include <linux/fcntl.h> #include <linux/termios.h> /* For TIOCINQ/OUTQ */ #include <linux/mm.h> #include <linux/interrupt.h> #include <linux/notifier.h> #include <linux/netfilter.h> #include <linux/init.h> #include <net/rose.h> #include <linux/seq_file.h> static unsigned int rose_neigh_no = 1; static struct rose_node *rose_node_list; static DEFINE_SPINLOCK(rose_node_list_lock); static struct rose_neigh *rose_neigh_list; static DEFINE_SPINLOCK(rose_neigh_list_lock); static struct rose_route *rose_route_list; static DEFINE_SPINLOCK(rose_route_list_lock); struct rose_neigh *rose_loopback_neigh; /* * Add a new route to a node, and in the process add the node and the * neighbour if it is new. */ static int __must_check rose_add_node(struct rose_route_struct *rose_route, struct net_device *dev) { struct rose_node *rose_node, *rose_tmpn, *rose_tmpp; struct rose_neigh *rose_neigh; int i, res = 0; spin_lock_bh(&rose_node_list_lock); spin_lock_bh(&rose_neigh_list_lock); rose_node = rose_node_list; while (rose_node != NULL) { if ((rose_node->mask == rose_route->mask) && (rosecmpm(&rose_route->address, &rose_node->address, rose_route->mask) == 0)) break; rose_node = rose_node->next; } if (rose_node != NULL && rose_node->loopback) { res = -EINVAL; goto out; } rose_neigh = rose_neigh_list; while (rose_neigh != NULL) { if (ax25cmp(&rose_route->neighbour, &rose_neigh->callsign) == 0 && rose_neigh->dev == dev) break; rose_neigh = rose_neigh->next; } if (rose_neigh == NULL) { rose_neigh = kmalloc(sizeof(*rose_neigh), GFP_ATOMIC); if (rose_neigh == NULL) { res = -ENOMEM; goto out; } rose_neigh->callsign = rose_route->neighbour; rose_neigh->digipeat = NULL; rose_neigh->ax25 = NULL; rose_neigh->dev = dev; rose_neigh->count = 0; rose_neigh->use = 0; rose_neigh->dce_mode = 0; rose_neigh->loopback = 0; rose_neigh->number = rose_neigh_no++; rose_neigh->restarted = 0; skb_queue_head_init(&rose_neigh->queue); init_timer(&rose_neigh->ftimer); init_timer(&rose_neigh->t0timer); if (rose_route->ndigis != 0) { rose_neigh->digipeat = kmalloc(sizeof(ax25_digi), GFP_ATOMIC); if (rose_neigh->digipeat == NULL) { kfree(rose_neigh); res = -ENOMEM; goto out; } rose_neigh->digipeat->ndigi = rose_route->ndigis; rose_neigh->digipeat->lastrepeat = -1; for (i = 0; i < rose_route->ndigis; i++) { rose_neigh->digipeat->calls[i] = rose_route->digipeaters[i]; rose_neigh->digipeat->repeated[i] = 0; } } rose_neigh->next = rose_neigh_list; rose_neigh_list = rose_neigh; } /* * This is a new node to be inserted into the list. Find where it needs * to be inserted into the list, and insert it. We want to be sure * to order the list in descending order of mask size to ensure that * later when we are searching this list the first match will be the * best match. */ if (rose_node == NULL) { rose_tmpn = rose_node_list; rose_tmpp = NULL; while (rose_tmpn != NULL) { if (rose_tmpn->mask > rose_route->mask) { rose_tmpp = rose_tmpn; rose_tmpn = rose_tmpn->next; } else { break; } } /* create new node */ rose_node = kmalloc(sizeof(*rose_node), GFP_ATOMIC); if (rose_node == NULL) { res = -ENOMEM; goto out; } rose_node->address = rose_route->address; rose_node->mask = rose_route->mask; rose_node->count = 1; rose_node->loopback = 0; rose_node->neighbour[0] = rose_neigh; if (rose_tmpn == NULL) { if (rose_tmpp == NULL) { /* Empty list */ rose_node_list = rose_node; rose_node->next = NULL; } else { rose_tmpp->next = rose_node; rose_node->next = NULL; } } else { if (rose_tmpp == NULL) { /* 1st node */ rose_node->next = rose_node_list; rose_node_list = rose_node; } else { rose_tmpp->next = rose_node; rose_node->next = rose_tmpn; } } rose_neigh->count++; goto out; } /* We have space, slot it in */ if (rose_node->count < 3) { rose_node->neighbour[rose_node->count] = rose_neigh; rose_node->count++; rose_neigh->count++; } out: spin_unlock_bh(&rose_neigh_list_lock); spin_unlock_bh(&rose_node_list_lock); return res; } /* * Caller is holding rose_node_list_lock. */ static void rose_remove_node(struct rose_node *rose_node) { struct rose_node *s; if ((s = rose_node_list) == rose_node) { rose_node_list = rose_node->next; kfree(rose_node); return; } while (s != NULL && s->next != NULL) { if (s->next == rose_node) { s->next = rose_node->next; kfree(rose_node); return; } s = s->next; } } /* * Caller is holding rose_neigh_list_lock. */ static void rose_remove_neigh(struct rose_neigh *rose_neigh) { struct rose_neigh *s; rose_stop_ftimer(rose_neigh); rose_stop_t0timer(rose_neigh); skb_queue_purge(&rose_neigh->queue); if ((s = rose_neigh_list) == rose_neigh) { rose_neigh_list = rose_neigh->next; if (rose_neigh->ax25) ax25_cb_put(rose_neigh->ax25); kfree(rose_neigh->digipeat); kfree(rose_neigh); return; } while (s != NULL && s->next != NULL) { if (s->next == rose_neigh) { s->next = rose_neigh->next; if (rose_neigh->ax25) ax25_cb_put(rose_neigh->ax25); kfree(rose_neigh->digipeat); kfree(rose_neigh); return; } s = s->next; } } /* * Caller is holding rose_route_list_lock. */ static void rose_remove_route(struct rose_route *rose_route) { struct rose_route *s; if (rose_route->neigh1 != NULL) rose_route->neigh1->use--; if (rose_route->neigh2 != NULL) rose_route->neigh2->use--; if ((s = rose_route_list) == rose_route) { rose_route_list = rose_route->next; kfree(rose_route); return; } while (s != NULL && s->next != NULL) { if (s->next == rose_route) { s->next = rose_route->next; kfree(rose_route); return; } s = s->next; } } /* * "Delete" a node. Strictly speaking remove a route to a node. The node * is only deleted if no routes are left to it. */ static int rose_del_node(struct rose_route_struct *rose_route, struct net_device *dev) { struct rose_node *rose_node; struct rose_neigh *rose_neigh; int i, err = 0; spin_lock_bh(&rose_node_list_lock); spin_lock_bh(&rose_neigh_list_lock); rose_node = rose_node_list; while (rose_node != NULL) { if ((rose_node->mask == rose_route->mask) && (rosecmpm(&rose_route->address, &rose_node->address, rose_route->mask) == 0)) break; rose_node = rose_node->next; } if (rose_node == NULL || rose_node->loopback) { err = -EINVAL; goto out; } rose_neigh = rose_neigh_list; while (rose_neigh != NULL) { if (ax25cmp(&rose_route->neighbour, &rose_neigh->callsign) == 0 && rose_neigh->dev == dev) break; rose_neigh = rose_neigh->next; } if (rose_neigh == NULL) { err = -EINVAL; goto out; } for (i = 0; i < rose_node->count; i++) { if (rose_node->neighbour[i] == rose_neigh) { rose_neigh->count--; if (rose_neigh->count == 0 && rose_neigh->use == 0) rose_remove_neigh(rose_neigh); rose_node->count--; if (rose_node->count == 0) { rose_remove_node(rose_node); } else { switch (i) { case 0: rose_node->neighbour[0] = rose_node->neighbour[1]; case 1: rose_node->neighbour[1] = rose_node->neighbour[2]; case 2: break; } } goto out; } } err = -EINVAL; out: spin_unlock_bh(&rose_neigh_list_lock); spin_unlock_bh(&rose_node_list_lock); return err; } /* * Add the loopback neighbour. */ void rose_add_loopback_neigh(void) { struct rose_neigh *sn; rose_loopback_neigh = kmalloc(sizeof(struct rose_neigh), GFP_KERNEL); if (!rose_loopback_neigh) return; sn = rose_loopback_neigh; sn->callsign = null_ax25_address; sn->digipeat = NULL; sn->ax25 = NULL; sn->dev = NULL; sn->count = 0; sn->use = 0; sn->dce_mode = 1; sn->loopback = 1; sn->number = rose_neigh_no++; sn->restarted = 1; skb_queue_head_init(&sn->queue); init_timer(&sn->ftimer); init_timer(&sn->t0timer); spin_lock_bh(&rose_neigh_list_lock); sn->next = rose_neigh_list; rose_neigh_list = sn; spin_unlock_bh(&rose_neigh_list_lock); } /* * Add a loopback node. */ int rose_add_loopback_node(rose_address *address) { struct rose_node *rose_node; int err = 0; spin_lock_bh(&rose_node_list_lock); rose_node = rose_node_list; while (rose_node != NULL) { if ((rose_node->mask == 10) && (rosecmpm(address, &rose_node->address, 10) == 0) && rose_node->loopback) break; rose_node = rose_node->next; } if (rose_node != NULL) goto out; if ((rose_node = kmalloc(sizeof(*rose_node), GFP_ATOMIC)) == NULL) { err = -ENOMEM; goto out; } rose_node->address = *address; rose_node->mask = 10; rose_node->count = 1; rose_node->loopback = 1; rose_node->neighbour[0] = rose_loopback_neigh; /* Insert at the head of list. Address is always mask=10 */ rose_node->next = rose_node_list; rose_node_list = rose_node; rose_loopback_neigh->count++; out: spin_unlock_bh(&rose_node_list_lock); return err; } /* * Delete a loopback node. */ void rose_del_loopback_node(rose_address *address) { struct rose_node *rose_node; spin_lock_bh(&rose_node_list_lock); rose_node = rose_node_list; while (rose_node != NULL) { if ((rose_node->mask == 10) && (rosecmpm(address, &rose_node->address, 10) == 0) && rose_node->loopback) break; rose_node = rose_node->next; } if (rose_node == NULL) goto out; rose_remove_node(rose_node); rose_loopback_neigh->count--; out: spin_unlock_bh(&rose_node_list_lock); } /* * A device has been removed. Remove its routes and neighbours. */ void rose_rt_device_down(struct net_device *dev) { struct rose_neigh *s, *rose_neigh; struct rose_node *t, *rose_node; int i; spin_lock_bh(&rose_node_list_lock); spin_lock_bh(&rose_neigh_list_lock); rose_neigh = rose_neigh_list; while (rose_neigh != NULL) { s = rose_neigh; rose_neigh = rose_neigh->next; if (s->dev != dev) continue; rose_node = rose_node_list; while (rose_node != NULL) { t = rose_node; rose_node = rose_node->next; for (i = 0; i < t->count; i++) { if (t->neighbour[i] != s) continue; t->count--; switch (i) { case 0: t->neighbour[0] = t->neighbour[1]; case 1: t->neighbour[1] = t->neighbour[2]; case 2: break; } } if (t->count <= 0) rose_remove_node(t); } rose_remove_neigh(s); } spin_unlock_bh(&rose_neigh_list_lock); spin_unlock_bh(&rose_node_list_lock); } #if 0 /* Currently unused */ /* * A device has been removed. Remove its links. */ void rose_route_device_down(struct net_device *dev) { struct rose_route *s, *rose_route; spin_lock_bh(&rose_route_list_lock); rose_route = rose_route_list; while (rose_route != NULL) { s = rose_route; rose_route = rose_route->next; if (s->neigh1->dev == dev || s->neigh2->dev == dev) rose_remove_route(s); } spin_unlock_bh(&rose_route_list_lock); } #endif /* * Clear all nodes and neighbours out, except for neighbours with * active connections going through them. * Do not clear loopback neighbour and nodes. */ static int rose_clear_routes(void) { struct rose_neigh *s, *rose_neigh; struct rose_node *t, *rose_node; spin_lock_bh(&rose_node_list_lock); spin_lock_bh(&rose_neigh_list_lock); rose_neigh = rose_neigh_list; rose_node = rose_node_list; while (rose_node != NULL) { t = rose_node; rose_node = rose_node->next; if (!t->loopback) rose_remove_node(t); } while (rose_neigh != NULL) { s = rose_neigh; rose_neigh = rose_neigh->next; if (s->use == 0 && !s->loopback) { s->count = 0; rose_remove_neigh(s); } } spin_unlock_bh(&rose_neigh_list_lock); spin_unlock_bh(&rose_node_list_lock); return 0; } /* * Check that the device given is a valid AX.25 interface that is "up". * called whith RTNL */ static struct net_device *rose_ax25_dev_find(char *devname) { struct net_device *dev; if ((dev = __dev_get_by_name(&init_net, devname)) == NULL) return NULL; if ((dev->flags & IFF_UP) && dev->type == ARPHRD_AX25) return dev; return NULL; } /* * Find the first active ROSE device, usually "rose0". */ struct net_device *rose_dev_first(void) { struct net_device *dev, *first = NULL; rcu_read_lock(); for_each_netdev_rcu(&init_net, dev) { if ((dev->flags & IFF_UP) && dev->type == ARPHRD_ROSE) if (first == NULL || strncmp(dev->name, first->name, 3) < 0) first = dev; } rcu_read_unlock(); return first; } /* * Find the ROSE device for the given address. */ struct net_device *rose_dev_get(rose_address *addr) { struct net_device *dev; rcu_read_lock(); for_each_netdev_rcu(&init_net, dev) { if ((dev->flags & IFF_UP) && dev->type == ARPHRD_ROSE && rosecmp(addr, (rose_address *)dev->dev_addr) == 0) { dev_hold(dev); goto out; } } dev = NULL; out: rcu_read_unlock(); return dev; } static int rose_dev_exists(rose_address *addr) { struct net_device *dev; rcu_read_lock(); for_each_netdev_rcu(&init_net, dev) { if ((dev->flags & IFF_UP) && dev->type == ARPHRD_ROSE && rosecmp(addr, (rose_address *)dev->dev_addr) == 0) goto out; } dev = NULL; out: rcu_read_unlock(); return dev != NULL; } struct rose_route *rose_route_free_lci(unsigned int lci, struct rose_neigh *neigh) { struct rose_route *rose_route; for (rose_route = rose_route_list; rose_route != NULL; rose_route = rose_route->next) if ((rose_route->neigh1 == neigh && rose_route->lci1 == lci) || (rose_route->neigh2 == neigh && rose_route->lci2 == lci)) return rose_route; return NULL; } /* * Find a neighbour or a route given a ROSE address. */ struct rose_neigh *rose_get_neigh(rose_address *addr, unsigned char *cause, unsigned char *diagnostic, int route_frame) { struct rose_neigh *res = NULL; struct rose_node *node; int failed = 0; int i; if (!route_frame) spin_lock_bh(&rose_node_list_lock); for (node = rose_node_list; node != NULL; node = node->next) { if (rosecmpm(addr, &node->address, node->mask) == 0) { for (i = 0; i < node->count; i++) { if (node->neighbour[i]->restarted) { res = node->neighbour[i]; goto out; } } } } if (!route_frame) { /* connect request */ for (node = rose_node_list; node != NULL; node = node->next) { if (rosecmpm(addr, &node->address, node->mask) == 0) { for (i = 0; i < node->count; i++) { if (!rose_ftimer_running(node->neighbour[i])) { res = node->neighbour[i]; failed = 0; goto out; } failed = 1; } } } } if (failed) { *cause = ROSE_OUT_OF_ORDER; *diagnostic = 0; } else { *cause = ROSE_NOT_OBTAINABLE; *diagnostic = 0; } out: if (!route_frame) spin_unlock_bh(&rose_node_list_lock); return res; } /* * Handle the ioctls that control the routing functions. */ int rose_rt_ioctl(unsigned int cmd, void __user *arg) { struct rose_route_struct rose_route; struct net_device *dev; int err; switch (cmd) { case SIOCADDRT: if (copy_from_user(&rose_route, arg, sizeof(struct rose_route_struct))) return -EFAULT; if ((dev = rose_ax25_dev_find(rose_route.device)) == NULL) return -EINVAL; if (rose_dev_exists(&rose_route.address)) /* Can't add routes to ourself */ return -EINVAL; if (rose_route.mask > 10) /* Mask can't be more than 10 digits */ return -EINVAL; if (rose_route.ndigis > AX25_MAX_DIGIS) return -EINVAL; err = rose_add_node(&rose_route, dev); return err; case SIOCDELRT: if (copy_from_user(&rose_route, arg, sizeof(struct rose_route_struct))) return -EFAULT; if ((dev = rose_ax25_dev_find(rose_route.device)) == NULL) return -EINVAL; err = rose_del_node(&rose_route, dev); return err; case SIOCRSCLRRT: return rose_clear_routes(); default: return -EINVAL; } return 0; } static void rose_del_route_by_neigh(struct rose_neigh *rose_neigh) { struct rose_route *rose_route, *s; rose_neigh->restarted = 0; rose_stop_t0timer(rose_neigh); rose_start_ftimer(rose_neigh); skb_queue_purge(&rose_neigh->queue); spin_lock_bh(&rose_route_list_lock); rose_route = rose_route_list; while (rose_route != NULL) { if ((rose_route->neigh1 == rose_neigh && rose_route->neigh2 == rose_neigh) || (rose_route->neigh1 == rose_neigh && rose_route->neigh2 == NULL) || (rose_route->neigh2 == rose_neigh && rose_route->neigh1 == NULL)) { s = rose_route->next; rose_remove_route(rose_route); rose_route = s; continue; } if (rose_route->neigh1 == rose_neigh) { rose_route->neigh1->use--; rose_route->neigh1 = NULL; rose_transmit_clear_request(rose_route->neigh2, rose_route->lci2, ROSE_OUT_OF_ORDER, 0); } if (rose_route->neigh2 == rose_neigh) { rose_route->neigh2->use--; rose_route->neigh2 = NULL; rose_transmit_clear_request(rose_route->neigh1, rose_route->lci1, ROSE_OUT_OF_ORDER, 0); } rose_route = rose_route->next; } spin_unlock_bh(&rose_route_list_lock); } /* * A level 2 link has timed out, therefore it appears to be a poor link, * then don't use that neighbour until it is reset. Blow away all through * routes and connections using this route. */ void rose_link_failed(ax25_cb *ax25, int reason) { struct rose_neigh *rose_neigh; spin_lock_bh(&rose_neigh_list_lock); rose_neigh = rose_neigh_list; while (rose_neigh != NULL) { if (rose_neigh->ax25 == ax25) break; rose_neigh = rose_neigh->next; } if (rose_neigh != NULL) { rose_neigh->ax25 = NULL; ax25_cb_put(ax25); rose_del_route_by_neigh(rose_neigh); rose_kill_by_neigh(rose_neigh); } spin_unlock_bh(&rose_neigh_list_lock); } /* * A device has been "downed" remove its link status. Blow away all * through routes and connections that use this device. */ void rose_link_device_down(struct net_device *dev) { struct rose_neigh *rose_neigh; for (rose_neigh = rose_neigh_list; rose_neigh != NULL; rose_neigh = rose_neigh->next) { if (rose_neigh->dev == dev) { rose_del_route_by_neigh(rose_neigh); rose_kill_by_neigh(rose_neigh); } } } /* * Route a frame to an appropriate AX.25 connection. */ int rose_route_frame(struct sk_buff *skb, ax25_cb *ax25) { struct rose_neigh *rose_neigh, *new_neigh; struct rose_route *rose_route; struct rose_facilities_struct facilities; rose_address *src_addr, *dest_addr; struct sock *sk; unsigned short frametype; unsigned int lci, new_lci; unsigned char cause, diagnostic; struct net_device *dev; int len, res = 0; char buf[11]; #if 0 if (call_in_firewall(PF_ROSE, skb->dev, skb->data, NULL, &skb) != FW_ACCEPT) return res; #endif frametype = skb->data[2]; lci = ((skb->data[0] << 8) & 0xF00) + ((skb->data[1] << 0) & 0x0FF); src_addr = (rose_address *)(skb->data + 9); dest_addr = (rose_address *)(skb->data + 4); spin_lock_bh(&rose_neigh_list_lock); spin_lock_bh(&rose_route_list_lock); rose_neigh = rose_neigh_list; while (rose_neigh != NULL) { if (ax25cmp(&ax25->dest_addr, &rose_neigh->callsign) == 0 && ax25->ax25_dev->dev == rose_neigh->dev) break; rose_neigh = rose_neigh->next; } if (rose_neigh == NULL) { printk("rose_route : unknown neighbour or device %s\n", ax2asc(buf, &ax25->dest_addr)); goto out; } /* * Obviously the link is working, halt the ftimer. */ rose_stop_ftimer(rose_neigh); /* * LCI of zero is always for us, and its always a restart * frame. */ if (lci == 0) { rose_link_rx_restart(skb, rose_neigh, frametype); goto out; } /* * Find an existing socket. */ if ((sk = rose_find_socket(lci, rose_neigh)) != NULL) { if (frametype == ROSE_CALL_REQUEST) { struct rose_sock *rose = rose_sk(sk); /* Remove an existing unused socket */ rose_clear_queues(sk); rose->cause = ROSE_NETWORK_CONGESTION; rose->diagnostic = 0; rose->neighbour->use--; rose->neighbour = NULL; rose->lci = 0; rose->state = ROSE_STATE_0; sk->sk_state = TCP_CLOSE; sk->sk_err = 0; sk->sk_shutdown |= SEND_SHUTDOWN; if (!sock_flag(sk, SOCK_DEAD)) { sk->sk_state_change(sk); sock_set_flag(sk, SOCK_DEAD); } } else { skb_reset_transport_header(skb); res = rose_process_rx_frame(sk, skb); goto out; } } /* * Is is a Call Request and is it for us ? */ if (frametype == ROSE_CALL_REQUEST) if ((dev = rose_dev_get(dest_addr)) != NULL) { res = rose_rx_call_request(skb, dev, rose_neigh, lci); dev_put(dev); goto out; } if (!sysctl_rose_routing_control) { rose_transmit_clear_request(rose_neigh, lci, ROSE_NOT_OBTAINABLE, 0); goto out; } /* * Route it to the next in line if we have an entry for it. */ rose_route = rose_route_list; while (rose_route != NULL) { if (rose_route->lci1 == lci && rose_route->neigh1 == rose_neigh) { if (frametype == ROSE_CALL_REQUEST) { /* F6FBB - Remove an existing unused route */ rose_remove_route(rose_route); break; } else if (rose_route->neigh2 != NULL) { skb->data[0] &= 0xF0; skb->data[0] |= (rose_route->lci2 >> 8) & 0x0F; skb->data[1] = (rose_route->lci2 >> 0) & 0xFF; rose_transmit_link(skb, rose_route->neigh2); if (frametype == ROSE_CLEAR_CONFIRMATION) rose_remove_route(rose_route); res = 1; goto out; } else { if (frametype == ROSE_CLEAR_CONFIRMATION) rose_remove_route(rose_route); goto out; } } if (rose_route->lci2 == lci && rose_route->neigh2 == rose_neigh) { if (frametype == ROSE_CALL_REQUEST) { /* F6FBB - Remove an existing unused route */ rose_remove_route(rose_route); break; } else if (rose_route->neigh1 != NULL) { skb->data[0] &= 0xF0; skb->data[0] |= (rose_route->lci1 >> 8) & 0x0F; skb->data[1] = (rose_route->lci1 >> 0) & 0xFF; rose_transmit_link(skb, rose_route->neigh1); if (frametype == ROSE_CLEAR_CONFIRMATION) rose_remove_route(rose_route); res = 1; goto out; } else { if (frametype == ROSE_CLEAR_CONFIRMATION) rose_remove_route(rose_route); goto out; } } rose_route = rose_route->next; } /* * We know that: * 1. The frame isn't for us, * 2. It isn't "owned" by any existing route. */ if (frametype != ROSE_CALL_REQUEST) { /* XXX */ res = 0; goto out; } len = (((skb->data[3] >> 4) & 0x0F) + 1) >> 1; len += (((skb->data[3] >> 0) & 0x0F) + 1) >> 1; memset(&facilities, 0x00, sizeof(struct rose_facilities_struct)); if (!rose_parse_facilities(skb->data + len + 4, &facilities)) { rose_transmit_clear_request(rose_neigh, lci, ROSE_INVALID_FACILITY, 76); goto out; } /* * Check for routing loops. */ rose_route = rose_route_list; while (rose_route != NULL) { if (rose_route->rand == facilities.rand && rosecmp(src_addr, &rose_route->src_addr) == 0 && ax25cmp(&facilities.dest_call, &rose_route->src_call) == 0 && ax25cmp(&facilities.source_call, &rose_route->dest_call) == 0) { rose_transmit_clear_request(rose_neigh, lci, ROSE_NOT_OBTAINABLE, 120); goto out; } rose_route = rose_route->next; } if ((new_neigh = rose_get_neigh(dest_addr, &cause, &diagnostic, 1)) == NULL) { rose_transmit_clear_request(rose_neigh, lci, cause, diagnostic); goto out; } if ((new_lci = rose_new_lci(new_neigh)) == 0) { rose_transmit_clear_request(rose_neigh, lci, ROSE_NETWORK_CONGESTION, 71); goto out; } if ((rose_route = kmalloc(sizeof(*rose_route), GFP_ATOMIC)) == NULL) { rose_transmit_clear_request(rose_neigh, lci, ROSE_NETWORK_CONGESTION, 120); goto out; } rose_route->lci1 = lci; rose_route->src_addr = *src_addr; rose_route->dest_addr = *dest_addr; rose_route->src_call = facilities.dest_call; rose_route->dest_call = facilities.source_call; rose_route->rand = facilities.rand; rose_route->neigh1 = rose_neigh; rose_route->lci2 = new_lci; rose_route->neigh2 = new_neigh; rose_route->neigh1->use++; rose_route->neigh2->use++; rose_route->next = rose_route_list; rose_route_list = rose_route; skb->data[0] &= 0xF0; skb->data[0] |= (rose_route->lci2 >> 8) & 0x0F; skb->data[1] = (rose_route->lci2 >> 0) & 0xFF; rose_transmit_link(skb, rose_route->neigh2); res = 1; out: spin_unlock_bh(&rose_route_list_lock); spin_unlock_bh(&rose_neigh_list_lock); return res; } #ifdef CONFIG_PROC_FS static void *rose_node_start(struct seq_file *seq, loff_t *pos) __acquires(rose_node_list_lock) { struct rose_node *rose_node; int i = 1; spin_lock_bh(&rose_node_list_lock); if (*pos == 0) return SEQ_START_TOKEN; for (rose_node = rose_node_list; rose_node && i < *pos; rose_node = rose_node->next, ++i); return (i == *pos) ? rose_node : NULL; } static void *rose_node_next(struct seq_file *seq, void *v, loff_t *pos) { ++*pos; return (v == SEQ_START_TOKEN) ? rose_node_list : ((struct rose_node *)v)->next; } static void rose_node_stop(struct seq_file *seq, void *v) __releases(rose_node_list_lock) { spin_unlock_bh(&rose_node_list_lock); } static int rose_node_show(struct seq_file *seq, void *v) { char rsbuf[11]; int i; if (v == SEQ_START_TOKEN) seq_puts(seq, "address mask n neigh neigh neigh\n"); else { const struct rose_node *rose_node = v; /* if (rose_node->loopback) { seq_printf(seq, "%-10s %04d 1 loopback\n", rose2asc(rsbuf, &rose_node->address), rose_node->mask); } else { */ seq_printf(seq, "%-10s %04d %d", rose2asc(rsbuf, &rose_node->address), rose_node->mask, rose_node->count); for (i = 0; i < rose_node->count; i++) seq_printf(seq, " %05d", rose_node->neighbour[i]->number); seq_puts(seq, "\n"); /* } */ } return 0; } static const struct seq_operations rose_node_seqops = { .start = rose_node_start, .next = rose_node_next, .stop = rose_node_stop, .show = rose_node_show, }; static int rose_nodes_open(struct inode *inode, struct file *file) { return seq_open(file, &rose_node_seqops); } const struct file_operations rose_nodes_fops = { .owner = THIS_MODULE, .open = rose_nodes_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release, }; static void *rose_neigh_start(struct seq_file *seq, loff_t *pos) __acquires(rose_neigh_list_lock) { struct rose_neigh *rose_neigh; int i = 1; spin_lock_bh(&rose_neigh_list_lock); if (*pos == 0) return SEQ_START_TOKEN; for (rose_neigh = rose_neigh_list; rose_neigh && i < *pos; rose_neigh = rose_neigh->next, ++i); return (i == *pos) ? rose_neigh : NULL; } static void *rose_neigh_next(struct seq_file *seq, void *v, loff_t *pos) { ++*pos; return (v == SEQ_START_TOKEN) ? rose_neigh_list : ((struct rose_neigh *)v)->next; } static void rose_neigh_stop(struct seq_file *seq, void *v) __releases(rose_neigh_list_lock) { spin_unlock_bh(&rose_neigh_list_lock); } static int rose_neigh_show(struct seq_file *seq, void *v) { char buf[11]; int i; if (v == SEQ_START_TOKEN) seq_puts(seq, "addr callsign dev count use mode restart t0 tf digipeaters\n"); else { struct rose_neigh *rose_neigh = v; /* if (!rose_neigh->loopback) { */ seq_printf(seq, "%05d %-9s %-4s %3d %3d %3s %3s %3lu %3lu", rose_neigh->number, (rose_neigh->loopback) ? "RSLOOP-0" : ax2asc(buf, &rose_neigh->callsign), rose_neigh->dev ? rose_neigh->dev->name : "???", rose_neigh->count, rose_neigh->use, (rose_neigh->dce_mode) ? "DCE" : "DTE", (rose_neigh->restarted) ? "yes" : "no", ax25_display_timer(&rose_neigh->t0timer) / HZ, ax25_display_timer(&rose_neigh->ftimer) / HZ); if (rose_neigh->digipeat != NULL) { for (i = 0; i < rose_neigh->digipeat->ndigi; i++) seq_printf(seq, " %s", ax2asc(buf, &rose_neigh->digipeat->calls[i])); } seq_puts(seq, "\n"); } return 0; } static const struct seq_operations rose_neigh_seqops = { .start = rose_neigh_start, .next = rose_neigh_next, .stop = rose_neigh_stop, .show = rose_neigh_show, }; static int rose_neigh_open(struct inode *inode, struct file *file) { return seq_open(file, &rose_neigh_seqops); } const struct file_operations rose_neigh_fops = { .owner = THIS_MODULE, .open = rose_neigh_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release, }; static void *rose_route_start(struct seq_file *seq, loff_t *pos) __acquires(rose_route_list_lock) { struct rose_route *rose_route; int i = 1; spin_lock_bh(&rose_route_list_lock); if (*pos == 0) return SEQ_START_TOKEN; for (rose_route = rose_route_list; rose_route && i < *pos; rose_route = rose_route->next, ++i); return (i == *pos) ? rose_route : NULL; } static void *rose_route_next(struct seq_file *seq, void *v, loff_t *pos) { ++*pos; return (v == SEQ_START_TOKEN) ? rose_route_list : ((struct rose_route *)v)->next; } static void rose_route_stop(struct seq_file *seq, void *v) __releases(rose_route_list_lock) { spin_unlock_bh(&rose_route_list_lock); } static int rose_route_show(struct seq_file *seq, void *v) { char buf[11], rsbuf[11]; if (v == SEQ_START_TOKEN) seq_puts(seq, "lci address callsign neigh <-> lci address callsign neigh\n"); else { struct rose_route *rose_route = v; if (rose_route->neigh1) seq_printf(seq, "%3.3X %-10s %-9s %05d ", rose_route->lci1, rose2asc(rsbuf, &rose_route->src_addr), ax2asc(buf, &rose_route->src_call), rose_route->neigh1->number); else seq_puts(seq, "000 * * 00000 "); if (rose_route->neigh2) seq_printf(seq, "%3.3X %-10s %-9s %05d\n", rose_route->lci2, rose2asc(rsbuf, &rose_route->dest_addr), ax2asc(buf, &rose_route->dest_call), rose_route->neigh2->number); else seq_puts(seq, "000 * * 00000\n"); } return 0; } static const struct seq_operations rose_route_seqops = { .start = rose_route_start, .next = rose_route_next, .stop = rose_route_stop, .show = rose_route_show, }; static int rose_route_open(struct inode *inode, struct file *file) { return seq_open(file, &rose_route_seqops); } const struct file_operations rose_routes_fops = { .owner = THIS_MODULE, .open = rose_route_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release, }; #endif /* CONFIG_PROC_FS */ /* * Release all memory associated with ROSE routing structures. */ void __exit rose_rt_free(void) { struct rose_neigh *s, *rose_neigh = rose_neigh_list; struct rose_node *t, *rose_node = rose_node_list; struct rose_route *u, *rose_route = rose_route_list; while (rose_neigh != NULL) { s = rose_neigh; rose_neigh = rose_neigh->next; rose_remove_neigh(s); } while (rose_node != NULL) { t = rose_node; rose_node = rose_node->next; rose_remove_node(t); } while (rose_route != NULL) { u = rose_route; rose_route = rose_route->next; rose_remove_route(u); } }
./CrossVul/dataset_final_sorted/CWE-20/c/bad_3547_3
crossvul-cpp_data_good_2891_2
/* Large capacity key type * * Copyright (C) 2017 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved. * Copyright (C) 2013 Red Hat, Inc. All Rights Reserved. * Written by David Howells (dhowells@redhat.com) * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public Licence * as published by the Free Software Foundation; either version * 2 of the Licence, or (at your option) any later version. */ #define pr_fmt(fmt) "big_key: "fmt #include <linux/init.h> #include <linux/seq_file.h> #include <linux/file.h> #include <linux/shmem_fs.h> #include <linux/err.h> #include <linux/scatterlist.h> #include <linux/random.h> #include <keys/user-type.h> #include <keys/big_key-type.h> #include <crypto/aead.h> /* * Layout of key payload words. */ enum { big_key_data, big_key_path, big_key_path_2nd_part, big_key_len, }; /* * Crypto operation with big_key data */ enum big_key_op { BIG_KEY_ENC, BIG_KEY_DEC, }; /* * If the data is under this limit, there's no point creating a shm file to * hold it as the permanently resident metadata for the shmem fs will be at * least as large as the data. */ #define BIG_KEY_FILE_THRESHOLD (sizeof(struct inode) + sizeof(struct dentry)) /* * Key size for big_key data encryption */ #define ENC_KEY_SIZE 32 /* * Authentication tag length */ #define ENC_AUTHTAG_SIZE 16 /* * big_key defined keys take an arbitrary string as the description and an * arbitrary blob of data as the payload */ struct key_type key_type_big_key = { .name = "big_key", .preparse = big_key_preparse, .free_preparse = big_key_free_preparse, .instantiate = generic_key_instantiate, .revoke = big_key_revoke, .destroy = big_key_destroy, .describe = big_key_describe, .read = big_key_read, /* no ->update(); don't add it without changing big_key_crypt() nonce */ }; /* * Crypto names for big_key data authenticated encryption */ static const char big_key_alg_name[] = "gcm(aes)"; /* * Crypto algorithms for big_key data authenticated encryption */ static struct crypto_aead *big_key_aead; /* * Since changing the key affects the entire object, we need a mutex. */ static DEFINE_MUTEX(big_key_aead_lock); /* * Encrypt/decrypt big_key data */ static int big_key_crypt(enum big_key_op op, u8 *data, size_t datalen, u8 *key) { int ret; struct scatterlist sgio; struct aead_request *aead_req; /* We always use a zero nonce. The reason we can get away with this is * because we're using a different randomly generated key for every * different encryption. Notably, too, key_type_big_key doesn't define * an .update function, so there's no chance we'll wind up reusing the * key to encrypt updated data. Simply put: one key, one encryption. */ u8 zero_nonce[crypto_aead_ivsize(big_key_aead)]; aead_req = aead_request_alloc(big_key_aead, GFP_KERNEL); if (!aead_req) return -ENOMEM; memset(zero_nonce, 0, sizeof(zero_nonce)); sg_init_one(&sgio, data, datalen + (op == BIG_KEY_ENC ? ENC_AUTHTAG_SIZE : 0)); aead_request_set_crypt(aead_req, &sgio, &sgio, datalen, zero_nonce); aead_request_set_callback(aead_req, CRYPTO_TFM_REQ_MAY_SLEEP, NULL, NULL); aead_request_set_ad(aead_req, 0); mutex_lock(&big_key_aead_lock); if (crypto_aead_setkey(big_key_aead, key, ENC_KEY_SIZE)) { ret = -EAGAIN; goto error; } if (op == BIG_KEY_ENC) ret = crypto_aead_encrypt(aead_req); else ret = crypto_aead_decrypt(aead_req); error: mutex_unlock(&big_key_aead_lock); aead_request_free(aead_req); return ret; } /* * Preparse a big key */ int big_key_preparse(struct key_preparsed_payload *prep) { struct path *path = (struct path *)&prep->payload.data[big_key_path]; struct file *file; u8 *enckey; u8 *data = NULL; ssize_t written; size_t datalen = prep->datalen; int ret; ret = -EINVAL; if (datalen <= 0 || datalen > 1024 * 1024 || !prep->data) goto error; /* Set an arbitrary quota */ prep->quotalen = 16; prep->payload.data[big_key_len] = (void *)(unsigned long)datalen; if (datalen > BIG_KEY_FILE_THRESHOLD) { /* Create a shmem file to store the data in. This will permit the data * to be swapped out if needed. * * File content is stored encrypted with randomly generated key. */ size_t enclen = datalen + ENC_AUTHTAG_SIZE; loff_t pos = 0; data = kmalloc(enclen, GFP_KERNEL); if (!data) return -ENOMEM; memcpy(data, prep->data, datalen); /* generate random key */ enckey = kmalloc(ENC_KEY_SIZE, GFP_KERNEL); if (!enckey) { ret = -ENOMEM; goto error; } ret = get_random_bytes_wait(enckey, ENC_KEY_SIZE); if (unlikely(ret)) goto err_enckey; /* encrypt aligned data */ ret = big_key_crypt(BIG_KEY_ENC, data, datalen, enckey); if (ret) goto err_enckey; /* save aligned data to file */ file = shmem_kernel_file_setup("", enclen, 0); if (IS_ERR(file)) { ret = PTR_ERR(file); goto err_enckey; } written = kernel_write(file, data, enclen, &pos); if (written != enclen) { ret = written; if (written >= 0) ret = -ENOMEM; goto err_fput; } /* Pin the mount and dentry to the key so that we can open it again * later */ prep->payload.data[big_key_data] = enckey; *path = file->f_path; path_get(path); fput(file); kzfree(data); } else { /* Just store the data in a buffer */ void *data = kmalloc(datalen, GFP_KERNEL); if (!data) return -ENOMEM; prep->payload.data[big_key_data] = data; memcpy(data, prep->data, prep->datalen); } return 0; err_fput: fput(file); err_enckey: kzfree(enckey); error: kzfree(data); return ret; } /* * Clear preparsement. */ void big_key_free_preparse(struct key_preparsed_payload *prep) { if (prep->datalen > BIG_KEY_FILE_THRESHOLD) { struct path *path = (struct path *)&prep->payload.data[big_key_path]; path_put(path); } kzfree(prep->payload.data[big_key_data]); } /* * dispose of the links from a revoked keyring * - called with the key sem write-locked */ void big_key_revoke(struct key *key) { struct path *path = (struct path *)&key->payload.data[big_key_path]; /* clear the quota */ key_payload_reserve(key, 0); if (key_is_positive(key) && (size_t)key->payload.data[big_key_len] > BIG_KEY_FILE_THRESHOLD) vfs_truncate(path, 0); } /* * dispose of the data dangling from the corpse of a big_key key */ void big_key_destroy(struct key *key) { size_t datalen = (size_t)key->payload.data[big_key_len]; if (datalen > BIG_KEY_FILE_THRESHOLD) { struct path *path = (struct path *)&key->payload.data[big_key_path]; path_put(path); path->mnt = NULL; path->dentry = NULL; } kzfree(key->payload.data[big_key_data]); key->payload.data[big_key_data] = NULL; } /* * describe the big_key key */ void big_key_describe(const struct key *key, struct seq_file *m) { size_t datalen = (size_t)key->payload.data[big_key_len]; seq_puts(m, key->description); if (key_is_positive(key)) seq_printf(m, ": %zu [%s]", datalen, datalen > BIG_KEY_FILE_THRESHOLD ? "file" : "buff"); } /* * read the key data * - the key's semaphore is read-locked */ long big_key_read(const struct key *key, char __user *buffer, size_t buflen) { size_t datalen = (size_t)key->payload.data[big_key_len]; long ret; if (!buffer || buflen < datalen) return datalen; if (datalen > BIG_KEY_FILE_THRESHOLD) { struct path *path = (struct path *)&key->payload.data[big_key_path]; struct file *file; u8 *data; u8 *enckey = (u8 *)key->payload.data[big_key_data]; size_t enclen = datalen + ENC_AUTHTAG_SIZE; loff_t pos = 0; data = kmalloc(enclen, GFP_KERNEL); if (!data) return -ENOMEM; file = dentry_open(path, O_RDONLY, current_cred()); if (IS_ERR(file)) { ret = PTR_ERR(file); goto error; } /* read file to kernel and decrypt */ ret = kernel_read(file, data, enclen, &pos); if (ret >= 0 && ret != enclen) { ret = -EIO; goto err_fput; } ret = big_key_crypt(BIG_KEY_DEC, data, enclen, enckey); if (ret) goto err_fput; ret = datalen; /* copy decrypted data to user */ if (copy_to_user(buffer, data, datalen) != 0) ret = -EFAULT; err_fput: fput(file); error: kzfree(data); } else { ret = datalen; if (copy_to_user(buffer, key->payload.data[big_key_data], datalen) != 0) ret = -EFAULT; } return ret; } /* * Register key type */ static int __init big_key_init(void) { int ret; /* init block cipher */ big_key_aead = crypto_alloc_aead(big_key_alg_name, 0, CRYPTO_ALG_ASYNC); if (IS_ERR(big_key_aead)) { ret = PTR_ERR(big_key_aead); pr_err("Can't alloc crypto: %d\n", ret); return ret; } ret = crypto_aead_setauthsize(big_key_aead, ENC_AUTHTAG_SIZE); if (ret < 0) { pr_err("Can't set crypto auth tag len: %d\n", ret); goto free_aead; } ret = register_key_type(&key_type_big_key); if (ret < 0) { pr_err("Can't register type: %d\n", ret); goto free_aead; } return 0; free_aead: crypto_free_aead(big_key_aead); return ret; } late_initcall(big_key_init);
./CrossVul/dataset_final_sorted/CWE-20/c/good_2891_2
crossvul-cpp_data_bad_5845_15
/* * Implements an IPX socket layer. * * This code is derived from work by * Ross Biro : Writing the original IP stack * Fred Van Kempen : Tidying up the TCP/IP * * Many thanks go to Keith Baker, Institute For Industrial Information * Technology Ltd, Swansea University for allowing me to work on this * in my own time even though it was in some ways related to commercial * work I am currently employed to do there. * * All the material in this file is subject to the Gnu license version 2. * Neither Alan Cox nor the Swansea University Computer Society admit * liability nor provide warranty for any of this software. This material * is provided as is and at no charge. * * Portions Copyright (c) 2000-2003 Conectiva, Inc. <acme@conectiva.com.br> * Neither Arnaldo Carvalho de Melo nor Conectiva, Inc. admit liability nor * provide warranty for any of this software. This material is provided * "AS-IS" and at no charge. * * Portions Copyright (c) 1995 Caldera, Inc. <greg@caldera.com> * Neither Greg Page nor Caldera, Inc. admit liability nor provide * warranty for any of this software. This material is provided * "AS-IS" and at no charge. * * See net/ipx/ChangeLog. */ #include <linux/capability.h> #include <linux/errno.h> #include <linux/if_arp.h> #include <linux/if_ether.h> #include <linux/init.h> #include <linux/ipx.h> #include <linux/kernel.h> #include <linux/list.h> #include <linux/module.h> #include <linux/net.h> #include <linux/netdevice.h> #include <linux/uio.h> #include <linux/slab.h> #include <linux/skbuff.h> #include <linux/socket.h> #include <linux/sockios.h> #include <linux/string.h> #include <linux/types.h> #include <linux/termios.h> #include <net/ipx.h> #include <net/p8022.h> #include <net/psnap.h> #include <net/sock.h> #include <net/tcp_states.h> #include <asm/uaccess.h> #ifdef CONFIG_SYSCTL extern void ipx_register_sysctl(void); extern void ipx_unregister_sysctl(void); #else #define ipx_register_sysctl() #define ipx_unregister_sysctl() #endif /* Configuration Variables */ static unsigned char ipxcfg_max_hops = 16; static char ipxcfg_auto_select_primary; static char ipxcfg_auto_create_interfaces; int sysctl_ipx_pprop_broadcasting = 1; /* Global Variables */ static struct datalink_proto *p8022_datalink; static struct datalink_proto *pEII_datalink; static struct datalink_proto *p8023_datalink; static struct datalink_proto *pSNAP_datalink; static const struct proto_ops ipx_dgram_ops; LIST_HEAD(ipx_interfaces); DEFINE_SPINLOCK(ipx_interfaces_lock); struct ipx_interface *ipx_primary_net; struct ipx_interface *ipx_internal_net; extern int ipxrtr_add_route(__be32 network, struct ipx_interface *intrfc, unsigned char *node); extern void ipxrtr_del_routes(struct ipx_interface *intrfc); extern int ipxrtr_route_packet(struct sock *sk, struct sockaddr_ipx *usipx, struct iovec *iov, size_t len, int noblock); extern int ipxrtr_route_skb(struct sk_buff *skb); extern struct ipx_route *ipxrtr_lookup(__be32 net); extern int ipxrtr_ioctl(unsigned int cmd, void __user *arg); struct ipx_interface *ipx_interfaces_head(void) { struct ipx_interface *rc = NULL; if (!list_empty(&ipx_interfaces)) rc = list_entry(ipx_interfaces.next, struct ipx_interface, node); return rc; } static void ipxcfg_set_auto_select(char val) { ipxcfg_auto_select_primary = val; if (val && !ipx_primary_net) ipx_primary_net = ipx_interfaces_head(); } static int ipxcfg_get_config_data(struct ipx_config_data __user *arg) { struct ipx_config_data vals; vals.ipxcfg_auto_create_interfaces = ipxcfg_auto_create_interfaces; vals.ipxcfg_auto_select_primary = ipxcfg_auto_select_primary; return copy_to_user(arg, &vals, sizeof(vals)) ? -EFAULT : 0; } /* * Note: Sockets may not be removed _during_ an interrupt or inet_bh * handler using this technique. They can be added although we do not * use this facility. */ static void ipx_remove_socket(struct sock *sk) { /* Determine interface with which socket is associated */ struct ipx_interface *intrfc = ipx_sk(sk)->intrfc; if (!intrfc) goto out; ipxitf_hold(intrfc); spin_lock_bh(&intrfc->if_sklist_lock); sk_del_node_init(sk); spin_unlock_bh(&intrfc->if_sklist_lock); ipxitf_put(intrfc); out: return; } static void ipx_destroy_socket(struct sock *sk) { ipx_remove_socket(sk); skb_queue_purge(&sk->sk_receive_queue); sk_refcnt_debug_dec(sk); } /* * The following code is used to support IPX Interfaces (IPXITF). An * IPX interface is defined by a physical device and a frame type. */ /* ipxitf_clear_primary_net has to be called with ipx_interfaces_lock held */ static void ipxitf_clear_primary_net(void) { ipx_primary_net = NULL; if (ipxcfg_auto_select_primary) ipx_primary_net = ipx_interfaces_head(); } static struct ipx_interface *__ipxitf_find_using_phys(struct net_device *dev, __be16 datalink) { struct ipx_interface *i; list_for_each_entry(i, &ipx_interfaces, node) if (i->if_dev == dev && i->if_dlink_type == datalink) goto out; i = NULL; out: return i; } static struct ipx_interface *ipxitf_find_using_phys(struct net_device *dev, __be16 datalink) { struct ipx_interface *i; spin_lock_bh(&ipx_interfaces_lock); i = __ipxitf_find_using_phys(dev, datalink); if (i) ipxitf_hold(i); spin_unlock_bh(&ipx_interfaces_lock); return i; } struct ipx_interface *ipxitf_find_using_net(__be32 net) { struct ipx_interface *i; spin_lock_bh(&ipx_interfaces_lock); if (net) { list_for_each_entry(i, &ipx_interfaces, node) if (i->if_netnum == net) goto hold; i = NULL; goto unlock; } i = ipx_primary_net; if (i) hold: ipxitf_hold(i); unlock: spin_unlock_bh(&ipx_interfaces_lock); return i; } /* Sockets are bound to a particular IPX interface. */ static void ipxitf_insert_socket(struct ipx_interface *intrfc, struct sock *sk) { ipxitf_hold(intrfc); spin_lock_bh(&intrfc->if_sklist_lock); ipx_sk(sk)->intrfc = intrfc; sk_add_node(sk, &intrfc->if_sklist); spin_unlock_bh(&intrfc->if_sklist_lock); ipxitf_put(intrfc); } /* caller must hold intrfc->if_sklist_lock */ static struct sock *__ipxitf_find_socket(struct ipx_interface *intrfc, __be16 port) { struct sock *s; sk_for_each(s, &intrfc->if_sklist) if (ipx_sk(s)->port == port) goto found; s = NULL; found: return s; } /* caller must hold a reference to intrfc */ static struct sock *ipxitf_find_socket(struct ipx_interface *intrfc, __be16 port) { struct sock *s; spin_lock_bh(&intrfc->if_sklist_lock); s = __ipxitf_find_socket(intrfc, port); if (s) sock_hold(s); spin_unlock_bh(&intrfc->if_sklist_lock); return s; } #ifdef CONFIG_IPX_INTERN static struct sock *ipxitf_find_internal_socket(struct ipx_interface *intrfc, unsigned char *ipx_node, __be16 port) { struct sock *s; ipxitf_hold(intrfc); spin_lock_bh(&intrfc->if_sklist_lock); sk_for_each(s, &intrfc->if_sklist) { struct ipx_sock *ipxs = ipx_sk(s); if (ipxs->port == port && !memcmp(ipx_node, ipxs->node, IPX_NODE_LEN)) goto found; } s = NULL; found: spin_unlock_bh(&intrfc->if_sklist_lock); ipxitf_put(intrfc); return s; } #endif static void __ipxitf_down(struct ipx_interface *intrfc) { struct sock *s; struct hlist_node *t; /* Delete all routes associated with this interface */ ipxrtr_del_routes(intrfc); spin_lock_bh(&intrfc->if_sklist_lock); /* error sockets */ sk_for_each_safe(s, t, &intrfc->if_sklist) { struct ipx_sock *ipxs = ipx_sk(s); s->sk_err = ENOLINK; s->sk_error_report(s); ipxs->intrfc = NULL; ipxs->port = 0; sock_set_flag(s, SOCK_ZAPPED); /* Indicates it is no longer bound */ sk_del_node_init(s); } INIT_HLIST_HEAD(&intrfc->if_sklist); spin_unlock_bh(&intrfc->if_sklist_lock); /* remove this interface from list */ list_del(&intrfc->node); /* remove this interface from *special* networks */ if (intrfc == ipx_primary_net) ipxitf_clear_primary_net(); if (intrfc == ipx_internal_net) ipx_internal_net = NULL; if (intrfc->if_dev) dev_put(intrfc->if_dev); kfree(intrfc); } void ipxitf_down(struct ipx_interface *intrfc) { spin_lock_bh(&ipx_interfaces_lock); __ipxitf_down(intrfc); spin_unlock_bh(&ipx_interfaces_lock); } static __inline__ void __ipxitf_put(struct ipx_interface *intrfc) { if (atomic_dec_and_test(&intrfc->refcnt)) __ipxitf_down(intrfc); } static int ipxitf_device_event(struct notifier_block *notifier, unsigned long event, void *ptr) { struct net_device *dev = netdev_notifier_info_to_dev(ptr); struct ipx_interface *i, *tmp; if (!net_eq(dev_net(dev), &init_net)) return NOTIFY_DONE; if (event != NETDEV_DOWN && event != NETDEV_UP) goto out; spin_lock_bh(&ipx_interfaces_lock); list_for_each_entry_safe(i, tmp, &ipx_interfaces, node) if (i->if_dev == dev) { if (event == NETDEV_UP) ipxitf_hold(i); else __ipxitf_put(i); } spin_unlock_bh(&ipx_interfaces_lock); out: return NOTIFY_DONE; } static __exit void ipxitf_cleanup(void) { struct ipx_interface *i, *tmp; spin_lock_bh(&ipx_interfaces_lock); list_for_each_entry_safe(i, tmp, &ipx_interfaces, node) __ipxitf_put(i); spin_unlock_bh(&ipx_interfaces_lock); } static void ipxitf_def_skb_handler(struct sock *sock, struct sk_buff *skb) { if (sock_queue_rcv_skb(sock, skb) < 0) kfree_skb(skb); } /* * On input skb->sk is NULL. Nobody is charged for the memory. */ /* caller must hold a reference to intrfc */ #ifdef CONFIG_IPX_INTERN static int ipxitf_demux_socket(struct ipx_interface *intrfc, struct sk_buff *skb, int copy) { struct ipxhdr *ipx = ipx_hdr(skb); int is_broadcast = !memcmp(ipx->ipx_dest.node, ipx_broadcast_node, IPX_NODE_LEN); struct sock *s; int rc; spin_lock_bh(&intrfc->if_sklist_lock); sk_for_each(s, &intrfc->if_sklist) { struct ipx_sock *ipxs = ipx_sk(s); if (ipxs->port == ipx->ipx_dest.sock && (is_broadcast || !memcmp(ipx->ipx_dest.node, ipxs->node, IPX_NODE_LEN))) { /* We found a socket to which to send */ struct sk_buff *skb1; if (copy) { skb1 = skb_clone(skb, GFP_ATOMIC); rc = -ENOMEM; if (!skb1) goto out; } else { skb1 = skb; copy = 1; /* skb may only be used once */ } ipxitf_def_skb_handler(s, skb1); /* On an external interface, one socket can listen */ if (intrfc != ipx_internal_net) break; } } /* skb was solely for us, and we did not make a copy, so free it. */ if (!copy) kfree_skb(skb); rc = 0; out: spin_unlock_bh(&intrfc->if_sklist_lock); return rc; } #else static struct sock *ncp_connection_hack(struct ipx_interface *intrfc, struct ipxhdr *ipx) { /* The packet's target is a NCP connection handler. We want to hand it * to the correct socket directly within the kernel, so that the * mars_nwe packet distribution process does not have to do it. Here we * only care about NCP and BURST packets. * * You might call this a hack, but believe me, you do not want a * complete NCP layer in the kernel, and this is VERY fast as well. */ struct sock *sk = NULL; int connection = 0; u8 *ncphdr = (u8 *)(ipx + 1); if (*ncphdr == 0x22 && *(ncphdr + 1) == 0x22) /* NCP request */ connection = (((int) *(ncphdr + 5)) << 8) | (int) *(ncphdr + 3); else if (*ncphdr == 0x77 && *(ncphdr + 1) == 0x77) /* BURST packet */ connection = (((int) *(ncphdr + 9)) << 8) | (int) *(ncphdr + 8); if (connection) { /* Now we have to look for a special NCP connection handling * socket. Only these sockets have ipx_ncp_conn != 0, set by * SIOCIPXNCPCONN. */ spin_lock_bh(&intrfc->if_sklist_lock); sk_for_each(sk, &intrfc->if_sklist) if (ipx_sk(sk)->ipx_ncp_conn == connection) { sock_hold(sk); goto found; } sk = NULL; found: spin_unlock_bh(&intrfc->if_sklist_lock); } return sk; } static int ipxitf_demux_socket(struct ipx_interface *intrfc, struct sk_buff *skb, int copy) { struct ipxhdr *ipx = ipx_hdr(skb); struct sock *sock1 = NULL, *sock2 = NULL; struct sk_buff *skb1 = NULL, *skb2 = NULL; int rc; if (intrfc == ipx_primary_net && ntohs(ipx->ipx_dest.sock) == 0x451) sock1 = ncp_connection_hack(intrfc, ipx); if (!sock1) /* No special socket found, forward the packet the normal way */ sock1 = ipxitf_find_socket(intrfc, ipx->ipx_dest.sock); /* * We need to check if there is a primary net and if * this is addressed to one of the *SPECIAL* sockets because * these need to be propagated to the primary net. * The *SPECIAL* socket list contains: 0x452(SAP), 0x453(RIP) and * 0x456(Diagnostic). */ if (ipx_primary_net && intrfc != ipx_primary_net) { const int dsock = ntohs(ipx->ipx_dest.sock); if (dsock == 0x452 || dsock == 0x453 || dsock == 0x456) /* The appropriate thing to do here is to dup the * packet and route to the primary net interface via * ipxitf_send; however, we'll cheat and just demux it * here. */ sock2 = ipxitf_find_socket(ipx_primary_net, ipx->ipx_dest.sock); } /* * If there is nothing to do return. The kfree will cancel any charging. */ rc = 0; if (!sock1 && !sock2) { if (!copy) kfree_skb(skb); goto out; } /* * This next segment of code is a little awkward, but it sets it up * so that the appropriate number of copies of the SKB are made and * that skb1 and skb2 point to it (them) so that it (they) can be * demuxed to sock1 and/or sock2. If we are unable to make enough * copies, we do as much as is possible. */ if (copy) skb1 = skb_clone(skb, GFP_ATOMIC); else skb1 = skb; rc = -ENOMEM; if (!skb1) goto out_put; /* Do we need 2 SKBs? */ if (sock1 && sock2) skb2 = skb_clone(skb1, GFP_ATOMIC); else skb2 = skb1; if (sock1) ipxitf_def_skb_handler(sock1, skb1); if (!skb2) goto out_put; if (sock2) ipxitf_def_skb_handler(sock2, skb2); rc = 0; out_put: if (sock1) sock_put(sock1); if (sock2) sock_put(sock2); out: return rc; } #endif /* CONFIG_IPX_INTERN */ static struct sk_buff *ipxitf_adjust_skbuff(struct ipx_interface *intrfc, struct sk_buff *skb) { struct sk_buff *skb2; int in_offset = (unsigned char *)ipx_hdr(skb) - skb->head; int out_offset = intrfc->if_ipx_offset; int len; /* Hopefully, most cases */ if (in_offset >= out_offset) return skb; /* Need new SKB */ len = skb->len + out_offset; skb2 = alloc_skb(len, GFP_ATOMIC); if (skb2) { skb_reserve(skb2, out_offset); skb_reset_network_header(skb2); skb_reset_transport_header(skb2); skb_put(skb2, skb->len); memcpy(ipx_hdr(skb2), ipx_hdr(skb), skb->len); memcpy(skb2->cb, skb->cb, sizeof(skb->cb)); } kfree_skb(skb); return skb2; } /* caller must hold a reference to intrfc and the skb has to be unshared */ int ipxitf_send(struct ipx_interface *intrfc, struct sk_buff *skb, char *node) { struct ipxhdr *ipx = ipx_hdr(skb); struct net_device *dev = intrfc->if_dev; struct datalink_proto *dl = intrfc->if_dlink; char dest_node[IPX_NODE_LEN]; int send_to_wire = 1; int addr_len; ipx->ipx_tctrl = IPX_SKB_CB(skb)->ipx_tctrl; ipx->ipx_dest.net = IPX_SKB_CB(skb)->ipx_dest_net; ipx->ipx_source.net = IPX_SKB_CB(skb)->ipx_source_net; /* see if we need to include the netnum in the route list */ if (IPX_SKB_CB(skb)->last_hop.index >= 0) { __be32 *last_hop = (__be32 *)(((u8 *) skb->data) + sizeof(struct ipxhdr) + IPX_SKB_CB(skb)->last_hop.index * sizeof(__be32)); *last_hop = IPX_SKB_CB(skb)->last_hop.netnum; IPX_SKB_CB(skb)->last_hop.index = -1; } /* * We need to know how many skbuffs it will take to send out this * packet to avoid unnecessary copies. */ if (!dl || !dev || dev->flags & IFF_LOOPBACK) send_to_wire = 0; /* No non looped */ /* * See if this should be demuxed to sockets on this interface * * We want to ensure the original was eaten or that we only use * up clones. */ if (ipx->ipx_dest.net == intrfc->if_netnum) { /* * To our own node, loop and free the original. * The internal net will receive on all node address. */ if (intrfc == ipx_internal_net || !memcmp(intrfc->if_node, node, IPX_NODE_LEN)) { /* Don't charge sender */ skb_orphan(skb); /* Will charge receiver */ return ipxitf_demux_socket(intrfc, skb, 0); } /* Broadcast, loop and possibly keep to send on. */ if (!memcmp(ipx_broadcast_node, node, IPX_NODE_LEN)) { if (!send_to_wire) skb_orphan(skb); ipxitf_demux_socket(intrfc, skb, send_to_wire); if (!send_to_wire) goto out; } } /* * If the originating net is not equal to our net; this is routed * We are still charging the sender. Which is right - the driver * free will handle this fairly. */ if (ipx->ipx_source.net != intrfc->if_netnum) { /* * Unshare the buffer before modifying the count in * case it's a flood or tcpdump */ skb = skb_unshare(skb, GFP_ATOMIC); if (!skb) goto out; if (++ipx->ipx_tctrl > ipxcfg_max_hops) send_to_wire = 0; } if (!send_to_wire) { kfree_skb(skb); goto out; } /* Determine the appropriate hardware address */ addr_len = dev->addr_len; if (!memcmp(ipx_broadcast_node, node, IPX_NODE_LEN)) memcpy(dest_node, dev->broadcast, addr_len); else memcpy(dest_node, &(node[IPX_NODE_LEN-addr_len]), addr_len); /* Make any compensation for differing physical/data link size */ skb = ipxitf_adjust_skbuff(intrfc, skb); if (!skb) goto out; /* set up data link and physical headers */ skb->dev = dev; skb->protocol = htons(ETH_P_IPX); /* Send it out */ dl->request(dl, skb, dest_node); out: return 0; } static int ipxitf_add_local_route(struct ipx_interface *intrfc) { return ipxrtr_add_route(intrfc->if_netnum, intrfc, NULL); } static void ipxitf_discover_netnum(struct ipx_interface *intrfc, struct sk_buff *skb); static int ipxitf_pprop(struct ipx_interface *intrfc, struct sk_buff *skb); static int ipxitf_rcv(struct ipx_interface *intrfc, struct sk_buff *skb) { struct ipxhdr *ipx = ipx_hdr(skb); int rc = 0; ipxitf_hold(intrfc); /* See if we should update our network number */ if (!intrfc->if_netnum) /* net number of intrfc not known yet */ ipxitf_discover_netnum(intrfc, skb); IPX_SKB_CB(skb)->last_hop.index = -1; if (ipx->ipx_type == IPX_TYPE_PPROP) { rc = ipxitf_pprop(intrfc, skb); if (rc) goto out_free_skb; } /* local processing follows */ if (!IPX_SKB_CB(skb)->ipx_dest_net) IPX_SKB_CB(skb)->ipx_dest_net = intrfc->if_netnum; if (!IPX_SKB_CB(skb)->ipx_source_net) IPX_SKB_CB(skb)->ipx_source_net = intrfc->if_netnum; /* it doesn't make sense to route a pprop packet, there's no meaning * in the ipx_dest_net for such packets */ if (ipx->ipx_type != IPX_TYPE_PPROP && intrfc->if_netnum != IPX_SKB_CB(skb)->ipx_dest_net) { /* We only route point-to-point packets. */ if (skb->pkt_type == PACKET_HOST) { skb = skb_unshare(skb, GFP_ATOMIC); if (skb) rc = ipxrtr_route_skb(skb); goto out_intrfc; } goto out_free_skb; } /* see if we should keep it */ if (!memcmp(ipx_broadcast_node, ipx->ipx_dest.node, IPX_NODE_LEN) || !memcmp(intrfc->if_node, ipx->ipx_dest.node, IPX_NODE_LEN)) { rc = ipxitf_demux_socket(intrfc, skb, 0); goto out_intrfc; } /* we couldn't pawn it off so unload it */ out_free_skb: kfree_skb(skb); out_intrfc: ipxitf_put(intrfc); return rc; } static void ipxitf_discover_netnum(struct ipx_interface *intrfc, struct sk_buff *skb) { const struct ipx_cb *cb = IPX_SKB_CB(skb); /* see if this is an intra packet: source_net == dest_net */ if (cb->ipx_source_net == cb->ipx_dest_net && cb->ipx_source_net) { struct ipx_interface *i = ipxitf_find_using_net(cb->ipx_source_net); /* NB: NetWare servers lie about their hop count so we * dropped the test based on it. This is the best way * to determine this is a 0 hop count packet. */ if (!i) { intrfc->if_netnum = cb->ipx_source_net; ipxitf_add_local_route(intrfc); } else { printk(KERN_WARNING "IPX: Network number collision " "%lx\n %s %s and %s %s\n", (unsigned long) ntohl(cb->ipx_source_net), ipx_device_name(i), ipx_frame_name(i->if_dlink_type), ipx_device_name(intrfc), ipx_frame_name(intrfc->if_dlink_type)); ipxitf_put(i); } } } /** * ipxitf_pprop - Process packet propagation IPX packet type 0x14, used for * NetBIOS broadcasts * @intrfc: IPX interface receiving this packet * @skb: Received packet * * Checks if packet is valid: if its more than %IPX_MAX_PPROP_HOPS hops or if it * is smaller than a IPX header + the room for %IPX_MAX_PPROP_HOPS hops we drop * it, not even processing it locally, if it has exact %IPX_MAX_PPROP_HOPS we * don't broadcast it, but process it locally. See chapter 5 of Novell's "IPX * RIP and SAP Router Specification", Part Number 107-000029-001. * * If it is valid, check if we have pprop broadcasting enabled by the user, * if not, just return zero for local processing. * * If it is enabled check the packet and don't broadcast it if we have already * seen this packet. * * Broadcast: send it to the interfaces that aren't on the packet visited nets * array, just after the IPX header. * * Returns -EINVAL for invalid packets, so that the calling function drops * the packet without local processing. 0 if packet is to be locally processed. */ static int ipxitf_pprop(struct ipx_interface *intrfc, struct sk_buff *skb) { struct ipxhdr *ipx = ipx_hdr(skb); int i, rc = -EINVAL; struct ipx_interface *ifcs; char *c; __be32 *l; /* Illegal packet - too many hops or too short */ /* We decide to throw it away: no broadcasting, no local processing. * NetBIOS unaware implementations route them as normal packets - * tctrl <= 15, any data payload... */ if (IPX_SKB_CB(skb)->ipx_tctrl > IPX_MAX_PPROP_HOPS || ntohs(ipx->ipx_pktsize) < sizeof(struct ipxhdr) + IPX_MAX_PPROP_HOPS * sizeof(u32)) goto out; /* are we broadcasting this damn thing? */ rc = 0; if (!sysctl_ipx_pprop_broadcasting) goto out; /* We do broadcast packet on the IPX_MAX_PPROP_HOPS hop, but we * process it locally. All previous hops broadcasted it, and process it * locally. */ if (IPX_SKB_CB(skb)->ipx_tctrl == IPX_MAX_PPROP_HOPS) goto out; c = ((u8 *) ipx) + sizeof(struct ipxhdr); l = (__be32 *) c; /* Don't broadcast packet if already seen this net */ for (i = 0; i < IPX_SKB_CB(skb)->ipx_tctrl; i++) if (*l++ == intrfc->if_netnum) goto out; /* < IPX_MAX_PPROP_HOPS hops && input interface not in list. Save the * position where we will insert recvd netnum into list, later on, * in ipxitf_send */ IPX_SKB_CB(skb)->last_hop.index = i; IPX_SKB_CB(skb)->last_hop.netnum = intrfc->if_netnum; /* xmit on all other interfaces... */ spin_lock_bh(&ipx_interfaces_lock); list_for_each_entry(ifcs, &ipx_interfaces, node) { /* Except unconfigured interfaces */ if (!ifcs->if_netnum) continue; /* That aren't in the list */ if (ifcs == intrfc) continue; l = (__be32 *) c; /* don't consider the last entry in the packet list, * it is our netnum, and it is not there yet */ for (i = 0; i < IPX_SKB_CB(skb)->ipx_tctrl; i++) if (ifcs->if_netnum == *l++) break; if (i == IPX_SKB_CB(skb)->ipx_tctrl) { struct sk_buff *s = skb_copy(skb, GFP_ATOMIC); if (s) { IPX_SKB_CB(s)->ipx_dest_net = ifcs->if_netnum; ipxrtr_route_skb(s); } } } spin_unlock_bh(&ipx_interfaces_lock); out: return rc; } static void ipxitf_insert(struct ipx_interface *intrfc) { spin_lock_bh(&ipx_interfaces_lock); list_add_tail(&intrfc->node, &ipx_interfaces); spin_unlock_bh(&ipx_interfaces_lock); if (ipxcfg_auto_select_primary && !ipx_primary_net) ipx_primary_net = intrfc; } static struct ipx_interface *ipxitf_alloc(struct net_device *dev, __be32 netnum, __be16 dlink_type, struct datalink_proto *dlink, unsigned char internal, int ipx_offset) { struct ipx_interface *intrfc = kmalloc(sizeof(*intrfc), GFP_ATOMIC); if (intrfc) { intrfc->if_dev = dev; intrfc->if_netnum = netnum; intrfc->if_dlink_type = dlink_type; intrfc->if_dlink = dlink; intrfc->if_internal = internal; intrfc->if_ipx_offset = ipx_offset; intrfc->if_sknum = IPX_MIN_EPHEMERAL_SOCKET; INIT_HLIST_HEAD(&intrfc->if_sklist); atomic_set(&intrfc->refcnt, 1); spin_lock_init(&intrfc->if_sklist_lock); } return intrfc; } static int ipxitf_create_internal(struct ipx_interface_definition *idef) { struct ipx_interface *intrfc; int rc = -EEXIST; /* Only one primary network allowed */ if (ipx_primary_net) goto out; /* Must have a valid network number */ rc = -EADDRNOTAVAIL; if (!idef->ipx_network) goto out; intrfc = ipxitf_find_using_net(idef->ipx_network); rc = -EADDRINUSE; if (intrfc) { ipxitf_put(intrfc); goto out; } intrfc = ipxitf_alloc(NULL, idef->ipx_network, 0, NULL, 1, 0); rc = -EAGAIN; if (!intrfc) goto out; memcpy((char *)&(intrfc->if_node), idef->ipx_node, IPX_NODE_LEN); ipx_internal_net = ipx_primary_net = intrfc; ipxitf_hold(intrfc); ipxitf_insert(intrfc); rc = ipxitf_add_local_route(intrfc); ipxitf_put(intrfc); out: return rc; } static __be16 ipx_map_frame_type(unsigned char type) { __be16 rc = 0; switch (type) { case IPX_FRAME_ETHERII: rc = htons(ETH_P_IPX); break; case IPX_FRAME_8022: rc = htons(ETH_P_802_2); break; case IPX_FRAME_SNAP: rc = htons(ETH_P_SNAP); break; case IPX_FRAME_8023: rc = htons(ETH_P_802_3); break; } return rc; } static int ipxitf_create(struct ipx_interface_definition *idef) { struct net_device *dev; __be16 dlink_type = 0; struct datalink_proto *datalink = NULL; struct ipx_interface *intrfc; int rc; if (idef->ipx_special == IPX_INTERNAL) { rc = ipxitf_create_internal(idef); goto out; } rc = -EEXIST; if (idef->ipx_special == IPX_PRIMARY && ipx_primary_net) goto out; intrfc = ipxitf_find_using_net(idef->ipx_network); rc = -EADDRINUSE; if (idef->ipx_network && intrfc) { ipxitf_put(intrfc); goto out; } if (intrfc) ipxitf_put(intrfc); dev = dev_get_by_name(&init_net, idef->ipx_device); rc = -ENODEV; if (!dev) goto out; switch (idef->ipx_dlink_type) { case IPX_FRAME_8022: dlink_type = htons(ETH_P_802_2); datalink = p8022_datalink; break; case IPX_FRAME_ETHERII: if (dev->type != ARPHRD_IEEE802) { dlink_type = htons(ETH_P_IPX); datalink = pEII_datalink; break; } /* fall through */ case IPX_FRAME_SNAP: dlink_type = htons(ETH_P_SNAP); datalink = pSNAP_datalink; break; case IPX_FRAME_8023: dlink_type = htons(ETH_P_802_3); datalink = p8023_datalink; break; case IPX_FRAME_NONE: default: rc = -EPROTONOSUPPORT; goto out_dev; } rc = -ENETDOWN; if (!(dev->flags & IFF_UP)) goto out_dev; /* Check addresses are suitable */ rc = -EINVAL; if (dev->addr_len > IPX_NODE_LEN) goto out_dev; intrfc = ipxitf_find_using_phys(dev, dlink_type); if (!intrfc) { /* Ok now create */ intrfc = ipxitf_alloc(dev, idef->ipx_network, dlink_type, datalink, 0, dev->hard_header_len + datalink->header_length); rc = -EAGAIN; if (!intrfc) goto out_dev; /* Setup primary if necessary */ if (idef->ipx_special == IPX_PRIMARY) ipx_primary_net = intrfc; if (!memcmp(idef->ipx_node, "\000\000\000\000\000\000", IPX_NODE_LEN)) { memset(intrfc->if_node, 0, IPX_NODE_LEN); memcpy(intrfc->if_node + IPX_NODE_LEN - dev->addr_len, dev->dev_addr, dev->addr_len); } else memcpy(intrfc->if_node, idef->ipx_node, IPX_NODE_LEN); ipxitf_hold(intrfc); ipxitf_insert(intrfc); } /* If the network number is known, add a route */ rc = 0; if (!intrfc->if_netnum) goto out_intrfc; rc = ipxitf_add_local_route(intrfc); out_intrfc: ipxitf_put(intrfc); goto out; out_dev: dev_put(dev); out: return rc; } static int ipxitf_delete(struct ipx_interface_definition *idef) { struct net_device *dev = NULL; __be16 dlink_type = 0; struct ipx_interface *intrfc; int rc = 0; spin_lock_bh(&ipx_interfaces_lock); if (idef->ipx_special == IPX_INTERNAL) { if (ipx_internal_net) { __ipxitf_put(ipx_internal_net); goto out; } rc = -ENOENT; goto out; } dlink_type = ipx_map_frame_type(idef->ipx_dlink_type); rc = -EPROTONOSUPPORT; if (!dlink_type) goto out; dev = __dev_get_by_name(&init_net, idef->ipx_device); rc = -ENODEV; if (!dev) goto out; intrfc = __ipxitf_find_using_phys(dev, dlink_type); rc = -EINVAL; if (!intrfc) goto out; __ipxitf_put(intrfc); rc = 0; out: spin_unlock_bh(&ipx_interfaces_lock); return rc; } static struct ipx_interface *ipxitf_auto_create(struct net_device *dev, __be16 dlink_type) { struct ipx_interface *intrfc = NULL; struct datalink_proto *datalink; if (!dev) goto out; /* Check addresses are suitable */ if (dev->addr_len > IPX_NODE_LEN) goto out; switch (ntohs(dlink_type)) { case ETH_P_IPX: datalink = pEII_datalink; break; case ETH_P_802_2: datalink = p8022_datalink; break; case ETH_P_SNAP: datalink = pSNAP_datalink; break; case ETH_P_802_3: datalink = p8023_datalink; break; default: goto out; } intrfc = ipxitf_alloc(dev, 0, dlink_type, datalink, 0, dev->hard_header_len + datalink->header_length); if (intrfc) { memset(intrfc->if_node, 0, IPX_NODE_LEN); memcpy((char *)&(intrfc->if_node[IPX_NODE_LEN-dev->addr_len]), dev->dev_addr, dev->addr_len); spin_lock_init(&intrfc->if_sklist_lock); atomic_set(&intrfc->refcnt, 1); ipxitf_insert(intrfc); dev_hold(dev); } out: return intrfc; } static int ipxitf_ioctl(unsigned int cmd, void __user *arg) { int rc = -EINVAL; struct ifreq ifr; int val; switch (cmd) { case SIOCSIFADDR: { struct sockaddr_ipx *sipx; struct ipx_interface_definition f; rc = -EFAULT; if (copy_from_user(&ifr, arg, sizeof(ifr))) break; sipx = (struct sockaddr_ipx *)&ifr.ifr_addr; rc = -EINVAL; if (sipx->sipx_family != AF_IPX) break; f.ipx_network = sipx->sipx_network; memcpy(f.ipx_device, ifr.ifr_name, sizeof(f.ipx_device)); memcpy(f.ipx_node, sipx->sipx_node, IPX_NODE_LEN); f.ipx_dlink_type = sipx->sipx_type; f.ipx_special = sipx->sipx_special; if (sipx->sipx_action == IPX_DLTITF) rc = ipxitf_delete(&f); else rc = ipxitf_create(&f); break; } case SIOCGIFADDR: { struct sockaddr_ipx *sipx; struct ipx_interface *ipxif; struct net_device *dev; rc = -EFAULT; if (copy_from_user(&ifr, arg, sizeof(ifr))) break; sipx = (struct sockaddr_ipx *)&ifr.ifr_addr; dev = __dev_get_by_name(&init_net, ifr.ifr_name); rc = -ENODEV; if (!dev) break; ipxif = ipxitf_find_using_phys(dev, ipx_map_frame_type(sipx->sipx_type)); rc = -EADDRNOTAVAIL; if (!ipxif) break; sipx->sipx_family = AF_IPX; sipx->sipx_network = ipxif->if_netnum; memcpy(sipx->sipx_node, ipxif->if_node, sizeof(sipx->sipx_node)); rc = -EFAULT; if (copy_to_user(arg, &ifr, sizeof(ifr))) break; ipxitf_put(ipxif); rc = 0; break; } case SIOCAIPXITFCRT: rc = -EFAULT; if (get_user(val, (unsigned char __user *) arg)) break; rc = 0; ipxcfg_auto_create_interfaces = val; break; case SIOCAIPXPRISLT: rc = -EFAULT; if (get_user(val, (unsigned char __user *) arg)) break; rc = 0; ipxcfg_set_auto_select(val); break; } return rc; } /* * Checksum routine for IPX */ /* Note: We assume ipx_tctrl==0 and htons(length)==ipx_pktsize */ /* This functions should *not* mess with packet contents */ __be16 ipx_cksum(struct ipxhdr *packet, int length) { /* * NOTE: sum is a net byte order quantity, which optimizes the * loop. This only works on big and little endian machines. (I * don't know of a machine that isn't.) */ /* handle the first 3 words separately; checksum should be skipped * and ipx_tctrl masked out */ __u16 *p = (__u16 *)packet; __u32 sum = p[1] + (p[2] & (__force u16)htons(0x00ff)); __u32 i = (length >> 1) - 3; /* Number of remaining complete words */ /* Loop through them */ p += 3; while (i--) sum += *p++; /* Add on the last part word if it exists */ if (packet->ipx_pktsize & htons(1)) sum += (__force u16)htons(0xff00) & *p; /* Do final fixup */ sum = (sum & 0xffff) + (sum >> 16); /* It's a pity there's no concept of carry in C */ if (sum >= 0x10000) sum++; /* * Leave 0 alone; we don't want 0xffff here. Note that we can't get * here with 0x10000, so this check is the same as ((__u16)sum) */ if (sum) sum = ~sum; return (__force __be16)sum; } const char *ipx_frame_name(__be16 frame) { char* rc = "None"; switch (ntohs(frame)) { case ETH_P_IPX: rc = "EtherII"; break; case ETH_P_802_2: rc = "802.2"; break; case ETH_P_SNAP: rc = "SNAP"; break; case ETH_P_802_3: rc = "802.3"; break; } return rc; } const char *ipx_device_name(struct ipx_interface *intrfc) { return intrfc->if_internal ? "Internal" : intrfc->if_dev ? intrfc->if_dev->name : "Unknown"; } /* Handling for system calls applied via the various interfaces to an IPX * socket object. */ static int ipx_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen) { struct sock *sk = sock->sk; int opt; int rc = -EINVAL; lock_sock(sk); if (optlen != sizeof(int)) goto out; rc = -EFAULT; if (get_user(opt, (unsigned int __user *)optval)) goto out; rc = -ENOPROTOOPT; if (!(level == SOL_IPX && optname == IPX_TYPE)) goto out; ipx_sk(sk)->type = opt; rc = 0; out: release_sock(sk); return rc; } static int ipx_getsockopt(struct socket *sock, int level, int optname, char __user *optval, int __user *optlen) { struct sock *sk = sock->sk; int val = 0; int len; int rc = -ENOPROTOOPT; lock_sock(sk); if (!(level == SOL_IPX && optname == IPX_TYPE)) goto out; val = ipx_sk(sk)->type; rc = -EFAULT; if (get_user(len, optlen)) goto out; len = min_t(unsigned int, len, sizeof(int)); rc = -EINVAL; if(len < 0) goto out; rc = -EFAULT; if (put_user(len, optlen) || copy_to_user(optval, &val, len)) goto out; rc = 0; out: release_sock(sk); return rc; } static struct proto ipx_proto = { .name = "IPX", .owner = THIS_MODULE, .obj_size = sizeof(struct ipx_sock), }; static int ipx_create(struct net *net, struct socket *sock, int protocol, int kern) { int rc = -ESOCKTNOSUPPORT; struct sock *sk; if (!net_eq(net, &init_net)) return -EAFNOSUPPORT; /* * SPX support is not anymore in the kernel sources. If you want to * ressurrect it, completing it and making it understand shared skbs, * be fully multithreaded, etc, grab the sources in an early 2.5 kernel * tree. */ if (sock->type != SOCK_DGRAM) goto out; rc = -ENOMEM; sk = sk_alloc(net, PF_IPX, GFP_KERNEL, &ipx_proto); if (!sk) goto out; sk_refcnt_debug_inc(sk); sock_init_data(sock, sk); sk->sk_no_check = 1; /* Checksum off by default */ sock->ops = &ipx_dgram_ops; rc = 0; out: return rc; } static int ipx_release(struct socket *sock) { struct sock *sk = sock->sk; if (!sk) goto out; lock_sock(sk); if (!sock_flag(sk, SOCK_DEAD)) sk->sk_state_change(sk); sock_set_flag(sk, SOCK_DEAD); sock->sk = NULL; sk_refcnt_debug_release(sk); ipx_destroy_socket(sk); release_sock(sk); sock_put(sk); out: return 0; } /* caller must hold a reference to intrfc */ static __be16 ipx_first_free_socketnum(struct ipx_interface *intrfc) { unsigned short socketNum = intrfc->if_sknum; spin_lock_bh(&intrfc->if_sklist_lock); if (socketNum < IPX_MIN_EPHEMERAL_SOCKET) socketNum = IPX_MIN_EPHEMERAL_SOCKET; while (__ipxitf_find_socket(intrfc, htons(socketNum))) if (socketNum > IPX_MAX_EPHEMERAL_SOCKET) socketNum = IPX_MIN_EPHEMERAL_SOCKET; else socketNum++; spin_unlock_bh(&intrfc->if_sklist_lock); intrfc->if_sknum = socketNum; return htons(socketNum); } static int __ipx_bind(struct socket *sock, struct sockaddr *uaddr, int addr_len) { struct sock *sk = sock->sk; struct ipx_sock *ipxs = ipx_sk(sk); struct ipx_interface *intrfc; struct sockaddr_ipx *addr = (struct sockaddr_ipx *)uaddr; int rc = -EINVAL; if (!sock_flag(sk, SOCK_ZAPPED) || addr_len != sizeof(struct sockaddr_ipx)) goto out; intrfc = ipxitf_find_using_net(addr->sipx_network); rc = -EADDRNOTAVAIL; if (!intrfc) goto out; if (!addr->sipx_port) { addr->sipx_port = ipx_first_free_socketnum(intrfc); rc = -EINVAL; if (!addr->sipx_port) goto out_put; } /* protect IPX system stuff like routing/sap */ rc = -EACCES; if (ntohs(addr->sipx_port) < IPX_MIN_EPHEMERAL_SOCKET && !capable(CAP_NET_ADMIN)) goto out_put; ipxs->port = addr->sipx_port; #ifdef CONFIG_IPX_INTERN if (intrfc == ipx_internal_net) { /* The source address is to be set explicitly if the * socket is to be bound on the internal network. If a * node number 0 was specified, the default is used. */ rc = -EINVAL; if (!memcmp(addr->sipx_node, ipx_broadcast_node, IPX_NODE_LEN)) goto out_put; if (!memcmp(addr->sipx_node, ipx_this_node, IPX_NODE_LEN)) memcpy(ipxs->node, intrfc->if_node, IPX_NODE_LEN); else memcpy(ipxs->node, addr->sipx_node, IPX_NODE_LEN); rc = -EADDRINUSE; if (ipxitf_find_internal_socket(intrfc, ipxs->node, ipxs->port)) { SOCK_DEBUG(sk, "IPX: bind failed because port %X in use.\n", ntohs(addr->sipx_port)); goto out_put; } } else { /* Source addresses are easy. It must be our * network:node pair for an interface routed to IPX * with the ipx routing ioctl() */ memcpy(ipxs->node, intrfc->if_node, IPX_NODE_LEN); rc = -EADDRINUSE; if (ipxitf_find_socket(intrfc, addr->sipx_port)) { SOCK_DEBUG(sk, "IPX: bind failed because port %X in use.\n", ntohs(addr->sipx_port)); goto out_put; } } #else /* !def CONFIG_IPX_INTERN */ /* Source addresses are easy. It must be our network:node pair for an interface routed to IPX with the ipx routing ioctl() */ rc = -EADDRINUSE; if (ipxitf_find_socket(intrfc, addr->sipx_port)) { SOCK_DEBUG(sk, "IPX: bind failed because port %X in use.\n", ntohs((int)addr->sipx_port)); goto out_put; } #endif /* CONFIG_IPX_INTERN */ ipxitf_insert_socket(intrfc, sk); sock_reset_flag(sk, SOCK_ZAPPED); rc = 0; out_put: ipxitf_put(intrfc); out: return rc; } static int ipx_bind(struct socket *sock, struct sockaddr *uaddr, int addr_len) { struct sock *sk = sock->sk; int rc; lock_sock(sk); rc = __ipx_bind(sock, uaddr, addr_len); release_sock(sk); return rc; } static int ipx_connect(struct socket *sock, struct sockaddr *uaddr, int addr_len, int flags) { struct sock *sk = sock->sk; struct ipx_sock *ipxs = ipx_sk(sk); struct sockaddr_ipx *addr; int rc = -EINVAL; struct ipx_route *rt; sk->sk_state = TCP_CLOSE; sock->state = SS_UNCONNECTED; lock_sock(sk); if (addr_len != sizeof(*addr)) goto out; addr = (struct sockaddr_ipx *)uaddr; /* put the autobinding in */ if (!ipxs->port) { struct sockaddr_ipx uaddr; uaddr.sipx_port = 0; uaddr.sipx_network = 0; #ifdef CONFIG_IPX_INTERN rc = -ENETDOWN; if (!ipxs->intrfc) goto out; /* Someone zonked the iface */ memcpy(uaddr.sipx_node, ipxs->intrfc->if_node, IPX_NODE_LEN); #endif /* CONFIG_IPX_INTERN */ rc = __ipx_bind(sock, (struct sockaddr *)&uaddr, sizeof(struct sockaddr_ipx)); if (rc) goto out; } /* We can either connect to primary network or somewhere * we can route to */ rt = ipxrtr_lookup(addr->sipx_network); rc = -ENETUNREACH; if (!rt && !(!addr->sipx_network && ipx_primary_net)) goto out; ipxs->dest_addr.net = addr->sipx_network; ipxs->dest_addr.sock = addr->sipx_port; memcpy(ipxs->dest_addr.node, addr->sipx_node, IPX_NODE_LEN); ipxs->type = addr->sipx_type; if (sock->type == SOCK_DGRAM) { sock->state = SS_CONNECTED; sk->sk_state = TCP_ESTABLISHED; } if (rt) ipxrtr_put(rt); rc = 0; out: release_sock(sk); return rc; } static int ipx_getname(struct socket *sock, struct sockaddr *uaddr, int *uaddr_len, int peer) { struct ipx_address *addr; struct sockaddr_ipx sipx; struct sock *sk = sock->sk; struct ipx_sock *ipxs = ipx_sk(sk); int rc; *uaddr_len = sizeof(struct sockaddr_ipx); lock_sock(sk); if (peer) { rc = -ENOTCONN; if (sk->sk_state != TCP_ESTABLISHED) goto out; addr = &ipxs->dest_addr; sipx.sipx_network = addr->net; sipx.sipx_port = addr->sock; memcpy(sipx.sipx_node, addr->node, IPX_NODE_LEN); } else { if (ipxs->intrfc) { sipx.sipx_network = ipxs->intrfc->if_netnum; #ifdef CONFIG_IPX_INTERN memcpy(sipx.sipx_node, ipxs->node, IPX_NODE_LEN); #else memcpy(sipx.sipx_node, ipxs->intrfc->if_node, IPX_NODE_LEN); #endif /* CONFIG_IPX_INTERN */ } else { sipx.sipx_network = 0; memset(sipx.sipx_node, '\0', IPX_NODE_LEN); } sipx.sipx_port = ipxs->port; } sipx.sipx_family = AF_IPX; sipx.sipx_type = ipxs->type; sipx.sipx_zero = 0; memcpy(uaddr, &sipx, sizeof(sipx)); rc = 0; out: release_sock(sk); return rc; } static int ipx_rcv(struct sk_buff *skb, struct net_device *dev, struct packet_type *pt, struct net_device *orig_dev) { /* NULL here for pt means the packet was looped back */ struct ipx_interface *intrfc; struct ipxhdr *ipx; u16 ipx_pktsize; int rc = 0; if (!net_eq(dev_net(dev), &init_net)) goto drop; /* Not ours */ if (skb->pkt_type == PACKET_OTHERHOST) goto drop; if ((skb = skb_share_check(skb, GFP_ATOMIC)) == NULL) goto out; if (!pskb_may_pull(skb, sizeof(struct ipxhdr))) goto drop; ipx_pktsize = ntohs(ipx_hdr(skb)->ipx_pktsize); /* Too small or invalid header? */ if (ipx_pktsize < sizeof(struct ipxhdr) || !pskb_may_pull(skb, ipx_pktsize)) goto drop; ipx = ipx_hdr(skb); if (ipx->ipx_checksum != IPX_NO_CHECKSUM && ipx->ipx_checksum != ipx_cksum(ipx, ipx_pktsize)) goto drop; IPX_SKB_CB(skb)->ipx_tctrl = ipx->ipx_tctrl; IPX_SKB_CB(skb)->ipx_dest_net = ipx->ipx_dest.net; IPX_SKB_CB(skb)->ipx_source_net = ipx->ipx_source.net; /* Determine what local ipx endpoint this is */ intrfc = ipxitf_find_using_phys(dev, pt->type); if (!intrfc) { if (ipxcfg_auto_create_interfaces && IPX_SKB_CB(skb)->ipx_dest_net) { intrfc = ipxitf_auto_create(dev, pt->type); if (intrfc) ipxitf_hold(intrfc); } if (!intrfc) /* Not one of ours */ /* or invalid packet for auto creation */ goto drop; } rc = ipxitf_rcv(intrfc, skb); ipxitf_put(intrfc); goto out; drop: kfree_skb(skb); out: return rc; } static int ipx_sendmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t len) { struct sock *sk = sock->sk; struct ipx_sock *ipxs = ipx_sk(sk); struct sockaddr_ipx *usipx = (struct sockaddr_ipx *)msg->msg_name; struct sockaddr_ipx local_sipx; int rc = -EINVAL; int flags = msg->msg_flags; lock_sock(sk); /* Socket gets bound below anyway */ /* if (sk->sk_zapped) return -EIO; */ /* Socket not bound */ if (flags & ~(MSG_DONTWAIT|MSG_CMSG_COMPAT)) goto out; /* Max possible packet size limited by 16 bit pktsize in header */ if (len >= 65535 - sizeof(struct ipxhdr)) goto out; if (usipx) { if (!ipxs->port) { struct sockaddr_ipx uaddr; uaddr.sipx_port = 0; uaddr.sipx_network = 0; #ifdef CONFIG_IPX_INTERN rc = -ENETDOWN; if (!ipxs->intrfc) goto out; /* Someone zonked the iface */ memcpy(uaddr.sipx_node, ipxs->intrfc->if_node, IPX_NODE_LEN); #endif rc = __ipx_bind(sock, (struct sockaddr *)&uaddr, sizeof(struct sockaddr_ipx)); if (rc) goto out; } rc = -EINVAL; if (msg->msg_namelen < sizeof(*usipx) || usipx->sipx_family != AF_IPX) goto out; } else { rc = -ENOTCONN; if (sk->sk_state != TCP_ESTABLISHED) goto out; usipx = &local_sipx; usipx->sipx_family = AF_IPX; usipx->sipx_type = ipxs->type; usipx->sipx_port = ipxs->dest_addr.sock; usipx->sipx_network = ipxs->dest_addr.net; memcpy(usipx->sipx_node, ipxs->dest_addr.node, IPX_NODE_LEN); } rc = ipxrtr_route_packet(sk, usipx, msg->msg_iov, len, flags & MSG_DONTWAIT); if (rc >= 0) rc = len; out: release_sock(sk); return rc; } static int ipx_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t size, int flags) { struct sock *sk = sock->sk; struct ipx_sock *ipxs = ipx_sk(sk); struct sockaddr_ipx *sipx = (struct sockaddr_ipx *)msg->msg_name; struct ipxhdr *ipx = NULL; struct sk_buff *skb; int copied, rc; lock_sock(sk); /* put the autobinding in */ if (!ipxs->port) { struct sockaddr_ipx uaddr; uaddr.sipx_port = 0; uaddr.sipx_network = 0; #ifdef CONFIG_IPX_INTERN rc = -ENETDOWN; if (!ipxs->intrfc) goto out; /* Someone zonked the iface */ memcpy(uaddr.sipx_node, ipxs->intrfc->if_node, IPX_NODE_LEN); #endif /* CONFIG_IPX_INTERN */ rc = __ipx_bind(sock, (struct sockaddr *)&uaddr, sizeof(struct sockaddr_ipx)); if (rc) goto out; } rc = -ENOTCONN; if (sock_flag(sk, SOCK_ZAPPED)) goto out; skb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT, flags & MSG_DONTWAIT, &rc); if (!skb) goto out; ipx = ipx_hdr(skb); copied = ntohs(ipx->ipx_pktsize) - sizeof(struct ipxhdr); if (copied > size) { copied = size; msg->msg_flags |= MSG_TRUNC; } rc = skb_copy_datagram_iovec(skb, sizeof(struct ipxhdr), msg->msg_iov, copied); if (rc) goto out_free; if (skb->tstamp.tv64) sk->sk_stamp = skb->tstamp; msg->msg_namelen = sizeof(*sipx); if (sipx) { sipx->sipx_family = AF_IPX; sipx->sipx_port = ipx->ipx_source.sock; memcpy(sipx->sipx_node, ipx->ipx_source.node, IPX_NODE_LEN); sipx->sipx_network = IPX_SKB_CB(skb)->ipx_source_net; sipx->sipx_type = ipx->ipx_type; sipx->sipx_zero = 0; } rc = copied; out_free: skb_free_datagram(sk, skb); out: release_sock(sk); return rc; } static int ipx_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg) { int rc = 0; long amount = 0; struct sock *sk = sock->sk; void __user *argp = (void __user *)arg; lock_sock(sk); switch (cmd) { case TIOCOUTQ: amount = sk->sk_sndbuf - sk_wmem_alloc_get(sk); if (amount < 0) amount = 0; rc = put_user(amount, (int __user *)argp); break; case TIOCINQ: { struct sk_buff *skb = skb_peek(&sk->sk_receive_queue); /* These two are safe on a single CPU system as only * user tasks fiddle here */ if (skb) amount = skb->len - sizeof(struct ipxhdr); rc = put_user(amount, (int __user *)argp); break; } case SIOCADDRT: case SIOCDELRT: rc = -EPERM; if (capable(CAP_NET_ADMIN)) rc = ipxrtr_ioctl(cmd, argp); break; case SIOCSIFADDR: case SIOCAIPXITFCRT: case SIOCAIPXPRISLT: rc = -EPERM; if (!capable(CAP_NET_ADMIN)) break; case SIOCGIFADDR: rc = ipxitf_ioctl(cmd, argp); break; case SIOCIPXCFGDATA: rc = ipxcfg_get_config_data(argp); break; case SIOCIPXNCPCONN: /* * This socket wants to take care of the NCP connection * handed to us in arg. */ rc = -EPERM; if (!capable(CAP_NET_ADMIN)) break; rc = get_user(ipx_sk(sk)->ipx_ncp_conn, (const unsigned short __user *)argp); break; case SIOCGSTAMP: rc = sock_get_timestamp(sk, argp); break; case SIOCGIFDSTADDR: case SIOCSIFDSTADDR: case SIOCGIFBRDADDR: case SIOCSIFBRDADDR: case SIOCGIFNETMASK: case SIOCSIFNETMASK: rc = -EINVAL; break; default: rc = -ENOIOCTLCMD; break; } release_sock(sk); return rc; } #ifdef CONFIG_COMPAT static int ipx_compat_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg) { /* * These 4 commands use same structure on 32bit and 64bit. Rest of IPX * commands is handled by generic ioctl code. As these commands are * SIOCPROTOPRIVATE..SIOCPROTOPRIVATE+3, they cannot be handled by generic * code. */ switch (cmd) { case SIOCAIPXITFCRT: case SIOCAIPXPRISLT: case SIOCIPXCFGDATA: case SIOCIPXNCPCONN: return ipx_ioctl(sock, cmd, arg); default: return -ENOIOCTLCMD; } } #endif /* * Socket family declarations */ static const struct net_proto_family ipx_family_ops = { .family = PF_IPX, .create = ipx_create, .owner = THIS_MODULE, }; static const struct proto_ops ipx_dgram_ops = { .family = PF_IPX, .owner = THIS_MODULE, .release = ipx_release, .bind = ipx_bind, .connect = ipx_connect, .socketpair = sock_no_socketpair, .accept = sock_no_accept, .getname = ipx_getname, .poll = datagram_poll, .ioctl = ipx_ioctl, #ifdef CONFIG_COMPAT .compat_ioctl = ipx_compat_ioctl, #endif .listen = sock_no_listen, .shutdown = sock_no_shutdown, /* FIXME: support shutdown */ .setsockopt = ipx_setsockopt, .getsockopt = ipx_getsockopt, .sendmsg = ipx_sendmsg, .recvmsg = ipx_recvmsg, .mmap = sock_no_mmap, .sendpage = sock_no_sendpage, }; static struct packet_type ipx_8023_packet_type __read_mostly = { .type = cpu_to_be16(ETH_P_802_3), .func = ipx_rcv, }; static struct packet_type ipx_dix_packet_type __read_mostly = { .type = cpu_to_be16(ETH_P_IPX), .func = ipx_rcv, }; static struct notifier_block ipx_dev_notifier = { .notifier_call = ipxitf_device_event, }; extern struct datalink_proto *make_EII_client(void); extern void destroy_EII_client(struct datalink_proto *); static const unsigned char ipx_8022_type = 0xE0; static const unsigned char ipx_snap_id[5] = { 0x0, 0x0, 0x0, 0x81, 0x37 }; static const char ipx_EII_err_msg[] __initconst = KERN_CRIT "IPX: Unable to register with Ethernet II\n"; static const char ipx_8023_err_msg[] __initconst = KERN_CRIT "IPX: Unable to register with 802.3\n"; static const char ipx_llc_err_msg[] __initconst = KERN_CRIT "IPX: Unable to register with 802.2\n"; static const char ipx_snap_err_msg[] __initconst = KERN_CRIT "IPX: Unable to register with SNAP\n"; static int __init ipx_init(void) { int rc = proto_register(&ipx_proto, 1); if (rc != 0) goto out; sock_register(&ipx_family_ops); pEII_datalink = make_EII_client(); if (pEII_datalink) dev_add_pack(&ipx_dix_packet_type); else printk(ipx_EII_err_msg); p8023_datalink = make_8023_client(); if (p8023_datalink) dev_add_pack(&ipx_8023_packet_type); else printk(ipx_8023_err_msg); p8022_datalink = register_8022_client(ipx_8022_type, ipx_rcv); if (!p8022_datalink) printk(ipx_llc_err_msg); pSNAP_datalink = register_snap_client(ipx_snap_id, ipx_rcv); if (!pSNAP_datalink) printk(ipx_snap_err_msg); register_netdevice_notifier(&ipx_dev_notifier); ipx_register_sysctl(); ipx_proc_init(); out: return rc; } static void __exit ipx_proto_finito(void) { ipx_proc_exit(); ipx_unregister_sysctl(); unregister_netdevice_notifier(&ipx_dev_notifier); ipxitf_cleanup(); if (pSNAP_datalink) { unregister_snap_client(pSNAP_datalink); pSNAP_datalink = NULL; } if (p8022_datalink) { unregister_8022_client(p8022_datalink); p8022_datalink = NULL; } dev_remove_pack(&ipx_8023_packet_type); if (p8023_datalink) { destroy_8023_client(p8023_datalink); p8023_datalink = NULL; } dev_remove_pack(&ipx_dix_packet_type); if (pEII_datalink) { destroy_EII_client(pEII_datalink); pEII_datalink = NULL; } proto_unregister(&ipx_proto); sock_unregister(ipx_family_ops.family); } module_init(ipx_init); module_exit(ipx_proto_finito); MODULE_LICENSE("GPL"); MODULE_ALIAS_NETPROTO(PF_IPX);
./CrossVul/dataset_final_sorted/CWE-20/c/bad_5845_15
crossvul-cpp_data_bad_2115_0
/* * Derived from "arch/i386/kernel/process.c" * Copyright (C) 1995 Linus Torvalds * * Updated and modified by Cort Dougan (cort@cs.nmt.edu) and * Paul Mackerras (paulus@cs.anu.edu.au) * * PowerPC version * Copyright (C) 1995-1996 Gary Thomas (gdt@linuxppc.org) * * 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/errno.h> #include <linux/sched.h> #include <linux/kernel.h> #include <linux/mm.h> #include <linux/smp.h> #include <linux/stddef.h> #include <linux/unistd.h> #include <linux/ptrace.h> #include <linux/slab.h> #include <linux/user.h> #include <linux/elf.h> #include <linux/prctl.h> #include <linux/init_task.h> #include <linux/export.h> #include <linux/kallsyms.h> #include <linux/mqueue.h> #include <linux/hardirq.h> #include <linux/utsname.h> #include <linux/ftrace.h> #include <linux/kernel_stat.h> #include <linux/personality.h> #include <linux/random.h> #include <linux/hw_breakpoint.h> #include <asm/pgtable.h> #include <asm/uaccess.h> #include <asm/io.h> #include <asm/processor.h> #include <asm/mmu.h> #include <asm/prom.h> #include <asm/machdep.h> #include <asm/time.h> #include <asm/runlatch.h> #include <asm/syscalls.h> #include <asm/switch_to.h> #include <asm/tm.h> #include <asm/debug.h> #ifdef CONFIG_PPC64 #include <asm/firmware.h> #endif #include <linux/kprobes.h> #include <linux/kdebug.h> /* Transactional Memory debug */ #ifdef TM_DEBUG_SW #define TM_DEBUG(x...) printk(KERN_INFO x) #else #define TM_DEBUG(x...) do { } while(0) #endif extern unsigned long _get_SP(void); #ifndef CONFIG_SMP struct task_struct *last_task_used_math = NULL; struct task_struct *last_task_used_altivec = NULL; struct task_struct *last_task_used_vsx = NULL; struct task_struct *last_task_used_spe = NULL; #endif #ifdef CONFIG_PPC_TRANSACTIONAL_MEM void giveup_fpu_maybe_transactional(struct task_struct *tsk) { /* * If we are saving the current thread's registers, and the * thread is in a transactional state, set the TIF_RESTORE_TM * bit so that we know to restore the registers before * returning to userspace. */ if (tsk == current && tsk->thread.regs && MSR_TM_ACTIVE(tsk->thread.regs->msr) && !test_thread_flag(TIF_RESTORE_TM)) { tsk->thread.tm_orig_msr = tsk->thread.regs->msr; set_thread_flag(TIF_RESTORE_TM); } giveup_fpu(tsk); } void giveup_altivec_maybe_transactional(struct task_struct *tsk) { /* * If we are saving the current thread's registers, and the * thread is in a transactional state, set the TIF_RESTORE_TM * bit so that we know to restore the registers before * returning to userspace. */ if (tsk == current && tsk->thread.regs && MSR_TM_ACTIVE(tsk->thread.regs->msr) && !test_thread_flag(TIF_RESTORE_TM)) { tsk->thread.tm_orig_msr = tsk->thread.regs->msr; set_thread_flag(TIF_RESTORE_TM); } giveup_altivec(tsk); } #else #define giveup_fpu_maybe_transactional(tsk) giveup_fpu(tsk) #define giveup_altivec_maybe_transactional(tsk) giveup_altivec(tsk) #endif /* CONFIG_PPC_TRANSACTIONAL_MEM */ #ifdef CONFIG_PPC_FPU /* * Make sure the floating-point register state in the * the thread_struct is up to date for task tsk. */ void flush_fp_to_thread(struct task_struct *tsk) { if (tsk->thread.regs) { /* * We need to disable preemption here because if we didn't, * another process could get scheduled after the regs->msr * test but before we have finished saving the FP registers * to the thread_struct. That process could take over the * FPU, and then when we get scheduled again we would store * bogus values for the remaining FP registers. */ preempt_disable(); if (tsk->thread.regs->msr & MSR_FP) { #ifdef CONFIG_SMP /* * This should only ever be called for current or * for a stopped child process. Since we save away * the FP register state on context switch on SMP, * there is something wrong if a stopped child appears * to still have its FP state in the CPU registers. */ BUG_ON(tsk != current); #endif giveup_fpu_maybe_transactional(tsk); } preempt_enable(); } } EXPORT_SYMBOL_GPL(flush_fp_to_thread); #endif /* CONFIG_PPC_FPU */ void enable_kernel_fp(void) { WARN_ON(preemptible()); #ifdef CONFIG_SMP if (current->thread.regs && (current->thread.regs->msr & MSR_FP)) giveup_fpu_maybe_transactional(current); else giveup_fpu(NULL); /* just enables FP for kernel */ #else giveup_fpu_maybe_transactional(last_task_used_math); #endif /* CONFIG_SMP */ } EXPORT_SYMBOL(enable_kernel_fp); #ifdef CONFIG_ALTIVEC void enable_kernel_altivec(void) { WARN_ON(preemptible()); #ifdef CONFIG_SMP if (current->thread.regs && (current->thread.regs->msr & MSR_VEC)) giveup_altivec_maybe_transactional(current); else giveup_altivec_notask(); #else giveup_altivec_maybe_transactional(last_task_used_altivec); #endif /* CONFIG_SMP */ } EXPORT_SYMBOL(enable_kernel_altivec); /* * Make sure the VMX/Altivec register state in the * the thread_struct is up to date for task tsk. */ void flush_altivec_to_thread(struct task_struct *tsk) { if (tsk->thread.regs) { preempt_disable(); if (tsk->thread.regs->msr & MSR_VEC) { #ifdef CONFIG_SMP BUG_ON(tsk != current); #endif giveup_altivec_maybe_transactional(tsk); } preempt_enable(); } } EXPORT_SYMBOL_GPL(flush_altivec_to_thread); #endif /* CONFIG_ALTIVEC */ #ifdef CONFIG_VSX #if 0 /* not currently used, but some crazy RAID module might want to later */ void enable_kernel_vsx(void) { WARN_ON(preemptible()); #ifdef CONFIG_SMP if (current->thread.regs && (current->thread.regs->msr & MSR_VSX)) giveup_vsx(current); else giveup_vsx(NULL); /* just enable vsx for kernel - force */ #else giveup_vsx(last_task_used_vsx); #endif /* CONFIG_SMP */ } EXPORT_SYMBOL(enable_kernel_vsx); #endif void giveup_vsx(struct task_struct *tsk) { giveup_fpu_maybe_transactional(tsk); giveup_altivec_maybe_transactional(tsk); __giveup_vsx(tsk); } void flush_vsx_to_thread(struct task_struct *tsk) { if (tsk->thread.regs) { preempt_disable(); if (tsk->thread.regs->msr & MSR_VSX) { #ifdef CONFIG_SMP BUG_ON(tsk != current); #endif giveup_vsx(tsk); } preempt_enable(); } } EXPORT_SYMBOL_GPL(flush_vsx_to_thread); #endif /* CONFIG_VSX */ #ifdef CONFIG_SPE void enable_kernel_spe(void) { WARN_ON(preemptible()); #ifdef CONFIG_SMP if (current->thread.regs && (current->thread.regs->msr & MSR_SPE)) giveup_spe(current); else giveup_spe(NULL); /* just enable SPE for kernel - force */ #else giveup_spe(last_task_used_spe); #endif /* __SMP __ */ } EXPORT_SYMBOL(enable_kernel_spe); void flush_spe_to_thread(struct task_struct *tsk) { if (tsk->thread.regs) { preempt_disable(); if (tsk->thread.regs->msr & MSR_SPE) { #ifdef CONFIG_SMP BUG_ON(tsk != current); #endif tsk->thread.spefscr = mfspr(SPRN_SPEFSCR); giveup_spe(tsk); } preempt_enable(); } } #endif /* CONFIG_SPE */ #ifndef CONFIG_SMP /* * If we are doing lazy switching of CPU state (FP, altivec or SPE), * and the current task has some state, discard it. */ void discard_lazy_cpu_state(void) { preempt_disable(); if (last_task_used_math == current) last_task_used_math = NULL; #ifdef CONFIG_ALTIVEC if (last_task_used_altivec == current) last_task_used_altivec = NULL; #endif /* CONFIG_ALTIVEC */ #ifdef CONFIG_VSX if (last_task_used_vsx == current) last_task_used_vsx = NULL; #endif /* CONFIG_VSX */ #ifdef CONFIG_SPE if (last_task_used_spe == current) last_task_used_spe = NULL; #endif preempt_enable(); } #endif /* CONFIG_SMP */ #ifdef CONFIG_PPC_ADV_DEBUG_REGS void do_send_trap(struct pt_regs *regs, unsigned long address, unsigned long error_code, int signal_code, int breakpt) { siginfo_t info; current->thread.trap_nr = signal_code; if (notify_die(DIE_DABR_MATCH, "dabr_match", regs, error_code, 11, SIGSEGV) == NOTIFY_STOP) return; /* Deliver the signal to userspace */ info.si_signo = SIGTRAP; info.si_errno = breakpt; /* breakpoint or watchpoint id */ info.si_code = signal_code; info.si_addr = (void __user *)address; force_sig_info(SIGTRAP, &info, current); } #else /* !CONFIG_PPC_ADV_DEBUG_REGS */ void do_break (struct pt_regs *regs, unsigned long address, unsigned long error_code) { siginfo_t info; current->thread.trap_nr = TRAP_HWBKPT; if (notify_die(DIE_DABR_MATCH, "dabr_match", regs, error_code, 11, SIGSEGV) == NOTIFY_STOP) return; if (debugger_break_match(regs)) return; /* Clear the breakpoint */ hw_breakpoint_disable(); /* Deliver the signal to userspace */ info.si_signo = SIGTRAP; info.si_errno = 0; info.si_code = TRAP_HWBKPT; info.si_addr = (void __user *)address; force_sig_info(SIGTRAP, &info, current); } #endif /* CONFIG_PPC_ADV_DEBUG_REGS */ static DEFINE_PER_CPU(struct arch_hw_breakpoint, current_brk); #ifdef CONFIG_PPC_ADV_DEBUG_REGS /* * Set the debug registers back to their default "safe" values. */ static void set_debug_reg_defaults(struct thread_struct *thread) { thread->debug.iac1 = thread->debug.iac2 = 0; #if CONFIG_PPC_ADV_DEBUG_IACS > 2 thread->debug.iac3 = thread->debug.iac4 = 0; #endif thread->debug.dac1 = thread->debug.dac2 = 0; #if CONFIG_PPC_ADV_DEBUG_DVCS > 0 thread->debug.dvc1 = thread->debug.dvc2 = 0; #endif thread->debug.dbcr0 = 0; #ifdef CONFIG_BOOKE /* * Force User/Supervisor bits to b11 (user-only MSR[PR]=1) */ thread->debug.dbcr1 = DBCR1_IAC1US | DBCR1_IAC2US | DBCR1_IAC3US | DBCR1_IAC4US; /* * Force Data Address Compare User/Supervisor bits to be User-only * (0b11 MSR[PR]=1) and set all other bits in DBCR2 register to be 0. */ thread->debug.dbcr2 = DBCR2_DAC1US | DBCR2_DAC2US; #else thread->debug.dbcr1 = 0; #endif } static void prime_debug_regs(struct debug_reg *debug) { /* * We could have inherited MSR_DE from userspace, since * it doesn't get cleared on exception entry. Make sure * MSR_DE is clear before we enable any debug events. */ mtmsr(mfmsr() & ~MSR_DE); mtspr(SPRN_IAC1, debug->iac1); mtspr(SPRN_IAC2, debug->iac2); #if CONFIG_PPC_ADV_DEBUG_IACS > 2 mtspr(SPRN_IAC3, debug->iac3); mtspr(SPRN_IAC4, debug->iac4); #endif mtspr(SPRN_DAC1, debug->dac1); mtspr(SPRN_DAC2, debug->dac2); #if CONFIG_PPC_ADV_DEBUG_DVCS > 0 mtspr(SPRN_DVC1, debug->dvc1); mtspr(SPRN_DVC2, debug->dvc2); #endif mtspr(SPRN_DBCR0, debug->dbcr0); mtspr(SPRN_DBCR1, debug->dbcr1); #ifdef CONFIG_BOOKE mtspr(SPRN_DBCR2, debug->dbcr2); #endif } /* * Unless neither the old or new thread are making use of the * debug registers, set the debug registers from the values * stored in the new thread. */ void switch_booke_debug_regs(struct debug_reg *new_debug) { if ((current->thread.debug.dbcr0 & DBCR0_IDM) || (new_debug->dbcr0 & DBCR0_IDM)) prime_debug_regs(new_debug); } EXPORT_SYMBOL_GPL(switch_booke_debug_regs); #else /* !CONFIG_PPC_ADV_DEBUG_REGS */ #ifndef CONFIG_HAVE_HW_BREAKPOINT static void set_debug_reg_defaults(struct thread_struct *thread) { thread->hw_brk.address = 0; thread->hw_brk.type = 0; set_breakpoint(&thread->hw_brk); } #endif /* !CONFIG_HAVE_HW_BREAKPOINT */ #endif /* CONFIG_PPC_ADV_DEBUG_REGS */ #ifdef CONFIG_PPC_ADV_DEBUG_REGS static inline int __set_dabr(unsigned long dabr, unsigned long dabrx) { mtspr(SPRN_DAC1, dabr); #ifdef CONFIG_PPC_47x isync(); #endif return 0; } #elif defined(CONFIG_PPC_BOOK3S) static inline int __set_dabr(unsigned long dabr, unsigned long dabrx) { mtspr(SPRN_DABR, dabr); if (cpu_has_feature(CPU_FTR_DABRX)) mtspr(SPRN_DABRX, dabrx); return 0; } #else static inline int __set_dabr(unsigned long dabr, unsigned long dabrx) { return -EINVAL; } #endif static inline int set_dabr(struct arch_hw_breakpoint *brk) { unsigned long dabr, dabrx; dabr = brk->address | (brk->type & HW_BRK_TYPE_DABR); dabrx = ((brk->type >> 3) & 0x7); if (ppc_md.set_dabr) return ppc_md.set_dabr(dabr, dabrx); return __set_dabr(dabr, dabrx); } static inline int set_dawr(struct arch_hw_breakpoint *brk) { unsigned long dawr, dawrx, mrd; dawr = brk->address; dawrx = (brk->type & (HW_BRK_TYPE_READ | HW_BRK_TYPE_WRITE)) \ << (63 - 58); //* read/write bits */ dawrx |= ((brk->type & (HW_BRK_TYPE_TRANSLATE)) >> 2) \ << (63 - 59); //* translate */ dawrx |= (brk->type & (HW_BRK_TYPE_PRIV_ALL)) \ >> 3; //* PRIM bits */ /* dawr length is stored in field MDR bits 48:53. Matches range in doublewords (64 bits) baised by -1 eg. 0b000000=1DW and 0b111111=64DW. brk->len is in bytes. This aligns up to double word size, shifts and does the bias. */ mrd = ((brk->len + 7) >> 3) - 1; dawrx |= (mrd & 0x3f) << (63 - 53); if (ppc_md.set_dawr) return ppc_md.set_dawr(dawr, dawrx); mtspr(SPRN_DAWR, dawr); mtspr(SPRN_DAWRX, dawrx); return 0; } int set_breakpoint(struct arch_hw_breakpoint *brk) { __get_cpu_var(current_brk) = *brk; if (cpu_has_feature(CPU_FTR_DAWR)) return set_dawr(brk); return set_dabr(brk); } #ifdef CONFIG_PPC64 DEFINE_PER_CPU(struct cpu_usage, cpu_usage_array); #endif static inline bool hw_brk_match(struct arch_hw_breakpoint *a, struct arch_hw_breakpoint *b) { if (a->address != b->address) return false; if (a->type != b->type) return false; if (a->len != b->len) return false; return true; } #ifdef CONFIG_PPC_TRANSACTIONAL_MEM static void tm_reclaim_thread(struct thread_struct *thr, struct thread_info *ti, uint8_t cause) { unsigned long msr_diff = 0; /* * If FP/VSX registers have been already saved to the * thread_struct, move them to the transact_fp array. * We clear the TIF_RESTORE_TM bit since after the reclaim * the thread will no longer be transactional. */ if (test_ti_thread_flag(ti, TIF_RESTORE_TM)) { msr_diff = thr->tm_orig_msr & ~thr->regs->msr; if (msr_diff & MSR_FP) memcpy(&thr->transact_fp, &thr->fp_state, sizeof(struct thread_fp_state)); if (msr_diff & MSR_VEC) memcpy(&thr->transact_vr, &thr->vr_state, sizeof(struct thread_vr_state)); clear_ti_thread_flag(ti, TIF_RESTORE_TM); msr_diff &= MSR_FP | MSR_VEC | MSR_VSX | MSR_FE0 | MSR_FE1; } tm_reclaim(thr, thr->regs->msr, cause); /* Having done the reclaim, we now have the checkpointed * FP/VSX values in the registers. These might be valid * even if we have previously called enable_kernel_fp() or * flush_fp_to_thread(), so update thr->regs->msr to * indicate their current validity. */ thr->regs->msr |= msr_diff; } void tm_reclaim_current(uint8_t cause) { tm_enable(); tm_reclaim_thread(&current->thread, current_thread_info(), cause); } static inline void tm_reclaim_task(struct task_struct *tsk) { /* We have to work out if we're switching from/to a task that's in the * middle of a transaction. * * In switching we need to maintain a 2nd register state as * oldtask->thread.ckpt_regs. We tm_reclaim(oldproc); this saves the * checkpointed (tbegin) state in ckpt_regs and saves the transactional * (current) FPRs into oldtask->thread.transact_fpr[]. * * We also context switch (save) TFHAR/TEXASR/TFIAR in here. */ struct thread_struct *thr = &tsk->thread; if (!thr->regs) return; if (!MSR_TM_ACTIVE(thr->regs->msr)) goto out_and_saveregs; /* Stash the original thread MSR, as giveup_fpu et al will * modify it. We hold onto it to see whether the task used * FP & vector regs. If the TIF_RESTORE_TM flag is set, * tm_orig_msr is already set. */ if (!test_ti_thread_flag(task_thread_info(tsk), TIF_RESTORE_TM)) thr->tm_orig_msr = thr->regs->msr; TM_DEBUG("--- tm_reclaim on pid %d (NIP=%lx, " "ccr=%lx, msr=%lx, trap=%lx)\n", tsk->pid, thr->regs->nip, thr->regs->ccr, thr->regs->msr, thr->regs->trap); tm_reclaim_thread(thr, task_thread_info(tsk), TM_CAUSE_RESCHED); TM_DEBUG("--- tm_reclaim on pid %d complete\n", tsk->pid); out_and_saveregs: /* Always save the regs here, even if a transaction's not active. * This context-switches a thread's TM info SPRs. We do it here to * be consistent with the restore path (in recheckpoint) which * cannot happen later in _switch(). */ tm_save_sprs(thr); } static inline void tm_recheckpoint_new_task(struct task_struct *new) { unsigned long msr; if (!cpu_has_feature(CPU_FTR_TM)) return; /* Recheckpoint the registers of the thread we're about to switch to. * * If the task was using FP, we non-lazily reload both the original and * the speculative FP register states. This is because the kernel * doesn't see if/when a TM rollback occurs, so if we take an FP * unavoidable later, we are unable to determine which set of FP regs * need to be restored. */ if (!new->thread.regs) return; /* The TM SPRs are restored here, so that TEXASR.FS can be set * before the trecheckpoint and no explosion occurs. */ tm_restore_sprs(&new->thread); if (!MSR_TM_ACTIVE(new->thread.regs->msr)) return; msr = new->thread.tm_orig_msr; /* Recheckpoint to restore original checkpointed register state. */ TM_DEBUG("*** tm_recheckpoint of pid %d " "(new->msr 0x%lx, new->origmsr 0x%lx)\n", new->pid, new->thread.regs->msr, msr); /* This loads the checkpointed FP/VEC state, if used */ tm_recheckpoint(&new->thread, msr); /* This loads the speculative FP/VEC state, if used */ if (msr & MSR_FP) { do_load_up_transact_fpu(&new->thread); new->thread.regs->msr |= (MSR_FP | new->thread.fpexc_mode); } #ifdef CONFIG_ALTIVEC if (msr & MSR_VEC) { do_load_up_transact_altivec(&new->thread); new->thread.regs->msr |= MSR_VEC; } #endif /* We may as well turn on VSX too since all the state is restored now */ if (msr & MSR_VSX) new->thread.regs->msr |= MSR_VSX; TM_DEBUG("*** tm_recheckpoint of pid %d complete " "(kernel msr 0x%lx)\n", new->pid, mfmsr()); } static inline void __switch_to_tm(struct task_struct *prev) { if (cpu_has_feature(CPU_FTR_TM)) { tm_enable(); tm_reclaim_task(prev); } } /* * This is called if we are on the way out to userspace and the * TIF_RESTORE_TM flag is set. It checks if we need to reload * FP and/or vector state and does so if necessary. * If userspace is inside a transaction (whether active or * suspended) and FP/VMX/VSX instructions have ever been enabled * inside that transaction, then we have to keep them enabled * and keep the FP/VMX/VSX state loaded while ever the transaction * continues. The reason is that if we didn't, and subsequently * got a FP/VMX/VSX unavailable interrupt inside a transaction, * we don't know whether it's the same transaction, and thus we * don't know which of the checkpointed state and the transactional * state to use. */ void restore_tm_state(struct pt_regs *regs) { unsigned long msr_diff; clear_thread_flag(TIF_RESTORE_TM); if (!MSR_TM_ACTIVE(regs->msr)) return; msr_diff = current->thread.tm_orig_msr & ~regs->msr; msr_diff &= MSR_FP | MSR_VEC | MSR_VSX; if (msr_diff & MSR_FP) { fp_enable(); load_fp_state(&current->thread.fp_state); regs->msr |= current->thread.fpexc_mode; } if (msr_diff & MSR_VEC) { vec_enable(); load_vr_state(&current->thread.vr_state); } regs->msr |= msr_diff; } #else #define tm_recheckpoint_new_task(new) #define __switch_to_tm(prev) #endif /* CONFIG_PPC_TRANSACTIONAL_MEM */ struct task_struct *__switch_to(struct task_struct *prev, struct task_struct *new) { struct thread_struct *new_thread, *old_thread; struct task_struct *last; #ifdef CONFIG_PPC_BOOK3S_64 struct ppc64_tlb_batch *batch; #endif WARN_ON(!irqs_disabled()); /* Back up the TAR across context switches. * Note that the TAR is not available for use in the kernel. (To * provide this, the TAR should be backed up/restored on exception * entry/exit instead, and be in pt_regs. FIXME, this should be in * pt_regs anyway (for debug).) * Save the TAR here before we do treclaim/trecheckpoint as these * will change the TAR. */ save_tar(&prev->thread); __switch_to_tm(prev); #ifdef CONFIG_SMP /* avoid complexity of lazy save/restore of fpu * by just saving it every time we switch out if * this task used the fpu during the last quantum. * * If it tries to use the fpu again, it'll trap and * reload its fp regs. So we don't have to do a restore * every switch, just a save. * -- Cort */ if (prev->thread.regs && (prev->thread.regs->msr & MSR_FP)) giveup_fpu(prev); #ifdef CONFIG_ALTIVEC /* * If the previous thread used altivec in the last quantum * (thus changing altivec regs) then save them. * We used to check the VRSAVE register but not all apps * set it, so we don't rely on it now (and in fact we need * to save & restore VSCR even if VRSAVE == 0). -- paulus * * On SMP we always save/restore altivec regs just to avoid the * complexity of changing processors. * -- Cort */ if (prev->thread.regs && (prev->thread.regs->msr & MSR_VEC)) giveup_altivec(prev); #endif /* CONFIG_ALTIVEC */ #ifdef CONFIG_VSX if (prev->thread.regs && (prev->thread.regs->msr & MSR_VSX)) /* VMX and FPU registers are already save here */ __giveup_vsx(prev); #endif /* CONFIG_VSX */ #ifdef CONFIG_SPE /* * If the previous thread used spe in the last quantum * (thus changing spe regs) then save them. * * On SMP we always save/restore spe regs just to avoid the * complexity of changing processors. */ if ((prev->thread.regs && (prev->thread.regs->msr & MSR_SPE))) giveup_spe(prev); #endif /* CONFIG_SPE */ #else /* CONFIG_SMP */ #ifdef CONFIG_ALTIVEC /* Avoid the trap. On smp this this never happens since * we don't set last_task_used_altivec -- Cort */ if (new->thread.regs && last_task_used_altivec == new) new->thread.regs->msr |= MSR_VEC; #endif /* CONFIG_ALTIVEC */ #ifdef CONFIG_VSX if (new->thread.regs && last_task_used_vsx == new) new->thread.regs->msr |= MSR_VSX; #endif /* CONFIG_VSX */ #ifdef CONFIG_SPE /* Avoid the trap. On smp this this never happens since * we don't set last_task_used_spe */ if (new->thread.regs && last_task_used_spe == new) new->thread.regs->msr |= MSR_SPE; #endif /* CONFIG_SPE */ #endif /* CONFIG_SMP */ #ifdef CONFIG_PPC_ADV_DEBUG_REGS switch_booke_debug_regs(&new->thread.debug); #else /* * For PPC_BOOK3S_64, we use the hw-breakpoint interfaces that would * schedule DABR */ #ifndef CONFIG_HAVE_HW_BREAKPOINT if (unlikely(!hw_brk_match(&__get_cpu_var(current_brk), &new->thread.hw_brk))) set_breakpoint(&new->thread.hw_brk); #endif /* CONFIG_HAVE_HW_BREAKPOINT */ #endif new_thread = &new->thread; old_thread = &current->thread; #ifdef CONFIG_PPC64 /* * Collect processor utilization data per process */ if (firmware_has_feature(FW_FEATURE_SPLPAR)) { struct cpu_usage *cu = &__get_cpu_var(cpu_usage_array); long unsigned start_tb, current_tb; start_tb = old_thread->start_tb; cu->current_tb = current_tb = mfspr(SPRN_PURR); old_thread->accum_tb += (current_tb - start_tb); new_thread->start_tb = current_tb; } #endif /* CONFIG_PPC64 */ #ifdef CONFIG_PPC_BOOK3S_64 batch = &__get_cpu_var(ppc64_tlb_batch); if (batch->active) { current_thread_info()->local_flags |= _TLF_LAZY_MMU; if (batch->index) __flush_tlb_pending(batch); batch->active = 0; } #endif /* CONFIG_PPC_BOOK3S_64 */ /* * We can't take a PMU exception inside _switch() since there is a * window where the kernel stack SLB and the kernel stack are out * of sync. Hard disable here. */ hard_irq_disable(); tm_recheckpoint_new_task(new); last = _switch(old_thread, new_thread); #ifdef CONFIG_PPC_BOOK3S_64 if (current_thread_info()->local_flags & _TLF_LAZY_MMU) { current_thread_info()->local_flags &= ~_TLF_LAZY_MMU; batch = &__get_cpu_var(ppc64_tlb_batch); batch->active = 1; } #endif /* CONFIG_PPC_BOOK3S_64 */ return last; } static int instructions_to_print = 16; static void show_instructions(struct pt_regs *regs) { int i; unsigned long pc = regs->nip - (instructions_to_print * 3 / 4 * sizeof(int)); printk("Instruction dump:"); for (i = 0; i < instructions_to_print; i++) { int instr; if (!(i % 8)) printk("\n"); #if !defined(CONFIG_BOOKE) /* If executing with the IMMU off, adjust pc rather * than print XXXXXXXX. */ if (!(regs->msr & MSR_IR)) pc = (unsigned long)phys_to_virt(pc); #endif /* We use __get_user here *only* to avoid an OOPS on a * bad address because the pc *should* only be a * kernel address. */ if (!__kernel_text_address(pc) || __get_user(instr, (unsigned int __user *)pc)) { printk(KERN_CONT "XXXXXXXX "); } else { if (regs->nip == pc) printk(KERN_CONT "<%08x> ", instr); else printk(KERN_CONT "%08x ", instr); } pc += sizeof(int); } printk("\n"); } static struct regbit { unsigned long bit; const char *name; } msr_bits[] = { #if defined(CONFIG_PPC64) && !defined(CONFIG_BOOKE) {MSR_SF, "SF"}, {MSR_HV, "HV"}, #endif {MSR_VEC, "VEC"}, {MSR_VSX, "VSX"}, #ifdef CONFIG_BOOKE {MSR_CE, "CE"}, #endif {MSR_EE, "EE"}, {MSR_PR, "PR"}, {MSR_FP, "FP"}, {MSR_ME, "ME"}, #ifdef CONFIG_BOOKE {MSR_DE, "DE"}, #else {MSR_SE, "SE"}, {MSR_BE, "BE"}, #endif {MSR_IR, "IR"}, {MSR_DR, "DR"}, {MSR_PMM, "PMM"}, #ifndef CONFIG_BOOKE {MSR_RI, "RI"}, {MSR_LE, "LE"}, #endif {0, NULL} }; static void printbits(unsigned long val, struct regbit *bits) { const char *sep = ""; printk("<"); for (; bits->bit; ++bits) if (val & bits->bit) { printk("%s%s", sep, bits->name); sep = ","; } printk(">"); } #ifdef CONFIG_PPC64 #define REG "%016lx" #define REGS_PER_LINE 4 #define LAST_VOLATILE 13 #else #define REG "%08lx" #define REGS_PER_LINE 8 #define LAST_VOLATILE 12 #endif void show_regs(struct pt_regs * regs) { int i, trap; show_regs_print_info(KERN_DEFAULT); printk("NIP: "REG" LR: "REG" CTR: "REG"\n", regs->nip, regs->link, regs->ctr); printk("REGS: %p TRAP: %04lx %s (%s)\n", regs, regs->trap, print_tainted(), init_utsname()->release); printk("MSR: "REG" ", regs->msr); printbits(regs->msr, msr_bits); printk(" CR: %08lx XER: %08lx\n", regs->ccr, regs->xer); trap = TRAP(regs); if ((regs->trap != 0xc00) && cpu_has_feature(CPU_FTR_CFAR)) printk("CFAR: "REG" ", regs->orig_gpr3); if (trap == 0x200 || trap == 0x300 || trap == 0x600) #if defined(CONFIG_4xx) || defined(CONFIG_BOOKE) printk("DEAR: "REG" ESR: "REG" ", regs->dar, regs->dsisr); #else printk("DAR: "REG" DSISR: %08lx ", regs->dar, regs->dsisr); #endif #ifdef CONFIG_PPC64 printk("SOFTE: %ld ", regs->softe); #endif #ifdef CONFIG_PPC_TRANSACTIONAL_MEM if (MSR_TM_ACTIVE(regs->msr)) printk("\nPACATMSCRATCH: %016llx ", get_paca()->tm_scratch); #endif for (i = 0; i < 32; i++) { if ((i % REGS_PER_LINE) == 0) printk("\nGPR%02d: ", i); printk(REG " ", regs->gpr[i]); if (i == LAST_VOLATILE && !FULL_REGS(regs)) break; } printk("\n"); #ifdef CONFIG_KALLSYMS /* * Lookup NIP late so we have the best change of getting the * above info out without failing */ printk("NIP ["REG"] %pS\n", regs->nip, (void *)regs->nip); printk("LR ["REG"] %pS\n", regs->link, (void *)regs->link); #endif show_stack(current, (unsigned long *) regs->gpr[1]); if (!user_mode(regs)) show_instructions(regs); } void exit_thread(void) { discard_lazy_cpu_state(); } void flush_thread(void) { discard_lazy_cpu_state(); #ifdef CONFIG_HAVE_HW_BREAKPOINT flush_ptrace_hw_breakpoint(current); #else /* CONFIG_HAVE_HW_BREAKPOINT */ set_debug_reg_defaults(&current->thread); #endif /* CONFIG_HAVE_HW_BREAKPOINT */ } void release_thread(struct task_struct *t) { } /* * this gets called so that we can store coprocessor state into memory and * copy the current task into the new thread. */ int arch_dup_task_struct(struct task_struct *dst, struct task_struct *src) { flush_fp_to_thread(src); flush_altivec_to_thread(src); flush_vsx_to_thread(src); flush_spe_to_thread(src); *dst = *src; clear_task_ebb(dst); return 0; } /* * Copy a thread.. */ extern unsigned long dscr_default; /* defined in arch/powerpc/kernel/sysfs.c */ int copy_thread(unsigned long clone_flags, unsigned long usp, unsigned long arg, struct task_struct *p) { struct pt_regs *childregs, *kregs; extern void ret_from_fork(void); extern void ret_from_kernel_thread(void); void (*f)(void); unsigned long sp = (unsigned long)task_stack_page(p) + THREAD_SIZE; /* Copy registers */ sp -= sizeof(struct pt_regs); childregs = (struct pt_regs *) sp; if (unlikely(p->flags & PF_KTHREAD)) { struct thread_info *ti = (void *)task_stack_page(p); memset(childregs, 0, sizeof(struct pt_regs)); childregs->gpr[1] = sp + sizeof(struct pt_regs); childregs->gpr[14] = usp; /* function */ #ifdef CONFIG_PPC64 clear_tsk_thread_flag(p, TIF_32BIT); childregs->softe = 1; #endif childregs->gpr[15] = arg; p->thread.regs = NULL; /* no user register state */ ti->flags |= _TIF_RESTOREALL; f = ret_from_kernel_thread; } else { struct pt_regs *regs = current_pt_regs(); CHECK_FULL_REGS(regs); *childregs = *regs; if (usp) childregs->gpr[1] = usp; p->thread.regs = childregs; childregs->gpr[3] = 0; /* Result from fork() */ if (clone_flags & CLONE_SETTLS) { #ifdef CONFIG_PPC64 if (!is_32bit_task()) childregs->gpr[13] = childregs->gpr[6]; else #endif childregs->gpr[2] = childregs->gpr[6]; } f = ret_from_fork; } sp -= STACK_FRAME_OVERHEAD; /* * The way this works is that at some point in the future * some task will call _switch to switch to the new task. * That will pop off the stack frame created below and start * the new task running at ret_from_fork. The new task will * do some house keeping and then return from the fork or clone * system call, using the stack frame created above. */ ((unsigned long *)sp)[0] = 0; sp -= sizeof(struct pt_regs); kregs = (struct pt_regs *) sp; sp -= STACK_FRAME_OVERHEAD; p->thread.ksp = sp; #ifdef CONFIG_PPC32 p->thread.ksp_limit = (unsigned long)task_stack_page(p) + _ALIGN_UP(sizeof(struct thread_info), 16); #endif #ifdef CONFIG_HAVE_HW_BREAKPOINT p->thread.ptrace_bps[0] = NULL; #endif p->thread.fp_save_area = NULL; #ifdef CONFIG_ALTIVEC p->thread.vr_save_area = NULL; #endif #ifdef CONFIG_PPC_STD_MMU_64 if (mmu_has_feature(MMU_FTR_SLB)) { unsigned long sp_vsid; unsigned long llp = mmu_psize_defs[mmu_linear_psize].sllp; if (mmu_has_feature(MMU_FTR_1T_SEGMENT)) sp_vsid = get_kernel_vsid(sp, MMU_SEGSIZE_1T) << SLB_VSID_SHIFT_1T; else sp_vsid = get_kernel_vsid(sp, MMU_SEGSIZE_256M) << SLB_VSID_SHIFT; sp_vsid |= SLB_VSID_KERNEL | llp; p->thread.ksp_vsid = sp_vsid; } #endif /* CONFIG_PPC_STD_MMU_64 */ #ifdef CONFIG_PPC64 if (cpu_has_feature(CPU_FTR_DSCR)) { p->thread.dscr_inherit = current->thread.dscr_inherit; p->thread.dscr = current->thread.dscr; } if (cpu_has_feature(CPU_FTR_HAS_PPR)) p->thread.ppr = INIT_PPR; #endif /* * The PPC64 ABI makes use of a TOC to contain function * pointers. The function (ret_from_except) is actually a pointer * to the TOC entry. The first entry is a pointer to the actual * function. */ #ifdef CONFIG_PPC64 kregs->nip = *((unsigned long *)f); #else kregs->nip = (unsigned long)f; #endif return 0; } /* * Set up a thread for executing a new program */ void start_thread(struct pt_regs *regs, unsigned long start, unsigned long sp) { #ifdef CONFIG_PPC64 unsigned long load_addr = regs->gpr[2]; /* saved by ELF_PLAT_INIT */ #endif /* * If we exec out of a kernel thread then thread.regs will not be * set. Do it now. */ if (!current->thread.regs) { struct pt_regs *regs = task_stack_page(current) + THREAD_SIZE; current->thread.regs = regs - 1; } memset(regs->gpr, 0, sizeof(regs->gpr)); regs->ctr = 0; regs->link = 0; regs->xer = 0; regs->ccr = 0; regs->gpr[1] = sp; /* * We have just cleared all the nonvolatile GPRs, so make * FULL_REGS(regs) return true. This is necessary to allow * ptrace to examine the thread immediately after exec. */ regs->trap &= ~1UL; #ifdef CONFIG_PPC32 regs->mq = 0; regs->nip = start; regs->msr = MSR_USER; #else if (!is_32bit_task()) { unsigned long entry; if (is_elf2_task()) { /* Look ma, no function descriptors! */ entry = start; /* * Ulrich says: * The latest iteration of the ABI requires that when * calling a function (at its global entry point), * the caller must ensure r12 holds the entry point * address (so that the function can quickly * establish addressability). */ regs->gpr[12] = start; /* Make sure that's restored on entry to userspace. */ set_thread_flag(TIF_RESTOREALL); } else { unsigned long toc; /* start is a relocated pointer to the function * descriptor for the elf _start routine. The first * entry in the function descriptor is the entry * address of _start and the second entry is the TOC * value we need to use. */ __get_user(entry, (unsigned long __user *)start); __get_user(toc, (unsigned long __user *)start+1); /* Check whether the e_entry function descriptor entries * need to be relocated before we can use them. */ if (load_addr != 0) { entry += load_addr; toc += load_addr; } regs->gpr[2] = toc; } regs->nip = entry; regs->msr = MSR_USER64; } else { regs->nip = start; regs->gpr[2] = 0; regs->msr = MSR_USER32; } #endif discard_lazy_cpu_state(); #ifdef CONFIG_VSX current->thread.used_vsr = 0; #endif memset(&current->thread.fp_state, 0, sizeof(current->thread.fp_state)); current->thread.fp_save_area = NULL; #ifdef CONFIG_ALTIVEC memset(&current->thread.vr_state, 0, sizeof(current->thread.vr_state)); current->thread.vr_state.vscr.u[3] = 0x00010000; /* Java mode disabled */ current->thread.vr_save_area = NULL; current->thread.vrsave = 0; current->thread.used_vr = 0; #endif /* CONFIG_ALTIVEC */ #ifdef CONFIG_SPE memset(current->thread.evr, 0, sizeof(current->thread.evr)); current->thread.acc = 0; current->thread.spefscr = 0; current->thread.used_spe = 0; #endif /* CONFIG_SPE */ #ifdef CONFIG_PPC_TRANSACTIONAL_MEM if (cpu_has_feature(CPU_FTR_TM)) regs->msr |= MSR_TM; current->thread.tm_tfhar = 0; current->thread.tm_texasr = 0; current->thread.tm_tfiar = 0; #endif /* CONFIG_PPC_TRANSACTIONAL_MEM */ } #define PR_FP_ALL_EXCEPT (PR_FP_EXC_DIV | PR_FP_EXC_OVF | PR_FP_EXC_UND \ | PR_FP_EXC_RES | PR_FP_EXC_INV) int set_fpexc_mode(struct task_struct *tsk, unsigned int val) { struct pt_regs *regs = tsk->thread.regs; /* This is a bit hairy. If we are an SPE enabled processor * (have embedded fp) we store the IEEE exception enable flags in * fpexc_mode. fpexc_mode is also used for setting FP exception * mode (asyn, precise, disabled) for 'Classic' FP. */ if (val & PR_FP_EXC_SW_ENABLE) { #ifdef CONFIG_SPE if (cpu_has_feature(CPU_FTR_SPE)) { /* * When the sticky exception bits are set * directly by userspace, it must call prctl * with PR_GET_FPEXC (with PR_FP_EXC_SW_ENABLE * in the existing prctl settings) or * PR_SET_FPEXC (with PR_FP_EXC_SW_ENABLE in * the bits being set). <fenv.h> functions * saving and restoring the whole * floating-point environment need to do so * anyway to restore the prctl settings from * the saved environment. */ tsk->thread.spefscr_last = mfspr(SPRN_SPEFSCR); tsk->thread.fpexc_mode = val & (PR_FP_EXC_SW_ENABLE | PR_FP_ALL_EXCEPT); return 0; } else { return -EINVAL; } #else return -EINVAL; #endif } /* on a CONFIG_SPE this does not hurt us. The bits that * __pack_fe01 use do not overlap with bits used for * PR_FP_EXC_SW_ENABLE. Additionally, the MSR[FE0,FE1] bits * on CONFIG_SPE implementations are reserved so writing to * them does not change anything */ if (val > PR_FP_EXC_PRECISE) return -EINVAL; tsk->thread.fpexc_mode = __pack_fe01(val); if (regs != NULL && (regs->msr & MSR_FP) != 0) regs->msr = (regs->msr & ~(MSR_FE0|MSR_FE1)) | tsk->thread.fpexc_mode; return 0; } int get_fpexc_mode(struct task_struct *tsk, unsigned long adr) { unsigned int val; if (tsk->thread.fpexc_mode & PR_FP_EXC_SW_ENABLE) #ifdef CONFIG_SPE if (cpu_has_feature(CPU_FTR_SPE)) { /* * When the sticky exception bits are set * directly by userspace, it must call prctl * with PR_GET_FPEXC (with PR_FP_EXC_SW_ENABLE * in the existing prctl settings) or * PR_SET_FPEXC (with PR_FP_EXC_SW_ENABLE in * the bits being set). <fenv.h> functions * saving and restoring the whole * floating-point environment need to do so * anyway to restore the prctl settings from * the saved environment. */ tsk->thread.spefscr_last = mfspr(SPRN_SPEFSCR); val = tsk->thread.fpexc_mode; } else return -EINVAL; #else return -EINVAL; #endif else val = __unpack_fe01(tsk->thread.fpexc_mode); return put_user(val, (unsigned int __user *) adr); } int set_endian(struct task_struct *tsk, unsigned int val) { struct pt_regs *regs = tsk->thread.regs; if ((val == PR_ENDIAN_LITTLE && !cpu_has_feature(CPU_FTR_REAL_LE)) || (val == PR_ENDIAN_PPC_LITTLE && !cpu_has_feature(CPU_FTR_PPC_LE))) return -EINVAL; if (regs == NULL) return -EINVAL; if (val == PR_ENDIAN_BIG) regs->msr &= ~MSR_LE; else if (val == PR_ENDIAN_LITTLE || val == PR_ENDIAN_PPC_LITTLE) regs->msr |= MSR_LE; else return -EINVAL; return 0; } int get_endian(struct task_struct *tsk, unsigned long adr) { struct pt_regs *regs = tsk->thread.regs; unsigned int val; if (!cpu_has_feature(CPU_FTR_PPC_LE) && !cpu_has_feature(CPU_FTR_REAL_LE)) return -EINVAL; if (regs == NULL) return -EINVAL; if (regs->msr & MSR_LE) { if (cpu_has_feature(CPU_FTR_REAL_LE)) val = PR_ENDIAN_LITTLE; else val = PR_ENDIAN_PPC_LITTLE; } else val = PR_ENDIAN_BIG; return put_user(val, (unsigned int __user *)adr); } int set_unalign_ctl(struct task_struct *tsk, unsigned int val) { tsk->thread.align_ctl = val; return 0; } int get_unalign_ctl(struct task_struct *tsk, unsigned long adr) { return put_user(tsk->thread.align_ctl, (unsigned int __user *)adr); } static inline int valid_irq_stack(unsigned long sp, struct task_struct *p, unsigned long nbytes) { unsigned long stack_page; unsigned long cpu = task_cpu(p); /* * Avoid crashing if the stack has overflowed and corrupted * task_cpu(p), which is in the thread_info struct. */ if (cpu < NR_CPUS && cpu_possible(cpu)) { stack_page = (unsigned long) hardirq_ctx[cpu]; if (sp >= stack_page + sizeof(struct thread_struct) && sp <= stack_page + THREAD_SIZE - nbytes) return 1; stack_page = (unsigned long) softirq_ctx[cpu]; if (sp >= stack_page + sizeof(struct thread_struct) && sp <= stack_page + THREAD_SIZE - nbytes) return 1; } return 0; } int validate_sp(unsigned long sp, struct task_struct *p, unsigned long nbytes) { unsigned long stack_page = (unsigned long)task_stack_page(p); if (sp >= stack_page + sizeof(struct thread_struct) && sp <= stack_page + THREAD_SIZE - nbytes) return 1; return valid_irq_stack(sp, p, nbytes); } EXPORT_SYMBOL(validate_sp); unsigned long get_wchan(struct task_struct *p) { unsigned long ip, sp; int count = 0; if (!p || p == current || p->state == TASK_RUNNING) return 0; sp = p->thread.ksp; if (!validate_sp(sp, p, STACK_FRAME_OVERHEAD)) return 0; do { sp = *(unsigned long *)sp; if (!validate_sp(sp, p, STACK_FRAME_OVERHEAD)) return 0; if (count > 0) { ip = ((unsigned long *)sp)[STACK_FRAME_LR_SAVE]; if (!in_sched_functions(ip)) return ip; } } while (count++ < 16); return 0; } static int kstack_depth_to_print = CONFIG_PRINT_STACK_DEPTH; void show_stack(struct task_struct *tsk, unsigned long *stack) { unsigned long sp, ip, lr, newsp; int count = 0; int firstframe = 1; #ifdef CONFIG_FUNCTION_GRAPH_TRACER int curr_frame = current->curr_ret_stack; extern void return_to_handler(void); unsigned long rth = (unsigned long)return_to_handler; unsigned long mrth = -1; #ifdef CONFIG_PPC64 extern void mod_return_to_handler(void); rth = *(unsigned long *)rth; mrth = (unsigned long)mod_return_to_handler; mrth = *(unsigned long *)mrth; #endif #endif sp = (unsigned long) stack; if (tsk == NULL) tsk = current; if (sp == 0) { if (tsk == current) asm("mr %0,1" : "=r" (sp)); else sp = tsk->thread.ksp; } lr = 0; printk("Call Trace:\n"); do { if (!validate_sp(sp, tsk, STACK_FRAME_OVERHEAD)) return; stack = (unsigned long *) sp; newsp = stack[0]; ip = stack[STACK_FRAME_LR_SAVE]; if (!firstframe || ip != lr) { printk("["REG"] ["REG"] %pS", sp, ip, (void *)ip); #ifdef CONFIG_FUNCTION_GRAPH_TRACER if ((ip == rth || ip == mrth) && curr_frame >= 0) { printk(" (%pS)", (void *)current->ret_stack[curr_frame].ret); curr_frame--; } #endif if (firstframe) printk(" (unreliable)"); printk("\n"); } firstframe = 0; /* * See if this is an exception frame. * We look for the "regshere" marker in the current frame. */ if (validate_sp(sp, tsk, STACK_INT_FRAME_SIZE) && stack[STACK_FRAME_MARKER] == STACK_FRAME_REGS_MARKER) { struct pt_regs *regs = (struct pt_regs *) (sp + STACK_FRAME_OVERHEAD); lr = regs->link; printk("--- Exception: %lx at %pS\n LR = %pS\n", regs->trap, (void *)regs->nip, (void *)lr); firstframe = 1; } sp = newsp; } while (count++ < kstack_depth_to_print); } #ifdef CONFIG_PPC64 /* Called with hard IRQs off */ void notrace __ppc64_runlatch_on(void) { struct thread_info *ti = current_thread_info(); unsigned long ctrl; ctrl = mfspr(SPRN_CTRLF); ctrl |= CTRL_RUNLATCH; mtspr(SPRN_CTRLT, ctrl); ti->local_flags |= _TLF_RUNLATCH; } /* Called with hard IRQs off */ void notrace __ppc64_runlatch_off(void) { struct thread_info *ti = current_thread_info(); unsigned long ctrl; ti->local_flags &= ~_TLF_RUNLATCH; ctrl = mfspr(SPRN_CTRLF); ctrl &= ~CTRL_RUNLATCH; mtspr(SPRN_CTRLT, ctrl); } #endif /* CONFIG_PPC64 */ unsigned long arch_align_stack(unsigned long sp) { if (!(current->personality & ADDR_NO_RANDOMIZE) && randomize_va_space) sp -= get_random_int() & ~PAGE_MASK; return sp & ~0xf; } static inline unsigned long brk_rnd(void) { unsigned long rnd = 0; /* 8MB for 32bit, 1GB for 64bit */ if (is_32bit_task()) rnd = (long)(get_random_int() % (1<<(23-PAGE_SHIFT))); else rnd = (long)(get_random_int() % (1<<(30-PAGE_SHIFT))); return rnd << PAGE_SHIFT; } unsigned long arch_randomize_brk(struct mm_struct *mm) { unsigned long base = mm->brk; unsigned long ret; #ifdef CONFIG_PPC_STD_MMU_64 /* * If we are using 1TB segments and we are allowed to randomise * the heap, we can put it above 1TB so it is backed by a 1TB * segment. Otherwise the heap will be in the bottom 1TB * which always uses 256MB segments and this may result in a * performance penalty. */ if (!is_32bit_task() && (mmu_highuser_ssize == MMU_SEGSIZE_1T)) base = max_t(unsigned long, mm->brk, 1UL << SID_SHIFT_1T); #endif ret = PAGE_ALIGN(base + brk_rnd()); if (ret < mm->brk) return mm->brk; return ret; } unsigned long randomize_et_dyn(unsigned long base) { unsigned long ret = PAGE_ALIGN(base + brk_rnd()); if (ret < base) return base; return ret; }
./CrossVul/dataset_final_sorted/CWE-20/c/bad_2115_0
crossvul-cpp_data_good_2738_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % JJJ PPPP 222 % % J P P 2 2 % % J PPPP 22 % % J J P 2 % % JJ P 22222 % % % % % % Read/Write JPEG-2000 Image Format % % % % Cristy % % Nathan Brown % % June 2001 % % % % % % Copyright 1999-2017 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://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/artifact.h" #include "magick/attribute.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/cache.h" #include "magick/colorspace.h" #include "magick/colorspace-private.h" #include "magick/color.h" #include "magick/color-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/option.h" #include "magick/pixel-accessor.h" #include "magick/profile.h" #include "magick/property.h" #include "magick/quantum-private.h" #include "magick/semaphore.h" #include "magick/static.h" #include "magick/statistic.h" #include "magick/string_.h" #include "magick/string-private.h" #include "magick/module.h" #if defined(MAGICKCORE_LIBOPENJP2_DELEGATE) #include <openjpeg.h> #endif /* Forward declarations. */ #if defined(MAGICKCORE_LIBOPENJP2_DELEGATE) static MagickBooleanType WriteJP2Image(const ImageInfo *,Image *); #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s J 2 K % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsJ2K() returns MagickTrue if the image format type, identified by the % magick string, is J2K. % % The format of the IsJ2K method is: % % MagickBooleanType IsJ2K(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 IsJ2K(const unsigned char *magick,const size_t length) { if (length < 4) return(MagickFalse); if (memcmp(magick,"\xff\x4f\xff\x51",4) == 0) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s J P 2 % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsJP2() returns MagickTrue if the image format type, identified by the % magick string, is JP2. % % The format of the IsJP2 method is: % % MagickBooleanType IsJP2(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 IsJP2(const unsigned char *magick,const size_t length) { if (length < 4) return(MagickFalse); if (memcmp(magick,"\x0d\x0a\x87\x0a",4) == 0) return(MagickTrue); if (length < 12) return(MagickFalse); if (memcmp(magick,"\x00\x00\x00\x0c\x6a\x50\x20\x20\x0d\x0a\x87\x0a",12) == 0) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d J P 2 I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadJP2Image() reads a JPEG 2000 Image file (JP2) or JPEG 2000 % codestream (JPC) image file and returns it. It allocates the memory % necessary for the new Image structure and returns a pointer to the new % image or set of images. % % JP2 support is originally written by Nathan Brown, nathanbrown@letu.edu. % % The format of the ReadJP2Image method is: % % Image *ReadJP2Image(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. % */ #if defined(MAGICKCORE_LIBOPENJP2_DELEGATE) static void JP2ErrorHandler(const char *message,void *client_data) { ExceptionInfo *exception; exception=(ExceptionInfo *) client_data; (void) ThrowMagickException(exception,GetMagickModule(),CoderError, message,"`%s'","OpenJP2"); } static OPJ_SIZE_T JP2ReadHandler(void *buffer,OPJ_SIZE_T length,void *context) { Image *image; ssize_t count; image=(Image *) context; count=ReadBlob(image,(ssize_t) length,(unsigned char *) buffer); if (count == 0) return((OPJ_SIZE_T) -1); return((OPJ_SIZE_T) count); } static OPJ_BOOL JP2SeekHandler(OPJ_OFF_T offset,void *context) { Image *image; image=(Image *) context; return(SeekBlob(image,offset,SEEK_SET) < 0 ? OPJ_FALSE : OPJ_TRUE); } static OPJ_OFF_T JP2SkipHandler(OPJ_OFF_T offset,void *context) { Image *image; image=(Image *) context; return(SeekBlob(image,offset,SEEK_CUR) < 0 ? -1 : offset); } static void JP2WarningHandler(const char *message,void *client_data) { ExceptionInfo *exception; exception=(ExceptionInfo *) client_data; (void) ThrowMagickException(exception,GetMagickModule(),CoderWarning, message,"`%s'","OpenJP2"); } static OPJ_SIZE_T JP2WriteHandler(void *buffer,OPJ_SIZE_T length,void *context) { Image *image; ssize_t count; image=(Image *) context; count=WriteBlob(image,(ssize_t) length,(unsigned char *) buffer); return((OPJ_SIZE_T) count); } static Image *ReadJP2Image(const ImageInfo *image_info,ExceptionInfo *exception) { const char *option; Image *image; int jp2_status; MagickBooleanType status; opj_codec_t *jp2_codec; opj_codestream_index_t *codestream_index = (opj_codestream_index_t *) NULL; opj_dparameters_t parameters; opj_image_t *jp2_image; opj_stream_t *jp2_stream; register ssize_t i; ssize_t y; unsigned char sans[4]; /* 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); } /* Initialize JP2 codec. */ if (ReadBlob(image,4,sans) != 4) { image=DestroyImageList(image); return((Image *) NULL); } (void) SeekBlob(image,SEEK_SET,0); if (LocaleCompare(image_info->magick,"JPT") == 0) jp2_codec=opj_create_decompress(OPJ_CODEC_JPT); else if (IsJ2K(sans,4) != MagickFalse) jp2_codec=opj_create_decompress(OPJ_CODEC_J2K); else jp2_codec=opj_create_decompress(OPJ_CODEC_JP2); opj_set_warning_handler(jp2_codec,JP2WarningHandler,exception); opj_set_error_handler(jp2_codec,JP2ErrorHandler,exception); opj_set_default_decoder_parameters(&parameters); option=GetImageOption(image_info,"jp2:reduce-factor"); if (option != (const char *) NULL) parameters.cp_reduce=StringToInteger(option); option=GetImageOption(image_info,"jp2:quality-layers"); if (option == (const char *) NULL) option=GetImageOption(image_info,"jp2:layer-number"); if (option != (const char *) NULL) parameters.cp_layer=StringToInteger(option); if (opj_setup_decoder(jp2_codec,&parameters) == 0) { opj_destroy_codec(jp2_codec); ThrowReaderException(DelegateError,"UnableToManageJP2Stream"); } jp2_stream=opj_stream_create(OPJ_J2K_STREAM_CHUNK_SIZE,OPJ_TRUE); opj_stream_set_read_function(jp2_stream,JP2ReadHandler); opj_stream_set_write_function(jp2_stream,JP2WriteHandler); opj_stream_set_seek_function(jp2_stream,JP2SeekHandler); opj_stream_set_skip_function(jp2_stream,JP2SkipHandler); opj_stream_set_user_data(jp2_stream,image,NULL); opj_stream_set_user_data_length(jp2_stream,GetBlobSize(image)); if (opj_read_header(jp2_stream,jp2_codec,&jp2_image) == 0) { opj_stream_destroy(jp2_stream); opj_destroy_codec(jp2_codec); ThrowReaderException(DelegateError,"UnableToDecodeImageFile"); } jp2_status=1; if ((image->columns != 0) && (image->rows != 0)) { /* Extract an area from the image. */ jp2_status=opj_set_decode_area(jp2_codec,jp2_image, (OPJ_INT32) image->extract_info.x,(OPJ_INT32) image->extract_info.y, (OPJ_INT32) image->extract_info.x+(ssize_t) image->columns, (OPJ_INT32) image->extract_info.y+(ssize_t) image->rows); if (jp2_status == 0) { opj_stream_destroy(jp2_stream); opj_destroy_codec(jp2_codec); opj_image_destroy(jp2_image); ThrowReaderException(DelegateError,"UnableToDecodeImageFile"); } } if ((image_info->number_scenes != 0) && (image_info->scene != 0)) jp2_status=opj_get_decoded_tile(jp2_codec,jp2_stream,jp2_image, (unsigned int) image_info->scene-1); else if (image->ping == MagickFalse) { jp2_status=opj_decode(jp2_codec,jp2_stream,jp2_image); if (jp2_status != 0) jp2_status=opj_end_decompress(jp2_codec,jp2_stream); } if (jp2_status == 0) { opj_stream_destroy(jp2_stream); opj_destroy_codec(jp2_codec); opj_image_destroy(jp2_image); ThrowReaderException(DelegateError,"UnableToDecodeImageFile"); } opj_stream_destroy(jp2_stream); for (i=0; i < (ssize_t) jp2_image->numcomps; i++) { if ((jp2_image->comps[0].dx == 0) || (jp2_image->comps[0].dy == 0) || (jp2_image->comps[0].dx != jp2_image->comps[i].dx) || (jp2_image->comps[0].dy != jp2_image->comps[i].dy) || (jp2_image->comps[0].prec != jp2_image->comps[i].prec) || (jp2_image->comps[0].sgnd != jp2_image->comps[i].sgnd) || (jp2_image->comps[i].data == NULL)) { opj_destroy_codec(jp2_codec); opj_image_destroy(jp2_image); ThrowReaderException(CoderError,"IrregularChannelGeometryNotSupported") } } /* Convert JP2 image. */ image->columns=(size_t) jp2_image->comps[0].w; image->rows=(size_t) jp2_image->comps[0].h; image->depth=jp2_image->comps[0].prec; status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } image->compression=JPEG2000Compression; if (jp2_image->color_space == 2) { SetImageColorspace(image,GRAYColorspace); if (jp2_image->numcomps > 1) image->matte=MagickTrue; } else if (jp2_image->color_space == 3) SetImageColorspace(image,Rec601YCbCrColorspace); if (jp2_image->numcomps > 3) image->matte=MagickTrue; if (jp2_image->icc_profile_buf != (unsigned char *) NULL) { StringInfo *profile; profile=BlobToStringInfo(jp2_image->icc_profile_buf, jp2_image->icc_profile_len); if (profile != (StringInfo *) NULL) SetImageProfile(image,"icc",profile); } if (image->ping != MagickFalse) { opj_destroy_codec(jp2_codec); opj_image_destroy(jp2_image); opj_destroy_cstr_index(&codestream_index); return(GetFirstImageInList(image)); } for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *magick_restrict q; register ssize_t x; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; for (i=0; i < (ssize_t) jp2_image->numcomps; i++) { double pixel, scale; scale=QuantumRange/(double) ((1UL << jp2_image->comps[i].prec)-1); pixel=scale*(jp2_image->comps[i].data[y/jp2_image->comps[i].dy* image->columns/jp2_image->comps[i].dx+x/jp2_image->comps[i].dx]+ (jp2_image->comps[i].sgnd ? 1UL << (jp2_image->comps[i].prec-1) : 0)); switch (i) { case 0: { q->red=ClampToQuantum(pixel); q->green=q->red; q->blue=q->red; q->opacity=OpaqueOpacity; break; } case 1: { if (jp2_image->numcomps == 2) { q->opacity=ClampToQuantum(QuantumRange-pixel); break; } q->green=ClampToQuantum(pixel); break; } case 2: { q->blue=ClampToQuantum(pixel); break; } case 3: { q->opacity=ClampToQuantum(QuantumRange-pixel); break; } } } q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } /* Free resources. */ opj_destroy_codec(jp2_codec); opj_image_destroy(jp2_image); opj_destroy_cstr_index(&codestream_index); (void) CloseBlob(image); return(GetFirstImageInList(image)); } #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r J P 2 I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterJP2Image() adds attributes for the JP2 image format to the list of % supported formats. The attributes include the image format tag, a method % 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 RegisterJP2Image method is: % % size_t RegisterJP2Image(void) % */ ModuleExport size_t RegisterJP2Image(void) { char version[MaxTextExtent]; MagickInfo *entry; *version='\0'; #if defined(MAGICKCORE_LIBOPENJP2_DELEGATE) (void) FormatLocaleString(version,MaxTextExtent,"%s",opj_version()); #endif entry=SetMagickInfo("JP2"); entry->description=ConstantString("JPEG-2000 File Format Syntax"); if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/jp2"); entry->module=ConstantString("JP2"); entry->magick=(IsImageFormatHandler *) IsJP2; entry->adjoin=MagickFalse; entry->seekable_stream=MagickTrue; #if defined(MAGICKCORE_LIBOPENJP2_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadJP2Image; entry->encoder=(EncodeImageHandler *) WriteJP2Image; #endif (void) RegisterMagickInfo(entry); entry=SetMagickInfo("J2C"); entry->description=ConstantString("JPEG-2000 Code Stream Syntax"); if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/jp2"); entry->module=ConstantString("JP2"); entry->magick=(IsImageFormatHandler *) IsJ2K; entry->adjoin=MagickFalse; entry->seekable_stream=MagickTrue; #if defined(MAGICKCORE_LIBOPENJP2_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadJP2Image; entry->encoder=(EncodeImageHandler *) WriteJP2Image; #endif (void) RegisterMagickInfo(entry); entry=SetMagickInfo("J2K"); entry->description=ConstantString("JPEG-2000 Code Stream Syntax"); if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/jp2"); entry->module=ConstantString("JP2"); entry->magick=(IsImageFormatHandler *) IsJ2K; entry->adjoin=MagickFalse; entry->seekable_stream=MagickTrue; #if defined(MAGICKCORE_LIBOPENJP2_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadJP2Image; entry->encoder=(EncodeImageHandler *) WriteJP2Image; #endif (void) RegisterMagickInfo(entry); entry=SetMagickInfo("JPM"); entry->description=ConstantString("JPEG-2000 Code Stream Syntax"); if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/jp2"); entry->module=ConstantString("JP2"); entry->magick=(IsImageFormatHandler *) IsJP2; entry->adjoin=MagickFalse; entry->seekable_stream=MagickTrue; #if defined(MAGICKCORE_LIBOPENJP2_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadJP2Image; entry->encoder=(EncodeImageHandler *) WriteJP2Image; #endif (void) RegisterMagickInfo(entry); entry=SetMagickInfo("JPT"); entry->description=ConstantString("JPEG-2000 File Format Syntax"); if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/jp2"); entry->module=ConstantString("JP2"); entry->magick=(IsImageFormatHandler *) IsJP2; entry->adjoin=MagickFalse; entry->seekable_stream=MagickTrue; #if defined(MAGICKCORE_LIBOPENJP2_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadJP2Image; entry->encoder=(EncodeImageHandler *) WriteJP2Image; #endif (void) RegisterMagickInfo(entry); entry=SetMagickInfo("JPC"); entry->description=ConstantString("JPEG-2000 Code Stream Syntax"); if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/jp2"); entry->module=ConstantString("JP2"); entry->magick=(IsImageFormatHandler *) IsJP2; entry->adjoin=MagickFalse; entry->seekable_stream=MagickTrue; #if defined(MAGICKCORE_LIBOPENJP2_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadJP2Image; entry->encoder=(EncodeImageHandler *) WriteJP2Image; #endif (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r J P 2 I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterJP2Image() removes format registrations made by the JP2 module % from the list of supported formats. % % The format of the UnregisterJP2Image method is: % % UnregisterJP2Image(void) % */ ModuleExport void UnregisterJP2Image(void) { (void) UnregisterMagickInfo("JPC"); (void) UnregisterMagickInfo("JPT"); (void) UnregisterMagickInfo("JPM"); (void) UnregisterMagickInfo("JP2"); (void) UnregisterMagickInfo("J2K"); } #if defined(MAGICKCORE_LIBOPENJP2_DELEGATE) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e J P 2 I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteJP2Image() writes an image in the JPEG 2000 image format. % % JP2 support originally written by Nathan Brown, nathanbrown@letu.edu % % The format of the WriteJP2Image method is: % % MagickBooleanType WriteJP2Image(const ImageInfo *image_info,Image *image) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % */ static void CinemaProfileCompliance(const opj_image_t *jp2_image, opj_cparameters_t *parameters) { /* Digital Cinema 4K profile compliant codestream. */ parameters->tile_size_on=OPJ_FALSE; parameters->cp_tdx=1; parameters->cp_tdy=1; parameters->tp_flag='C'; parameters->tp_on=1; parameters->cp_tx0=0; parameters->cp_ty0=0; parameters->image_offset_x0=0; parameters->image_offset_y0=0; parameters->cblockw_init=32; parameters->cblockh_init=32; parameters->csty|=0x01; parameters->prog_order=OPJ_CPRL; parameters->roi_compno=(-1); parameters->subsampling_dx=1; parameters->subsampling_dy=1; parameters->irreversible=1; if ((jp2_image->comps[0].w == 2048) || (jp2_image->comps[0].h == 1080)) { /* Digital Cinema 2K. */ parameters->cp_cinema=OPJ_CINEMA2K_24; parameters->cp_rsiz=OPJ_CINEMA2K; parameters->max_comp_size=1041666; if (parameters->numresolution > 6) parameters->numresolution=6; } if ((jp2_image->comps[0].w == 4096) || (jp2_image->comps[0].h == 2160)) { /* Digital Cinema 4K. */ parameters->cp_cinema=OPJ_CINEMA4K_24; parameters->cp_rsiz=OPJ_CINEMA4K; parameters->max_comp_size=1041666; if (parameters->numresolution < 1) parameters->numresolution=1; if (parameters->numresolution > 7) parameters->numresolution=7; parameters->numpocs=2; parameters->POC[0].tile=1; parameters->POC[0].resno0=0; parameters->POC[0].compno0=0; parameters->POC[0].layno1=1; parameters->POC[0].resno1=parameters->numresolution-1; parameters->POC[0].compno1=3; parameters->POC[0].prg1=OPJ_CPRL; parameters->POC[1].tile=1; parameters->POC[1].resno0=parameters->numresolution-1; parameters->POC[1].compno0=0; parameters->POC[1].layno1=1; parameters->POC[1].resno1=parameters->numresolution; parameters->POC[1].compno1=3; parameters->POC[1].prg1=OPJ_CPRL; } parameters->tcp_numlayers=1; parameters->tcp_rates[0]=((float) (jp2_image->numcomps*jp2_image->comps[0].w* jp2_image->comps[0].h*jp2_image->comps[0].prec))/(parameters->max_comp_size* 8*jp2_image->comps[0].dx*jp2_image->comps[0].dy); parameters->cp_disto_alloc=1; } static MagickBooleanType WriteJP2Image(const ImageInfo *image_info,Image *image) { const char *option, *property; int jp2_status; MagickBooleanType status; opj_codec_t *jp2_codec; OPJ_COLOR_SPACE jp2_colorspace; opj_cparameters_t parameters; opj_image_cmptparm_t jp2_info[5]; opj_image_t *jp2_image; opj_stream_t *jp2_stream; register ssize_t i; ssize_t y; unsigned int channels; /* Open 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); /* Initialize JPEG 2000 encoder parameters. */ opj_set_default_encoder_parameters(&parameters); for (i=1; i < 6; i++) if (((size_t) (1 << (i+2)) > image->columns) && ((size_t) (1 << (i+2)) > image->rows)) break; parameters.numresolution=i; option=GetImageOption(image_info,"jp2:number-resolutions"); if (option != (const char *) NULL) parameters.numresolution=StringToInteger(option); parameters.tcp_numlayers=1; parameters.tcp_rates[0]=0; /* lossless */ parameters.cp_disto_alloc=1; if ((image_info->quality != 0) && (image_info->quality != 100)) { parameters.tcp_distoratio[0]=(double) image_info->quality; parameters.cp_fixed_quality=OPJ_TRUE; } if (image_info->extract != (char *) NULL) { RectangleInfo geometry; int flags; /* Set tile size. */ flags=ParseAbsoluteGeometry(image_info->extract,&geometry); parameters.cp_tdx=(int) geometry.width; parameters.cp_tdy=(int) geometry.width; if ((flags & HeightValue) != 0) parameters.cp_tdy=(int) geometry.height; if ((flags & XValue) != 0) parameters.cp_tx0=geometry.x; if ((flags & YValue) != 0) parameters.cp_ty0=geometry.y; parameters.tile_size_on=OPJ_TRUE; } option=GetImageOption(image_info,"jp2:quality"); if (option != (const char *) NULL) { register const char *p; /* Set quality PSNR. */ p=option; for (i=0; sscanf(p,"%f",&parameters.tcp_distoratio[i]) == 1; i++) { if (i >= 100) break; while ((*p != '\0') && (*p != ',')) p++; if (*p == '\0') break; p++; } parameters.tcp_numlayers=i+1; parameters.cp_fixed_quality=OPJ_TRUE; } option=GetImageOption(image_info,"jp2:progression-order"); if (option != (const char *) NULL) { if (LocaleCompare(option,"LRCP") == 0) parameters.prog_order=OPJ_LRCP; if (LocaleCompare(option,"RLCP") == 0) parameters.prog_order=OPJ_RLCP; if (LocaleCompare(option,"RPCL") == 0) parameters.prog_order=OPJ_RPCL; if (LocaleCompare(option,"PCRL") == 0) parameters.prog_order=OPJ_PCRL; if (LocaleCompare(option,"CPRL") == 0) parameters.prog_order=OPJ_CPRL; } option=GetImageOption(image_info,"jp2:rate"); if (option != (const char *) NULL) { register const char *p; /* Set compression rate. */ p=option; for (i=0; sscanf(p,"%f",&parameters.tcp_rates[i]) == 1; i++) { if (i > 100) break; while ((*p != '\0') && (*p != ',')) p++; if (*p == '\0') break; p++; } parameters.tcp_numlayers=i+1; parameters.cp_disto_alloc=OPJ_TRUE; } if (image_info->sampling_factor != (const char *) NULL) (void) sscanf(image_info->sampling_factor,"%d,%d", &parameters.subsampling_dx,&parameters.subsampling_dy); property=GetImageProperty(image,"comment"); if (property != (const char *) NULL) parameters.cp_comment=ConstantString(property); channels=3; jp2_colorspace=OPJ_CLRSPC_SRGB; if (image->colorspace == YUVColorspace) { jp2_colorspace=OPJ_CLRSPC_SYCC; parameters.subsampling_dx=2; } else { if (IsGrayColorspace(image->colorspace) != MagickFalse) { channels=1; jp2_colorspace=OPJ_CLRSPC_GRAY; } else (void) TransformImageColorspace(image,sRGBColorspace); if (image->matte != MagickFalse) channels++; } parameters.tcp_mct=channels == 3 ? 1 : 0; ResetMagickMemory(jp2_info,0,sizeof(jp2_info)); for (i=0; i < (ssize_t) channels; i++) { jp2_info[i].prec=(unsigned int) image->depth; jp2_info[i].bpp=(unsigned int) image->depth; if ((image->depth == 1) && ((LocaleCompare(image_info->magick,"JPT") == 0) || (LocaleCompare(image_info->magick,"JP2") == 0))) { jp2_info[i].prec++; /* OpenJPEG returns exception for depth @ 1 */ jp2_info[i].bpp++; } jp2_info[i].sgnd=0; jp2_info[i].dx=parameters.subsampling_dx; jp2_info[i].dy=parameters.subsampling_dy; jp2_info[i].w=(unsigned int) image->columns; jp2_info[i].h=(unsigned int) image->rows; } jp2_image=opj_image_create(channels,jp2_info,jp2_colorspace); if (jp2_image == (opj_image_t *) NULL) ThrowWriterException(DelegateError,"UnableToEncodeImageFile"); jp2_image->x0=parameters.image_offset_x0; jp2_image->y0=parameters.image_offset_y0; jp2_image->x1=(unsigned int) (2*parameters.image_offset_x0+(image->columns-1)* parameters.subsampling_dx+1); jp2_image->y1=(unsigned int) (2*parameters.image_offset_y0+(image->rows-1)* parameters.subsampling_dx+1); if ((image->depth == 12) && ((image->columns == 2048) || (image->rows == 1080) || (image->columns == 4096) || (image->rows == 2160))) CinemaProfileCompliance(jp2_image,&parameters); if (channels == 4) jp2_image->comps[3].alpha=1; else if ((channels == 2) && (jp2_colorspace == OPJ_CLRSPC_GRAY)) jp2_image->comps[1].alpha=1; /* Convert to JP2 pixels. */ for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *p; ssize_t x; 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++) { for (i=0; i < (ssize_t) channels; i++) { double scale; register int *q; scale=(double) ((1UL << jp2_image->comps[i].prec)-1)/QuantumRange; q=jp2_image->comps[i].data+(y/jp2_image->comps[i].dy* image->columns/jp2_image->comps[i].dx+x/jp2_image->comps[i].dx); switch (i) { case 0: { if (jp2_colorspace == OPJ_CLRSPC_GRAY) { *q=(int) (scale*GetPixelLuma(image,p)); break; } *q=(int) (scale*p->red); break; } case 1: { if (jp2_colorspace == OPJ_CLRSPC_GRAY) { *q=(int) (scale*(QuantumRange-p->opacity)); break; } *q=(int) (scale*p->green); break; } case 2: { *q=(int) (scale*p->blue); break; } case 3: { *q=(int) (scale*(QuantumRange-p->opacity)); break; } } } p++; } status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } if (LocaleCompare(image_info->magick,"JPT") == 0) jp2_codec=opj_create_compress(OPJ_CODEC_JPT); else if (LocaleCompare(image_info->magick,"J2K") == 0) jp2_codec=opj_create_compress(OPJ_CODEC_J2K); else jp2_codec=opj_create_compress(OPJ_CODEC_JP2); opj_set_warning_handler(jp2_codec,JP2WarningHandler,&image->exception); opj_set_error_handler(jp2_codec,JP2ErrorHandler,&image->exception); opj_setup_encoder(jp2_codec,&parameters,jp2_image); jp2_stream=opj_stream_create(OPJ_J2K_STREAM_CHUNK_SIZE,OPJ_FALSE); opj_stream_set_read_function(jp2_stream,JP2ReadHandler); opj_stream_set_write_function(jp2_stream,JP2WriteHandler); opj_stream_set_seek_function(jp2_stream,JP2SeekHandler); opj_stream_set_skip_function(jp2_stream,JP2SkipHandler); opj_stream_set_user_data(jp2_stream,image,NULL); if (jp2_stream == (opj_stream_t *) NULL) ThrowWriterException(DelegateError,"UnableToEncodeImageFile"); jp2_status=opj_start_compress(jp2_codec,jp2_image,jp2_stream); if (jp2_status == 0) ThrowWriterException(DelegateError,"UnableToEncodeImageFile"); if ((opj_encode(jp2_codec,jp2_stream) == 0) || (opj_end_compress(jp2_codec,jp2_stream) == 0)) { opj_stream_destroy(jp2_stream); opj_destroy_codec(jp2_codec); opj_image_destroy(jp2_image); ThrowWriterException(DelegateError,"UnableToEncodeImageFile"); } /* Free resources. */ opj_stream_destroy(jp2_stream); opj_destroy_codec(jp2_codec); opj_image_destroy(jp2_image); (void) CloseBlob(image); return(MagickTrue); } #endif
./CrossVul/dataset_final_sorted/CWE-20/c/good_2738_0
crossvul-cpp_data_bad_5418_4
/* * Copyright (c) 2002-2003 Michael David Adams. * All rights reserved. */ /* __START_OF_JASPER_LICENSE__ * * JasPer License Version 2.0 * * Copyright (c) 2001-2006 Michael David Adams * Copyright (c) 1999-2000 Image Power, Inc. * Copyright (c) 1999-2000 The University of British Columbia * * All rights reserved. * * Permission is hereby granted, free of charge, to any person (the * "User") obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, * publish, distribute, and/or sell copies of the Software, and to permit * persons to whom the Software is furnished to do so, subject to the * following conditions: * * 1. The above copyright notices and this permission notice (which * includes the disclaimer below) shall be included in all copies or * substantial portions of the Software. * * 2. The name of a copyright holder shall not be used to endorse or * promote products derived from the Software without specific prior * written permission. * * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY. * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES, * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH, * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. * * __END_OF_JASPER_LICENSE__ */ #include <assert.h> #include "jasper/jas_config.h" #include "jasper/jas_types.h" #include "jasper/jas_malloc.h" #include "jasper/jas_debug.h" #include "jasper/jas_icc.h" #include "jasper/jas_cm.h" #include "jasper/jas_stream.h" #include "jasper/jas_string.h" #include <stdlib.h> #include <ctype.h> #include <inttypes.h> #define jas_iccputuint8(out, val) jas_iccputuint(out, 1, val) #define jas_iccputuint16(out, val) jas_iccputuint(out, 2, val) #define jas_iccputsint32(out, val) jas_iccputsint(out, 4, val) #define jas_iccputuint32(out, val) jas_iccputuint(out, 4, val) #define jas_iccputuint64(out, val) jas_iccputuint(out, 8, val) static jas_iccattrval_t *jas_iccattrval_create0(void); static int jas_iccgetuint(jas_stream_t *in, int n, ulonglong *val); static int jas_iccgetuint8(jas_stream_t *in, jas_iccuint8_t *val); static int jas_iccgetuint16(jas_stream_t *in, jas_iccuint16_t *val); static int jas_iccgetsint32(jas_stream_t *in, jas_iccsint32_t *val); static int jas_iccgetuint32(jas_stream_t *in, jas_iccuint32_t *val); static int jas_iccgetuint64(jas_stream_t *in, jas_iccuint64_t *val); static int jas_iccputuint(jas_stream_t *out, int n, ulonglong val); static int jas_iccputsint(jas_stream_t *out, int n, longlong val); static jas_iccprof_t *jas_iccprof_create(void); static int jas_iccprof_readhdr(jas_stream_t *in, jas_icchdr_t *hdr); static int jas_iccprof_writehdr(jas_stream_t *out, jas_icchdr_t *hdr); static int jas_iccprof_gettagtab(jas_stream_t *in, jas_icctagtab_t *tagtab); static void jas_iccprof_sorttagtab(jas_icctagtab_t *tagtab); static int jas_iccattrtab_lookup(jas_iccattrtab_t *attrtab, jas_iccuint32_t name); static jas_iccattrtab_t *jas_iccattrtab_copy(jas_iccattrtab_t *attrtab); static jas_iccattrvalinfo_t *jas_iccattrvalinfo_lookup(jas_iccsig_t name); static int jas_iccgettime(jas_stream_t *in, jas_icctime_t *time); static int jas_iccgetxyz(jas_stream_t *in, jas_iccxyz_t *xyz); static int jas_icctagtabent_cmp(const void *src, const void *dst); static void jas_icccurv_destroy(jas_iccattrval_t *attrval); static int jas_icccurv_copy(jas_iccattrval_t *attrval, jas_iccattrval_t *othattrval); static int jas_icccurv_input(jas_iccattrval_t *attrval, jas_stream_t *in, int cnt); static int jas_icccurv_getsize(jas_iccattrval_t *attrval); static int jas_icccurv_output(jas_iccattrval_t *attrval, jas_stream_t *out); static void jas_icccurv_dump(jas_iccattrval_t *attrval, FILE *out); static void jas_icctxtdesc_destroy(jas_iccattrval_t *attrval); static int jas_icctxtdesc_copy(jas_iccattrval_t *attrval, jas_iccattrval_t *othattrval); static int jas_icctxtdesc_input(jas_iccattrval_t *attrval, jas_stream_t *in, int cnt); static int jas_icctxtdesc_getsize(jas_iccattrval_t *attrval); static int jas_icctxtdesc_output(jas_iccattrval_t *attrval, jas_stream_t *out); static void jas_icctxtdesc_dump(jas_iccattrval_t *attrval, FILE *out); static void jas_icctxt_destroy(jas_iccattrval_t *attrval); static int jas_icctxt_copy(jas_iccattrval_t *attrval, jas_iccattrval_t *othattrval); static int jas_icctxt_input(jas_iccattrval_t *attrval, jas_stream_t *in, int cnt); static int jas_icctxt_getsize(jas_iccattrval_t *attrval); static int jas_icctxt_output(jas_iccattrval_t *attrval, jas_stream_t *out); static void jas_icctxt_dump(jas_iccattrval_t *attrval, FILE *out); static int jas_iccxyz_input(jas_iccattrval_t *attrval, jas_stream_t *in, int cnt); static int jas_iccxyz_getsize(jas_iccattrval_t *attrval); static int jas_iccxyz_output(jas_iccattrval_t *attrval, jas_stream_t *out); static void jas_iccxyz_dump(jas_iccattrval_t *attrval, FILE *out); static jas_iccattrtab_t *jas_iccattrtab_create(void); static void jas_iccattrtab_destroy(jas_iccattrtab_t *tab); static int jas_iccattrtab_resize(jas_iccattrtab_t *tab, int maxents); static int jas_iccattrtab_add(jas_iccattrtab_t *attrtab, int i, jas_iccuint32_t name, jas_iccattrval_t *val); static int jas_iccattrtab_replace(jas_iccattrtab_t *attrtab, int i, jas_iccuint32_t name, jas_iccattrval_t *val); static void jas_iccattrtab_delete(jas_iccattrtab_t *attrtab, int i); static long jas_iccpadtomult(long x, long y); static int jas_iccattrtab_get(jas_iccattrtab_t *attrtab, int i, jas_iccattrname_t *name, jas_iccattrval_t **val); static int jas_iccprof_puttagtab(jas_stream_t *out, jas_icctagtab_t *tagtab); static void jas_icclut16_destroy(jas_iccattrval_t *attrval); static int jas_icclut16_copy(jas_iccattrval_t *attrval, jas_iccattrval_t *othattrval); static int jas_icclut16_input(jas_iccattrval_t *attrval, jas_stream_t *in, int cnt); static int jas_icclut16_getsize(jas_iccattrval_t *attrval); static int jas_icclut16_output(jas_iccattrval_t *attrval, jas_stream_t *out); static void jas_icclut16_dump(jas_iccattrval_t *attrval, FILE *out); static void jas_icclut8_destroy(jas_iccattrval_t *attrval); static int jas_icclut8_copy(jas_iccattrval_t *attrval, jas_iccattrval_t *othattrval); static int jas_icclut8_input(jas_iccattrval_t *attrval, jas_stream_t *in, int cnt); static int jas_icclut8_getsize(jas_iccattrval_t *attrval); static int jas_icclut8_output(jas_iccattrval_t *attrval, jas_stream_t *out); static void jas_icclut8_dump(jas_iccattrval_t *attrval, FILE *out); static int jas_iccputtime(jas_stream_t *out, jas_icctime_t *ctime); static int jas_iccputxyz(jas_stream_t *out, jas_iccxyz_t *xyz); static long jas_iccpowi(int x, int n); static char *jas_iccsigtostr(int sig, char *buf); jas_iccattrvalinfo_t jas_iccattrvalinfos[] = { {JAS_ICC_TYPE_CURV, {jas_icccurv_destroy, jas_icccurv_copy, jas_icccurv_input, jas_icccurv_output, jas_icccurv_getsize, jas_icccurv_dump}}, {JAS_ICC_TYPE_XYZ, {0, 0, jas_iccxyz_input, jas_iccxyz_output, jas_iccxyz_getsize, jas_iccxyz_dump}}, {JAS_ICC_TYPE_TXTDESC, {jas_icctxtdesc_destroy, jas_icctxtdesc_copy, jas_icctxtdesc_input, jas_icctxtdesc_output, jas_icctxtdesc_getsize, jas_icctxtdesc_dump}}, {JAS_ICC_TYPE_TXT, {jas_icctxt_destroy, jas_icctxt_copy, jas_icctxt_input, jas_icctxt_output, jas_icctxt_getsize, jas_icctxt_dump}}, {JAS_ICC_TYPE_LUT8, {jas_icclut8_destroy, jas_icclut8_copy, jas_icclut8_input, jas_icclut8_output, jas_icclut8_getsize, jas_icclut8_dump}}, {JAS_ICC_TYPE_LUT16, {jas_icclut16_destroy, jas_icclut16_copy, jas_icclut16_input, jas_icclut16_output, jas_icclut16_getsize, jas_icclut16_dump}}, {0, {0, 0, 0, 0, 0, 0}} }; typedef struct { jas_iccuint32_t tag; char *name; } jas_icctaginfo_t; /******************************************************************************\ * profile class \******************************************************************************/ static jas_iccprof_t *jas_iccprof_create() { jas_iccprof_t *prof; prof = 0; if (!(prof = jas_malloc(sizeof(jas_iccprof_t)))) { goto error; } if (!(prof->attrtab = jas_iccattrtab_create())) goto error; memset(&prof->hdr, 0, sizeof(jas_icchdr_t)); prof->tagtab.numents = 0; prof->tagtab.ents = 0; return prof; error: if (prof) jas_iccprof_destroy(prof); return 0; } jas_iccprof_t *jas_iccprof_copy(jas_iccprof_t *prof) { jas_iccprof_t *newprof; newprof = 0; if (!(newprof = jas_iccprof_create())) goto error; newprof->hdr = prof->hdr; newprof->tagtab.numents = 0; newprof->tagtab.ents = 0; assert(newprof->attrtab); jas_iccattrtab_destroy(newprof->attrtab); if (!(newprof->attrtab = jas_iccattrtab_copy(prof->attrtab))) goto error; return newprof; error: if (newprof) jas_iccprof_destroy(newprof); return 0; } void jas_iccprof_destroy(jas_iccprof_t *prof) { if (prof->attrtab) jas_iccattrtab_destroy(prof->attrtab); if (prof->tagtab.ents) jas_free(prof->tagtab.ents); jas_free(prof); } void jas_iccprof_dump(jas_iccprof_t *prof, FILE *out) { jas_iccattrtab_dump(prof->attrtab, out); } jas_iccprof_t *jas_iccprof_load(jas_stream_t *in) { jas_iccprof_t *prof; int numtags; long curoff; long reloff; long prevoff; jas_iccsig_t type; jas_iccattrval_t *attrval; jas_iccattrval_t *prevattrval; jas_icctagtabent_t *tagtabent; int i; int len; prof = 0; attrval = 0; if (!(prof = jas_iccprof_create())) { goto error; } if (jas_iccprof_readhdr(in, &prof->hdr)) { jas_eprintf("cannot get header\n"); goto error; } if (jas_iccprof_gettagtab(in, &prof->tagtab)) { jas_eprintf("cannot get tab table\n"); goto error; } jas_iccprof_sorttagtab(&prof->tagtab); numtags = prof->tagtab.numents; curoff = JAS_ICC_HDRLEN + 4 + 12 * numtags; prevoff = 0; prevattrval = 0; for (i = 0; i < numtags; ++i) { tagtabent = &prof->tagtab.ents[i]; if (tagtabent->off == JAS_CAST(jas_iccuint32_t, prevoff)) { if (prevattrval) { if (!(attrval = jas_iccattrval_clone(prevattrval))) goto error; if (jas_iccprof_setattr(prof, tagtabent->tag, attrval)) goto error; jas_iccattrval_destroy(attrval); attrval = 0; } else { #if 0 jas_eprintf("warning: skipping unknown tag type\n"); #endif } continue; } reloff = tagtabent->off - curoff; if (reloff > 0) { if (jas_stream_gobble(in, reloff) != reloff) goto error; curoff += reloff; } else if (reloff < 0) { /* This should never happen since we read the tagged element data in a single pass. */ abort(); } prevoff = curoff; if (jas_iccgetuint32(in, &type)) { goto error; } if (jas_stream_gobble(in, 4) != 4) { goto error; } curoff += 8; if (!jas_iccattrvalinfo_lookup(type)) { #if 0 jas_eprintf("warning: skipping unknown tag type\n"); #endif prevattrval = 0; continue; } if (!(attrval = jas_iccattrval_create(type))) { goto error; } len = tagtabent->len - 8; if ((*attrval->ops->input)(attrval, in, len)) { goto error; } curoff += len; if (jas_iccprof_setattr(prof, tagtabent->tag, attrval)) { goto error; } prevattrval = attrval; /* This is correct, but slimey. */ jas_iccattrval_destroy(attrval); attrval = 0; } return prof; error: if (prof) jas_iccprof_destroy(prof); if (attrval) jas_iccattrval_destroy(attrval); return 0; } int jas_iccprof_save(jas_iccprof_t *prof, jas_stream_t *out) { long curoff; long reloff; long newoff; int i; int j; jas_icctagtabent_t *tagtabent; jas_icctagtabent_t *sharedtagtabent; jas_icctagtabent_t *tmptagtabent; jas_iccuint32_t attrname; jas_iccattrval_t *attrval; jas_icctagtab_t *tagtab; tagtab = &prof->tagtab; if (!(tagtab->ents = jas_alloc2(prof->attrtab->numattrs, sizeof(jas_icctagtabent_t)))) goto error; tagtab->numents = prof->attrtab->numattrs; curoff = JAS_ICC_HDRLEN + 4 + 12 * tagtab->numents; for (i = 0; i < JAS_CAST(int, tagtab->numents); ++i) { tagtabent = &tagtab->ents[i]; if (jas_iccattrtab_get(prof->attrtab, i, &attrname, &attrval)) goto error; assert(attrval->ops->output); tagtabent->tag = attrname; tagtabent->data = &attrval->data; sharedtagtabent = 0; for (j = 0; j < i; ++j) { tmptagtabent = &tagtab->ents[j]; if (tagtabent->data == tmptagtabent->data) { sharedtagtabent = tmptagtabent; break; } } if (sharedtagtabent) { tagtabent->off = sharedtagtabent->off; tagtabent->len = sharedtagtabent->len; tagtabent->first = sharedtagtabent; } else { tagtabent->off = curoff; tagtabent->len = (*attrval->ops->getsize)(attrval) + 8; tagtabent->first = 0; if (i < JAS_CAST(int, tagtab->numents - 1)) { curoff = jas_iccpadtomult(curoff + tagtabent->len, 4); } else { curoff += tagtabent->len; } } jas_iccattrval_destroy(attrval); } prof->hdr.size = curoff; if (jas_iccprof_writehdr(out, &prof->hdr)) goto error; if (jas_iccprof_puttagtab(out, &prof->tagtab)) goto error; curoff = JAS_ICC_HDRLEN + 4 + 12 * tagtab->numents; for (i = 0; i < JAS_CAST(int, tagtab->numents);) { tagtabent = &tagtab->ents[i]; assert(curoff == JAS_CAST(long, tagtabent->off)); if (jas_iccattrtab_get(prof->attrtab, i, &attrname, &attrval)) goto error; if (jas_iccputuint32(out, attrval->type) || jas_stream_pad(out, 4, 0) != 4) goto error; if ((*attrval->ops->output)(attrval, out)) goto error; jas_iccattrval_destroy(attrval); curoff += tagtabent->len; ++i; while (i < JAS_CAST(int, tagtab->numents) && tagtab->ents[i].first) ++i; newoff = (i < JAS_CAST(int, tagtab->numents)) ? tagtab->ents[i].off : prof->hdr.size; reloff = newoff - curoff; assert(reloff >= 0); if (reloff > 0) { if (jas_stream_pad(out, reloff, 0) != reloff) goto error; curoff += reloff; } } return 0; error: /* XXX - need to free some resources here */ return -1; } static int jas_iccprof_writehdr(jas_stream_t *out, jas_icchdr_t *hdr) { if (jas_iccputuint32(out, hdr->size) || jas_iccputuint32(out, hdr->cmmtype) || jas_iccputuint32(out, hdr->version) || jas_iccputuint32(out, hdr->clas) || jas_iccputuint32(out, hdr->colorspc) || jas_iccputuint32(out, hdr->refcolorspc) || jas_iccputtime(out, &hdr->ctime) || jas_iccputuint32(out, hdr->magic) || jas_iccputuint32(out, hdr->platform) || jas_iccputuint32(out, hdr->flags) || jas_iccputuint32(out, hdr->maker) || jas_iccputuint32(out, hdr->model) || jas_iccputuint64(out, hdr->attr) || jas_iccputuint32(out, hdr->intent) || jas_iccputxyz(out, &hdr->illum) || jas_iccputuint32(out, hdr->creator) || jas_stream_pad(out, 44, 0) != 44) return -1; return 0; } static int jas_iccprof_puttagtab(jas_stream_t *out, jas_icctagtab_t *tagtab) { int i; jas_icctagtabent_t *tagtabent; if (jas_iccputuint32(out, tagtab->numents)) goto error; for (i = 0; i < JAS_CAST(int, tagtab->numents); ++i) { tagtabent = &tagtab->ents[i]; if (jas_iccputuint32(out, tagtabent->tag) || jas_iccputuint32(out, tagtabent->off) || jas_iccputuint32(out, tagtabent->len)) goto error; } return 0; error: return -1; } static int jas_iccprof_readhdr(jas_stream_t *in, jas_icchdr_t *hdr) { if (jas_iccgetuint32(in, &hdr->size) || jas_iccgetuint32(in, &hdr->cmmtype) || jas_iccgetuint32(in, &hdr->version) || jas_iccgetuint32(in, &hdr->clas) || jas_iccgetuint32(in, &hdr->colorspc) || jas_iccgetuint32(in, &hdr->refcolorspc) || jas_iccgettime(in, &hdr->ctime) || jas_iccgetuint32(in, &hdr->magic) || jas_iccgetuint32(in, &hdr->platform) || jas_iccgetuint32(in, &hdr->flags) || jas_iccgetuint32(in, &hdr->maker) || jas_iccgetuint32(in, &hdr->model) || jas_iccgetuint64(in, &hdr->attr) || jas_iccgetuint32(in, &hdr->intent) || jas_iccgetxyz(in, &hdr->illum) || jas_iccgetuint32(in, &hdr->creator) || jas_stream_gobble(in, 44) != 44) return -1; return 0; } static int jas_iccprof_gettagtab(jas_stream_t *in, jas_icctagtab_t *tagtab) { int i; jas_icctagtabent_t *tagtabent; if (tagtab->ents) { jas_free(tagtab->ents); tagtab->ents = 0; } if (jas_iccgetuint32(in, &tagtab->numents)) goto error; if (!(tagtab->ents = jas_alloc2(tagtab->numents, sizeof(jas_icctagtabent_t)))) goto error; tagtabent = tagtab->ents; for (i = 0; i < JAS_CAST(long, tagtab->numents); ++i) { if (jas_iccgetuint32(in, &tagtabent->tag) || jas_iccgetuint32(in, &tagtabent->off) || jas_iccgetuint32(in, &tagtabent->len)) goto error; ++tagtabent; } return 0; error: if (tagtab->ents) { jas_free(tagtab->ents); tagtab->ents = 0; } return -1; } jas_iccattrval_t *jas_iccprof_getattr(jas_iccprof_t *prof, jas_iccattrname_t name) { int i; jas_iccattrval_t *attrval; if ((i = jas_iccattrtab_lookup(prof->attrtab, name)) < 0) goto error; if (!(attrval = jas_iccattrval_clone(prof->attrtab->attrs[i].val))) goto error; return attrval; error: return 0; } int jas_iccprof_setattr(jas_iccprof_t *prof, jas_iccattrname_t name, jas_iccattrval_t *val) { int i; if ((i = jas_iccattrtab_lookup(prof->attrtab, name)) >= 0) { if (val) { if (jas_iccattrtab_replace(prof->attrtab, i, name, val)) goto error; } else { jas_iccattrtab_delete(prof->attrtab, i); } } else { if (val) { if (jas_iccattrtab_add(prof->attrtab, -1, name, val)) goto error; } else { /* NOP */ } } return 0; error: return -1; } int jas_iccprof_gethdr(jas_iccprof_t *prof, jas_icchdr_t *hdr) { *hdr = prof->hdr; return 0; } int jas_iccprof_sethdr(jas_iccprof_t *prof, jas_icchdr_t *hdr) { prof->hdr = *hdr; return 0; } static void jas_iccprof_sorttagtab(jas_icctagtab_t *tagtab) { qsort(tagtab->ents, tagtab->numents, sizeof(jas_icctagtabent_t), jas_icctagtabent_cmp); } static int jas_icctagtabent_cmp(const void *src, const void *dst) { jas_icctagtabent_t *srctagtabent = JAS_CAST(jas_icctagtabent_t *, src); jas_icctagtabent_t *dsttagtabent = JAS_CAST(jas_icctagtabent_t *, dst); if (srctagtabent->off > dsttagtabent->off) { return 1; } else if (srctagtabent->off < dsttagtabent->off) { return -1; } return 0; } static jas_iccattrvalinfo_t *jas_iccattrvalinfo_lookup(jas_iccsig_t type) { jas_iccattrvalinfo_t *info; info = jas_iccattrvalinfos; for (info = jas_iccattrvalinfos; info->type; ++info) { if (info->type == type) { return info; } } return 0; } static int jas_iccgettime(jas_stream_t *in, jas_icctime_t *time) { if (jas_iccgetuint16(in, &time->year) || jas_iccgetuint16(in, &time->month) || jas_iccgetuint16(in, &time->day) || jas_iccgetuint16(in, &time->hour) || jas_iccgetuint16(in, &time->min) || jas_iccgetuint16(in, &time->sec)) { return -1; } return 0; } static int jas_iccgetxyz(jas_stream_t *in, jas_iccxyz_t *xyz) { if (jas_iccgetsint32(in, &xyz->x) || jas_iccgetsint32(in, &xyz->y) || jas_iccgetsint32(in, &xyz->z)) { return -1; } return 0; } static int jas_iccputtime(jas_stream_t *out, jas_icctime_t *time) { jas_iccputuint16(out, time->year); jas_iccputuint16(out, time->month); jas_iccputuint16(out, time->day); jas_iccputuint16(out, time->hour); jas_iccputuint16(out, time->min); jas_iccputuint16(out, time->sec); return 0; } static int jas_iccputxyz(jas_stream_t *out, jas_iccxyz_t *xyz) { jas_iccputuint32(out, xyz->x); jas_iccputuint32(out, xyz->y); jas_iccputuint32(out, xyz->z); return 0; } /******************************************************************************\ * attribute table class \******************************************************************************/ static jas_iccattrtab_t *jas_iccattrtab_create() { jas_iccattrtab_t *tab; tab = 0; if (!(tab = jas_malloc(sizeof(jas_iccattrtab_t)))) goto error; tab->maxattrs = 0; tab->numattrs = 0; tab->attrs = 0; if (jas_iccattrtab_resize(tab, 32)) goto error; return tab; error: if (tab) jas_iccattrtab_destroy(tab); return 0; } static jas_iccattrtab_t *jas_iccattrtab_copy(jas_iccattrtab_t *attrtab) { jas_iccattrtab_t *newattrtab; int i; if (!(newattrtab = jas_iccattrtab_create())) goto error; for (i = 0; i < attrtab->numattrs; ++i) { if (jas_iccattrtab_add(newattrtab, i, attrtab->attrs[i].name, attrtab->attrs[i].val)) goto error; } return newattrtab; error: return 0; } static void jas_iccattrtab_destroy(jas_iccattrtab_t *tab) { if (tab->attrs) { while (tab->numattrs > 0) { jas_iccattrtab_delete(tab, 0); } jas_free(tab->attrs); } jas_free(tab); } void jas_iccattrtab_dump(jas_iccattrtab_t *attrtab, FILE *out) { int i; jas_iccattr_t *attr; jas_iccattrval_t *attrval; jas_iccattrvalinfo_t *info; char buf[16]; fprintf(out, "numattrs=%d\n", attrtab->numattrs); fprintf(out, "---\n"); for (i = 0; i < attrtab->numattrs; ++i) { attr = &attrtab->attrs[i]; attrval = attr->val; info = jas_iccattrvalinfo_lookup(attrval->type); if (!info) abort(); fprintf(out, "attrno=%d; attrname=\"%s\"(0x%08"PRIxFAST32"); attrtype=\"%s\"(0x%08"PRIxFAST32")\n", i, jas_iccsigtostr(attr->name, &buf[0]), attr->name, jas_iccsigtostr(attrval->type, &buf[8]), attrval->type ); jas_iccattrval_dump(attrval, out); fprintf(out, "---\n"); } } static int jas_iccattrtab_resize(jas_iccattrtab_t *tab, int maxents) { jas_iccattr_t *newattrs; assert(maxents >= tab->numattrs); newattrs = tab->attrs ? jas_realloc2(tab->attrs, maxents, sizeof(jas_iccattr_t)) : jas_alloc2(maxents, sizeof(jas_iccattr_t)); if (!newattrs) { return -1; } tab->attrs = newattrs; tab->maxattrs = maxents; return 0; } static int jas_iccattrtab_add(jas_iccattrtab_t *attrtab, int i, jas_iccuint32_t name, jas_iccattrval_t *val) { int n; jas_iccattr_t *attr; jas_iccattrval_t *tmpattrval; tmpattrval = 0; if (i < 0) { i = attrtab->numattrs; } assert(i >= 0 && i <= attrtab->numattrs); if (attrtab->numattrs >= attrtab->maxattrs) { if (jas_iccattrtab_resize(attrtab, attrtab->numattrs + 32)) { goto error; } } if (!(tmpattrval = jas_iccattrval_clone(val))) goto error; n = attrtab->numattrs - i; if (n > 0) memmove(&attrtab->attrs[i + 1], &attrtab->attrs[i], n * sizeof(jas_iccattr_t)); attr = &attrtab->attrs[i]; attr->name = name; attr->val = tmpattrval; ++attrtab->numattrs; return 0; error: if (tmpattrval) jas_iccattrval_destroy(tmpattrval); return -1; } static int jas_iccattrtab_replace(jas_iccattrtab_t *attrtab, int i, jas_iccuint32_t name, jas_iccattrval_t *val) { jas_iccattrval_t *newval; jas_iccattr_t *attr; if (!(newval = jas_iccattrval_clone(val))) goto error; attr = &attrtab->attrs[i]; jas_iccattrval_destroy(attr->val); attr->name = name; attr->val = newval; return 0; error: return -1; } static void jas_iccattrtab_delete(jas_iccattrtab_t *attrtab, int i) { int n; jas_iccattrval_destroy(attrtab->attrs[i].val); if ((n = attrtab->numattrs - i - 1) > 0) memmove(&attrtab->attrs[i], &attrtab->attrs[i + 1], n * sizeof(jas_iccattr_t)); --attrtab->numattrs; } static int jas_iccattrtab_get(jas_iccattrtab_t *attrtab, int i, jas_iccattrname_t *name, jas_iccattrval_t **val) { jas_iccattr_t *attr; if (i < 0 || i >= attrtab->numattrs) goto error; attr = &attrtab->attrs[i]; *name = attr->name; if (!(*val = jas_iccattrval_clone(attr->val))) goto error; return 0; error: return -1; } static int jas_iccattrtab_lookup(jas_iccattrtab_t *attrtab, jas_iccuint32_t name) { int i; jas_iccattr_t *attr; for (i = 0; i < attrtab->numattrs; ++i) { attr = &attrtab->attrs[i]; if (attr->name == name) return i; } return -1; } /******************************************************************************\ * attribute value class \******************************************************************************/ jas_iccattrval_t *jas_iccattrval_create(jas_iccuint32_t type) { jas_iccattrval_t *attrval; jas_iccattrvalinfo_t *info; if (!(info = jas_iccattrvalinfo_lookup(type))) goto error; if (!(attrval = jas_iccattrval_create0())) goto error; attrval->ops = &info->ops; attrval->type = type; ++attrval->refcnt; memset(&attrval->data, 0, sizeof(attrval->data)); return attrval; error: return 0; } jas_iccattrval_t *jas_iccattrval_clone(jas_iccattrval_t *attrval) { ++attrval->refcnt; return attrval; } void jas_iccattrval_destroy(jas_iccattrval_t *attrval) { #if 0 jas_eprintf("refcnt=%d\n", attrval->refcnt); #endif if (--attrval->refcnt <= 0) { if (attrval->ops->destroy) (*attrval->ops->destroy)(attrval); jas_free(attrval); } } void jas_iccattrval_dump(jas_iccattrval_t *attrval, FILE *out) { char buf[8]; jas_iccsigtostr(attrval->type, buf); fprintf(out, "refcnt = %d; type = 0x%08"PRIxFAST32" %s\n", attrval->refcnt, attrval->type, jas_iccsigtostr(attrval->type, &buf[0])); if (attrval->ops->dump) { (*attrval->ops->dump)(attrval, out); } } int jas_iccattrval_allowmodify(jas_iccattrval_t **attrvalx) { jas_iccattrval_t *newattrval; jas_iccattrval_t *attrval = *attrvalx; newattrval = 0; if (attrval->refcnt > 1) { if (!(newattrval = jas_iccattrval_create0())) goto error; newattrval->ops = attrval->ops; newattrval->type = attrval->type; ++newattrval->refcnt; if (newattrval->ops->copy) { if ((*newattrval->ops->copy)(newattrval, attrval)) goto error; } else { memcpy(&newattrval->data, &attrval->data, sizeof(newattrval->data)); } *attrvalx = newattrval; } return 0; error: if (newattrval) { jas_free(newattrval); } return -1; } static jas_iccattrval_t *jas_iccattrval_create0() { jas_iccattrval_t *attrval; if (!(attrval = jas_malloc(sizeof(jas_iccattrval_t)))) return 0; memset(attrval, 0, sizeof(jas_iccattrval_t)); attrval->refcnt = 0; attrval->ops = 0; attrval->type = 0; return attrval; } /******************************************************************************\ * \******************************************************************************/ static int jas_iccxyz_input(jas_iccattrval_t *attrval, jas_stream_t *in, int len) { if (len != 4 * 3) abort(); return jas_iccgetxyz(in, &attrval->data.xyz); } static int jas_iccxyz_output(jas_iccattrval_t *attrval, jas_stream_t *out) { jas_iccxyz_t *xyz = &attrval->data.xyz; if (jas_iccputuint32(out, xyz->x) || jas_iccputuint32(out, xyz->y) || jas_iccputuint32(out, xyz->z)) return -1; return 0; } static int jas_iccxyz_getsize(jas_iccattrval_t *attrval) { /* Avoid compiler warnings about unused parameters. */ attrval = 0; return 12; } static void jas_iccxyz_dump(jas_iccattrval_t *attrval, FILE *out) { jas_iccxyz_t *xyz = &attrval->data.xyz; fprintf(out, "(%f, %f, %f)\n", xyz->x / 65536.0, xyz->y / 65536.0, xyz->z / 65536.0); } /******************************************************************************\ * attribute table class \******************************************************************************/ static void jas_icccurv_destroy(jas_iccattrval_t *attrval) { jas_icccurv_t *curv = &attrval->data.curv; if (curv->ents) { jas_free(curv->ents); curv->ents = 0; } } static int jas_icccurv_copy(jas_iccattrval_t *attrval, jas_iccattrval_t *othattrval) { /* Avoid compiler warnings about unused parameters. */ attrval = 0; othattrval = 0; /* Not yet implemented. */ abort(); return -1; } static int jas_icccurv_input(jas_iccattrval_t *attrval, jas_stream_t *in, int cnt) { jas_icccurv_t *curv = &attrval->data.curv; unsigned int i; curv->numents = 0; curv->ents = 0; if (jas_iccgetuint32(in, &curv->numents)) goto error; if (!(curv->ents = jas_alloc2(curv->numents, sizeof(jas_iccuint16_t)))) goto error; for (i = 0; i < curv->numents; ++i) { if (jas_iccgetuint16(in, &curv->ents[i])) goto error; } if (JAS_CAST(int, 4 + 2 * curv->numents) != cnt) goto error; return 0; error: jas_icccurv_destroy(attrval); return -1; } static int jas_icccurv_getsize(jas_iccattrval_t *attrval) { jas_icccurv_t *curv = &attrval->data.curv; return 4 + 2 * curv->numents; } static int jas_icccurv_output(jas_iccattrval_t *attrval, jas_stream_t *out) { jas_icccurv_t *curv = &attrval->data.curv; unsigned int i; if (jas_iccputuint32(out, curv->numents)) goto error; for (i = 0; i < curv->numents; ++i) { if (jas_iccputuint16(out, curv->ents[i])) goto error; } return 0; error: return -1; } static void jas_icccurv_dump(jas_iccattrval_t *attrval, FILE *out) { int i; jas_icccurv_t *curv = &attrval->data.curv; fprintf(out, "number of entries = %"PRIuFAST32"\n", curv->numents); if (curv->numents == 1) { fprintf(out, "gamma = %f\n", curv->ents[0] / 256.0); } else { for (i = 0; i < JAS_CAST(int, curv->numents); ++i) { if (i < 3 || i >= JAS_CAST(int, curv->numents) - 3) { fprintf(out, "entry[%d] = %f\n", i, curv->ents[i] / 65535.0); } } } } /******************************************************************************\ * \******************************************************************************/ static void jas_icctxtdesc_destroy(jas_iccattrval_t *attrval) { jas_icctxtdesc_t *txtdesc = &attrval->data.txtdesc; if (txtdesc->ascdata) { jas_free(txtdesc->ascdata); txtdesc->ascdata = 0; } if (txtdesc->ucdata) { jas_free(txtdesc->ucdata); txtdesc->ucdata = 0; } } static int jas_icctxtdesc_copy(jas_iccattrval_t *attrval, jas_iccattrval_t *othattrval) { jas_icctxtdesc_t *txtdesc = &attrval->data.txtdesc; /* Avoid compiler warnings about unused parameters. */ attrval = 0; othattrval = 0; txtdesc = 0; /* Not yet implemented. */ abort(); return -1; } static int jas_icctxtdesc_input(jas_iccattrval_t *attrval, jas_stream_t *in, int cnt) { int n; int c; jas_icctxtdesc_t *txtdesc = &attrval->data.txtdesc; txtdesc->ascdata = 0; txtdesc->ucdata = 0; if (jas_iccgetuint32(in, &txtdesc->asclen)) goto error; if (!(txtdesc->ascdata = jas_malloc(txtdesc->asclen))) goto error; if (jas_stream_read(in, txtdesc->ascdata, txtdesc->asclen) != JAS_CAST(int, txtdesc->asclen)) goto error; txtdesc->ascdata[txtdesc->asclen - 1] = '\0'; if (jas_iccgetuint32(in, &txtdesc->uclangcode) || jas_iccgetuint32(in, &txtdesc->uclen)) goto error; if (!(txtdesc->ucdata = jas_alloc2(txtdesc->uclen, 2))) goto error; if (jas_stream_read(in, txtdesc->ucdata, txtdesc->uclen * 2) != JAS_CAST(int, txtdesc->uclen * 2)) goto error; if (jas_iccgetuint16(in, &txtdesc->sccode)) goto error; if ((c = jas_stream_getc(in)) == EOF) goto error; txtdesc->maclen = c; if (jas_stream_read(in, txtdesc->macdata, 67) != 67) goto error; txtdesc->asclen = JAS_CAST(jas_iccuint32_t, strlen(txtdesc->ascdata) + 1); #define WORKAROUND_BAD_PROFILES #ifdef WORKAROUND_BAD_PROFILES n = txtdesc->asclen + txtdesc->uclen * 2 + 15 + 67; if (n > cnt) { return -1; } if (n < cnt) { if (jas_stream_gobble(in, cnt - n) != cnt - n) goto error; } #else if (txtdesc->asclen + txtdesc->uclen * 2 + 15 + 67 != cnt) return -1; #endif return 0; error: jas_icctxtdesc_destroy(attrval); return -1; } static int jas_icctxtdesc_getsize(jas_iccattrval_t *attrval) { jas_icctxtdesc_t *txtdesc = &attrval->data.txtdesc; return JAS_CAST(int, strlen(txtdesc->ascdata) + 1 + txtdesc->uclen * 2 + 15 + 67); } static int jas_icctxtdesc_output(jas_iccattrval_t *attrval, jas_stream_t *out) { jas_icctxtdesc_t *txtdesc = &attrval->data.txtdesc; if (jas_iccputuint32(out, txtdesc->asclen) || jas_stream_puts(out, txtdesc->ascdata) || jas_stream_putc(out, 0) == EOF || jas_iccputuint32(out, txtdesc->uclangcode) || jas_iccputuint32(out, txtdesc->uclen) || jas_stream_write(out, txtdesc->ucdata, txtdesc->uclen * 2) != JAS_CAST(int, txtdesc->uclen * 2) || jas_iccputuint16(out, txtdesc->sccode) || jas_stream_putc(out, txtdesc->maclen) == EOF) goto error; if (txtdesc->maclen > 0) { if (jas_stream_write(out, txtdesc->macdata, 67) != 67) goto error; } else { if (jas_stream_pad(out, 67, 0) != 67) goto error; } return 0; error: return -1; } static void jas_icctxtdesc_dump(jas_iccattrval_t *attrval, FILE *out) { jas_icctxtdesc_t *txtdesc = &attrval->data.txtdesc; fprintf(out, "ascii = \"%s\"\n", txtdesc->ascdata); fprintf(out, "uclangcode = %"PRIuFAST32"; uclen = %"PRIuFAST32"\n", txtdesc->uclangcode, txtdesc->uclen); fprintf(out, "sccode = %"PRIuFAST16"\n", txtdesc->sccode); fprintf(out, "maclen = %d\n", txtdesc->maclen); } /******************************************************************************\ * \******************************************************************************/ static void jas_icctxt_destroy(jas_iccattrval_t *attrval) { jas_icctxt_t *txt = &attrval->data.txt; if (txt->string) { jas_free(txt->string); txt->string = 0; } } static int jas_icctxt_copy(jas_iccattrval_t *attrval, jas_iccattrval_t *othattrval) { jas_icctxt_t *txt = &attrval->data.txt; jas_icctxt_t *othtxt = &othattrval->data.txt; if (!(txt->string = jas_strdup(othtxt->string))) return -1; return 0; } static int jas_icctxt_input(jas_iccattrval_t *attrval, jas_stream_t *in, int cnt) { jas_icctxt_t *txt = &attrval->data.txt; txt->string = 0; if (!(txt->string = jas_malloc(cnt))) goto error; if (jas_stream_read(in, txt->string, cnt) != cnt) goto error; txt->string[cnt - 1] = '\0'; if (JAS_CAST(int, strlen(txt->string)) + 1 != cnt) goto error; return 0; error: jas_icctxt_destroy(attrval); return -1; } static int jas_icctxt_getsize(jas_iccattrval_t *attrval) { jas_icctxt_t *txt = &attrval->data.txt; return JAS_CAST(int, strlen(txt->string) + 1); } static int jas_icctxt_output(jas_iccattrval_t *attrval, jas_stream_t *out) { jas_icctxt_t *txt = &attrval->data.txt; if (jas_stream_puts(out, txt->string) || jas_stream_putc(out, 0) == EOF) return -1; return 0; } static void jas_icctxt_dump(jas_iccattrval_t *attrval, FILE *out) { jas_icctxt_t *txt = &attrval->data.txt; fprintf(out, "string = \"%s\"\n", txt->string); } /******************************************************************************\ * \******************************************************************************/ static void jas_icclut8_destroy(jas_iccattrval_t *attrval) { jas_icclut8_t *lut8 = &attrval->data.lut8; if (lut8->clut) { jas_free(lut8->clut); lut8->clut = 0; } if (lut8->intabs) { jas_free(lut8->intabs); lut8->intabs = 0; } if (lut8->intabsbuf) { jas_free(lut8->intabsbuf); lut8->intabsbuf = 0; } if (lut8->outtabs) { jas_free(lut8->outtabs); lut8->outtabs = 0; } if (lut8->outtabsbuf) { jas_free(lut8->outtabsbuf); lut8->outtabsbuf = 0; } } static int jas_icclut8_copy(jas_iccattrval_t *attrval, jas_iccattrval_t *othattrval) { jas_icclut8_t *lut8 = &attrval->data.lut8; /* Avoid compiler warnings about unused parameters. */ attrval = 0; othattrval = 0; lut8 = 0; abort(); return -1; } static int jas_icclut8_input(jas_iccattrval_t *attrval, jas_stream_t *in, int cnt) { int i; int j; int clutsize; jas_icclut8_t *lut8 = &attrval->data.lut8; lut8->clut = 0; lut8->intabs = 0; lut8->intabsbuf = 0; lut8->outtabs = 0; lut8->outtabsbuf = 0; if (jas_iccgetuint8(in, &lut8->numinchans) || jas_iccgetuint8(in, &lut8->numoutchans) || jas_iccgetuint8(in, &lut8->clutlen) || jas_stream_getc(in) == EOF) goto error; for (i = 0; i < 3; ++i) { for (j = 0; j < 3; ++j) { if (jas_iccgetsint32(in, &lut8->e[i][j])) goto error; } } if (jas_iccgetuint16(in, &lut8->numintabents) || jas_iccgetuint16(in, &lut8->numouttabents)) goto error; clutsize = jas_iccpowi(lut8->clutlen, lut8->numinchans) * lut8->numoutchans; if (!(lut8->clut = jas_alloc2(clutsize, sizeof(jas_iccuint8_t))) || !(lut8->intabsbuf = jas_alloc3(lut8->numinchans, lut8->numintabents, sizeof(jas_iccuint8_t))) || !(lut8->intabs = jas_alloc2(lut8->numinchans, sizeof(jas_iccuint8_t *)))) goto error; for (i = 0; i < lut8->numinchans; ++i) lut8->intabs[i] = &lut8->intabsbuf[i * lut8->numintabents]; if (!(lut8->outtabsbuf = jas_alloc3(lut8->numoutchans, lut8->numouttabents, sizeof(jas_iccuint8_t))) || !(lut8->outtabs = jas_alloc2(lut8->numoutchans, sizeof(jas_iccuint8_t *)))) goto error; for (i = 0; i < lut8->numoutchans; ++i) lut8->outtabs[i] = &lut8->outtabsbuf[i * lut8->numouttabents]; for (i = 0; i < lut8->numinchans; ++i) { for (j = 0; j < JAS_CAST(int, lut8->numintabents); ++j) { if (jas_iccgetuint8(in, &lut8->intabs[i][j])) goto error; } } for (i = 0; i < lut8->numoutchans; ++i) { for (j = 0; j < JAS_CAST(int, lut8->numouttabents); ++j) { if (jas_iccgetuint8(in, &lut8->outtabs[i][j])) goto error; } } for (i = 0; i < clutsize; ++i) { if (jas_iccgetuint8(in, &lut8->clut[i])) goto error; } if (JAS_CAST(int, 44 + lut8->numinchans * lut8->numintabents + lut8->numoutchans * lut8->numouttabents + jas_iccpowi(lut8->clutlen, lut8->numinchans) * lut8->numoutchans) != cnt) goto error; return 0; error: jas_icclut8_destroy(attrval); return -1; } static int jas_icclut8_getsize(jas_iccattrval_t *attrval) { jas_icclut8_t *lut8 = &attrval->data.lut8; return 44 + lut8->numinchans * lut8->numintabents + lut8->numoutchans * lut8->numouttabents + jas_iccpowi(lut8->clutlen, lut8->numinchans) * lut8->numoutchans; } static int jas_icclut8_output(jas_iccattrval_t *attrval, jas_stream_t *out) { jas_icclut8_t *lut8 = &attrval->data.lut8; int i; int j; int n; lut8->clut = 0; lut8->intabs = 0; lut8->intabsbuf = 0; lut8->outtabs = 0; lut8->outtabsbuf = 0; if (jas_stream_putc(out, lut8->numinchans) == EOF || jas_stream_putc(out, lut8->numoutchans) == EOF || jas_stream_putc(out, lut8->clutlen) == EOF || jas_stream_putc(out, 0) == EOF) goto error; for (i = 0; i < 3; ++i) { for (j = 0; j < 3; ++j) { if (jas_iccputsint32(out, lut8->e[i][j])) goto error; } } if (jas_iccputuint16(out, lut8->numintabents) || jas_iccputuint16(out, lut8->numouttabents)) goto error; n = lut8->numinchans * lut8->numintabents; for (i = 0; i < n; ++i) { if (jas_iccputuint8(out, lut8->intabsbuf[i])) goto error; } n = lut8->numoutchans * lut8->numouttabents; for (i = 0; i < n; ++i) { if (jas_iccputuint8(out, lut8->outtabsbuf[i])) goto error; } n = jas_iccpowi(lut8->clutlen, lut8->numinchans) * lut8->numoutchans; for (i = 0; i < n; ++i) { if (jas_iccputuint8(out, lut8->clut[i])) goto error; } return 0; error: return -1; } static void jas_icclut8_dump(jas_iccattrval_t *attrval, FILE *out) { jas_icclut8_t *lut8 = &attrval->data.lut8; int i; int j; fprintf(out, "numinchans=%d, numoutchans=%d, clutlen=%d\n", lut8->numinchans, lut8->numoutchans, lut8->clutlen); for (i = 0; i < 3; ++i) { for (j = 0; j < 3; ++j) { fprintf(out, "e[%d][%d]=%f ", i, j, lut8->e[i][j] / 65536.0); } fprintf(out, "\n"); } fprintf(out, "numintabents=%"PRIuFAST16", numouttabents=%"PRIuFAST16"\n", lut8->numintabents, lut8->numouttabents); } /******************************************************************************\ * \******************************************************************************/ static void jas_icclut16_destroy(jas_iccattrval_t *attrval) { jas_icclut16_t *lut16 = &attrval->data.lut16; if (lut16->clut) { jas_free(lut16->clut); lut16->clut = 0; } if (lut16->intabs) { jas_free(lut16->intabs); lut16->intabs = 0; } if (lut16->intabsbuf) { jas_free(lut16->intabsbuf); lut16->intabsbuf = 0; } if (lut16->outtabs) { jas_free(lut16->outtabs); lut16->outtabs = 0; } if (lut16->outtabsbuf) { jas_free(lut16->outtabsbuf); lut16->outtabsbuf = 0; } } static int jas_icclut16_copy(jas_iccattrval_t *attrval, jas_iccattrval_t *othattrval) { /* Avoid compiler warnings about unused parameters. */ attrval = 0; othattrval = 0; /* Not yet implemented. */ abort(); return -1; } static int jas_icclut16_input(jas_iccattrval_t *attrval, jas_stream_t *in, int cnt) { int i; int j; int clutsize; jas_icclut16_t *lut16 = &attrval->data.lut16; lut16->clut = 0; lut16->intabs = 0; lut16->intabsbuf = 0; lut16->outtabs = 0; lut16->outtabsbuf = 0; if (jas_iccgetuint8(in, &lut16->numinchans) || jas_iccgetuint8(in, &lut16->numoutchans) || jas_iccgetuint8(in, &lut16->clutlen) || jas_stream_getc(in) == EOF) goto error; for (i = 0; i < 3; ++i) { for (j = 0; j < 3; ++j) { if (jas_iccgetsint32(in, &lut16->e[i][j])) goto error; } } if (jas_iccgetuint16(in, &lut16->numintabents) || jas_iccgetuint16(in, &lut16->numouttabents)) goto error; clutsize = jas_iccpowi(lut16->clutlen, lut16->numinchans) * lut16->numoutchans; if (!(lut16->clut = jas_alloc2(clutsize, sizeof(jas_iccuint16_t))) || !(lut16->intabsbuf = jas_alloc3(lut16->numinchans, lut16->numintabents, sizeof(jas_iccuint16_t))) || !(lut16->intabs = jas_alloc2(lut16->numinchans, sizeof(jas_iccuint16_t *)))) goto error; for (i = 0; i < lut16->numinchans; ++i) lut16->intabs[i] = &lut16->intabsbuf[i * lut16->numintabents]; if (!(lut16->outtabsbuf = jas_alloc3(lut16->numoutchans, lut16->numouttabents, sizeof(jas_iccuint16_t))) || !(lut16->outtabs = jas_alloc2(lut16->numoutchans, sizeof(jas_iccuint16_t *)))) goto error; for (i = 0; i < lut16->numoutchans; ++i) lut16->outtabs[i] = &lut16->outtabsbuf[i * lut16->numouttabents]; for (i = 0; i < lut16->numinchans; ++i) { for (j = 0; j < JAS_CAST(int, lut16->numintabents); ++j) { if (jas_iccgetuint16(in, &lut16->intabs[i][j])) goto error; } } for (i = 0; i < lut16->numoutchans; ++i) { for (j = 0; j < JAS_CAST(int, lut16->numouttabents); ++j) { if (jas_iccgetuint16(in, &lut16->outtabs[i][j])) goto error; } } for (i = 0; i < clutsize; ++i) { if (jas_iccgetuint16(in, &lut16->clut[i])) goto error; } if (JAS_CAST(int, 44 + 2 * (lut16->numinchans * lut16->numintabents + lut16->numoutchans * lut16->numouttabents + jas_iccpowi(lut16->clutlen, lut16->numinchans) * lut16->numoutchans)) != cnt) goto error; return 0; error: jas_icclut16_destroy(attrval); return -1; } static int jas_icclut16_getsize(jas_iccattrval_t *attrval) { jas_icclut16_t *lut16 = &attrval->data.lut16; return 44 + 2 * (lut16->numinchans * lut16->numintabents + lut16->numoutchans * lut16->numouttabents + jas_iccpowi(lut16->clutlen, lut16->numinchans) * lut16->numoutchans); } static int jas_icclut16_output(jas_iccattrval_t *attrval, jas_stream_t *out) { jas_icclut16_t *lut16 = &attrval->data.lut16; int i; int j; int n; if (jas_stream_putc(out, lut16->numinchans) == EOF || jas_stream_putc(out, lut16->numoutchans) == EOF || jas_stream_putc(out, lut16->clutlen) == EOF || jas_stream_putc(out, 0) == EOF) goto error; for (i = 0; i < 3; ++i) { for (j = 0; j < 3; ++j) { if (jas_iccputsint32(out, lut16->e[i][j])) goto error; } } if (jas_iccputuint16(out, lut16->numintabents) || jas_iccputuint16(out, lut16->numouttabents)) goto error; n = lut16->numinchans * lut16->numintabents; for (i = 0; i < n; ++i) { if (jas_iccputuint16(out, lut16->intabsbuf[i])) goto error; } n = lut16->numoutchans * lut16->numouttabents; for (i = 0; i < n; ++i) { if (jas_iccputuint16(out, lut16->outtabsbuf[i])) goto error; } n = jas_iccpowi(lut16->clutlen, lut16->numinchans) * lut16->numoutchans; for (i = 0; i < n; ++i) { if (jas_iccputuint16(out, lut16->clut[i])) goto error; } return 0; error: return -1; } static void jas_icclut16_dump(jas_iccattrval_t *attrval, FILE *out) { jas_icclut16_t *lut16 = &attrval->data.lut16; int i; int j; fprintf(out, "numinchans=%d, numoutchans=%d, clutlen=%d\n", lut16->numinchans, lut16->numoutchans, lut16->clutlen); for (i = 0; i < 3; ++i) { for (j = 0; j < 3; ++j) { fprintf(out, "e[%d][%d]=%f ", i, j, lut16->e[i][j] / 65536.0); } fprintf(out, "\n"); } fprintf(out, "numintabents=%"PRIuFAST16", numouttabents=%"PRIuFAST16"\n", lut16->numintabents, lut16->numouttabents); } /******************************************************************************\ * \******************************************************************************/ static int jas_iccgetuint(jas_stream_t *in, int n, ulonglong *val) { int i; int c; ulonglong v; v = 0; for (i = n; i > 0; --i) { if ((c = jas_stream_getc(in)) == EOF) return -1; v = (v << 8) | c; } *val = v; return 0; } static int jas_iccgetuint8(jas_stream_t *in, jas_iccuint8_t *val) { int c; if ((c = jas_stream_getc(in)) == EOF) return -1; *val = c; return 0; } static int jas_iccgetuint16(jas_stream_t *in, jas_iccuint16_t *val) { ulonglong tmp; if (jas_iccgetuint(in, 2, &tmp)) return -1; *val = tmp; return 0; } static int jas_iccgetsint32(jas_stream_t *in, jas_iccsint32_t *val) { ulonglong tmp; if (jas_iccgetuint(in, 4, &tmp)) return -1; *val = (tmp & 0x80000000) ? (-JAS_CAST(longlong, (((~tmp) & 0x7fffffff) + 1))) : JAS_CAST(longlong, tmp); return 0; } static int jas_iccgetuint32(jas_stream_t *in, jas_iccuint32_t *val) { ulonglong tmp; if (jas_iccgetuint(in, 4, &tmp)) return -1; *val = tmp; return 0; } static int jas_iccgetuint64(jas_stream_t *in, jas_iccuint64_t *val) { ulonglong tmp; if (jas_iccgetuint(in, 8, &tmp)) return -1; *val = tmp; return 0; } static int jas_iccputuint(jas_stream_t *out, int n, ulonglong val) { int i; int c; for (i = n; i > 0; --i) { c = (val >> (8 * (i - 1))) & 0xff; if (jas_stream_putc(out, c) == EOF) return -1; } return 0; } static int jas_iccputsint(jas_stream_t *out, int n, longlong val) { ulonglong tmp; tmp = (val < 0) ? (abort(), 0) : val; return jas_iccputuint(out, n, tmp); } /******************************************************************************\ * \******************************************************************************/ static char *jas_iccsigtostr(int sig, char *buf) { int n; int c; char *bufptr; bufptr = buf; for (n = 4; n > 0; --n) { c = (sig >> 24) & 0xff; if (isalpha(c) || isdigit(c)) { *bufptr++ = c; } sig <<= 8; } *bufptr = '\0'; return buf; } static long jas_iccpadtomult(long x, long y) { return ((x + y - 1) / y) * y; } static long jas_iccpowi(int x, int n) { long y; y = 1; while (--n >= 0) y *= x; return y; } jas_iccprof_t *jas_iccprof_createfrombuf(uchar *buf, int len) { jas_stream_t *in; jas_iccprof_t *prof; if (!(in = jas_stream_memopen(JAS_CAST(char *, buf), len))) goto error; if (!(prof = jas_iccprof_load(in))) goto error; jas_stream_close(in); return prof; error: if (in) jas_stream_close(in); return 0; } jas_iccprof_t *jas_iccprof_createfromclrspc(int clrspc) { jas_iccprof_t *prof; switch (clrspc) { case JAS_CLRSPC_SRGB: prof = jas_iccprof_createfrombuf(jas_iccprofdata_srgb, jas_iccprofdata_srgblen); break; case JAS_CLRSPC_SGRAY: prof = jas_iccprof_createfrombuf(jas_iccprofdata_sgray, jas_iccprofdata_sgraylen); break; default: prof = 0; break; } return prof; }
./CrossVul/dataset_final_sorted/CWE-20/c/bad_5418_4
crossvul-cpp_data_good_405_0
/* * Copyright (C) 2012,2013 - ARM Ltd * Author: Marc Zyngier <marc.zyngier@arm.com> * * Derived from arch/arm/kvm/guest.c: * Copyright (C) 2012 - Virtual Open Systems and Columbia University * Author: Christoffer Dall <c.dall@virtualopensystems.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * 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 <linux/errno.h> #include <linux/err.h> #include <linux/kvm_host.h> #include <linux/module.h> #include <linux/vmalloc.h> #include <linux/fs.h> #include <kvm/arm_psci.h> #include <asm/cputype.h> #include <linux/uaccess.h> #include <asm/kvm.h> #include <asm/kvm_emulate.h> #include <asm/kvm_coproc.h> #include "trace.h" #define VM_STAT(x) { #x, offsetof(struct kvm, stat.x), KVM_STAT_VM } #define VCPU_STAT(x) { #x, offsetof(struct kvm_vcpu, stat.x), KVM_STAT_VCPU } struct kvm_stats_debugfs_item debugfs_entries[] = { VCPU_STAT(hvc_exit_stat), VCPU_STAT(wfe_exit_stat), VCPU_STAT(wfi_exit_stat), VCPU_STAT(mmio_exit_user), VCPU_STAT(mmio_exit_kernel), VCPU_STAT(exits), { NULL } }; int kvm_arch_vcpu_setup(struct kvm_vcpu *vcpu) { return 0; } static u64 core_reg_offset_from_id(u64 id) { return id & ~(KVM_REG_ARCH_MASK | KVM_REG_SIZE_MASK | KVM_REG_ARM_CORE); } static int validate_core_offset(const struct kvm_one_reg *reg) { u64 off = core_reg_offset_from_id(reg->id); int size; switch (off) { case KVM_REG_ARM_CORE_REG(regs.regs[0]) ... KVM_REG_ARM_CORE_REG(regs.regs[30]): case KVM_REG_ARM_CORE_REG(regs.sp): case KVM_REG_ARM_CORE_REG(regs.pc): case KVM_REG_ARM_CORE_REG(regs.pstate): case KVM_REG_ARM_CORE_REG(sp_el1): case KVM_REG_ARM_CORE_REG(elr_el1): case KVM_REG_ARM_CORE_REG(spsr[0]) ... KVM_REG_ARM_CORE_REG(spsr[KVM_NR_SPSR - 1]): size = sizeof(__u64); break; case KVM_REG_ARM_CORE_REG(fp_regs.vregs[0]) ... KVM_REG_ARM_CORE_REG(fp_regs.vregs[31]): size = sizeof(__uint128_t); break; case KVM_REG_ARM_CORE_REG(fp_regs.fpsr): case KVM_REG_ARM_CORE_REG(fp_regs.fpcr): size = sizeof(__u32); break; default: return -EINVAL; } if (KVM_REG_SIZE(reg->id) == size && IS_ALIGNED(off, size / sizeof(__u32))) return 0; return -EINVAL; } static int get_core_reg(struct kvm_vcpu *vcpu, const struct kvm_one_reg *reg) { /* * Because the kvm_regs structure is a mix of 32, 64 and * 128bit fields, we index it as if it was a 32bit * array. Hence below, nr_regs is the number of entries, and * off the index in the "array". */ __u32 __user *uaddr = (__u32 __user *)(unsigned long)reg->addr; struct kvm_regs *regs = vcpu_gp_regs(vcpu); int nr_regs = sizeof(*regs) / sizeof(__u32); u32 off; /* Our ID is an index into the kvm_regs struct. */ off = core_reg_offset_from_id(reg->id); if (off >= nr_regs || (off + (KVM_REG_SIZE(reg->id) / sizeof(__u32))) >= nr_regs) return -ENOENT; if (validate_core_offset(reg)) return -EINVAL; if (copy_to_user(uaddr, ((u32 *)regs) + off, KVM_REG_SIZE(reg->id))) return -EFAULT; return 0; } static int set_core_reg(struct kvm_vcpu *vcpu, const struct kvm_one_reg *reg) { __u32 __user *uaddr = (__u32 __user *)(unsigned long)reg->addr; struct kvm_regs *regs = vcpu_gp_regs(vcpu); int nr_regs = sizeof(*regs) / sizeof(__u32); __uint128_t tmp; void *valp = &tmp; u64 off; int err = 0; /* Our ID is an index into the kvm_regs struct. */ off = core_reg_offset_from_id(reg->id); if (off >= nr_regs || (off + (KVM_REG_SIZE(reg->id) / sizeof(__u32))) >= nr_regs) return -ENOENT; if (validate_core_offset(reg)) return -EINVAL; if (KVM_REG_SIZE(reg->id) > sizeof(tmp)) return -EINVAL; if (copy_from_user(valp, uaddr, KVM_REG_SIZE(reg->id))) { err = -EFAULT; goto out; } if (off == KVM_REG_ARM_CORE_REG(regs.pstate)) { u64 mode = (*(u64 *)valp) & PSR_AA32_MODE_MASK; switch (mode) { case PSR_AA32_MODE_USR: if (!system_supports_32bit_el0()) return -EINVAL; break; case PSR_AA32_MODE_FIQ: case PSR_AA32_MODE_IRQ: case PSR_AA32_MODE_SVC: case PSR_AA32_MODE_ABT: case PSR_AA32_MODE_UND: if (!vcpu_el1_is_32bit(vcpu)) return -EINVAL; break; case PSR_MODE_EL0t: case PSR_MODE_EL1t: case PSR_MODE_EL1h: if (vcpu_el1_is_32bit(vcpu)) return -EINVAL; break; default: err = -EINVAL; goto out; } } memcpy((u32 *)regs + off, valp, KVM_REG_SIZE(reg->id)); out: return err; } int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs) { return -EINVAL; } int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs) { return -EINVAL; } static unsigned long num_core_regs(void) { return sizeof(struct kvm_regs) / sizeof(__u32); } /** * ARM64 versions of the TIMER registers, always available on arm64 */ #define NUM_TIMER_REGS 3 static bool is_timer_reg(u64 index) { switch (index) { case KVM_REG_ARM_TIMER_CTL: case KVM_REG_ARM_TIMER_CNT: case KVM_REG_ARM_TIMER_CVAL: return true; } return false; } static int copy_timer_indices(struct kvm_vcpu *vcpu, u64 __user *uindices) { if (put_user(KVM_REG_ARM_TIMER_CTL, uindices)) return -EFAULT; uindices++; if (put_user(KVM_REG_ARM_TIMER_CNT, uindices)) return -EFAULT; uindices++; if (put_user(KVM_REG_ARM_TIMER_CVAL, uindices)) return -EFAULT; return 0; } static int set_timer_reg(struct kvm_vcpu *vcpu, const struct kvm_one_reg *reg) { void __user *uaddr = (void __user *)(long)reg->addr; u64 val; int ret; ret = copy_from_user(&val, uaddr, KVM_REG_SIZE(reg->id)); if (ret != 0) return -EFAULT; return kvm_arm_timer_set_reg(vcpu, reg->id, val); } static int get_timer_reg(struct kvm_vcpu *vcpu, const struct kvm_one_reg *reg) { void __user *uaddr = (void __user *)(long)reg->addr; u64 val; val = kvm_arm_timer_get_reg(vcpu, reg->id); return copy_to_user(uaddr, &val, KVM_REG_SIZE(reg->id)) ? -EFAULT : 0; } /** * kvm_arm_num_regs - how many registers do we present via KVM_GET_ONE_REG * * This is for all registers. */ unsigned long kvm_arm_num_regs(struct kvm_vcpu *vcpu) { return num_core_regs() + kvm_arm_num_sys_reg_descs(vcpu) + kvm_arm_get_fw_num_regs(vcpu) + NUM_TIMER_REGS; } /** * kvm_arm_copy_reg_indices - get indices of all registers. * * We do core registers right here, then we append system regs. */ int kvm_arm_copy_reg_indices(struct kvm_vcpu *vcpu, u64 __user *uindices) { unsigned int i; const u64 core_reg = KVM_REG_ARM64 | KVM_REG_SIZE_U64 | KVM_REG_ARM_CORE; int ret; for (i = 0; i < sizeof(struct kvm_regs) / sizeof(__u32); i++) { if (put_user(core_reg | i, uindices)) return -EFAULT; uindices++; } ret = kvm_arm_copy_fw_reg_indices(vcpu, uindices); if (ret) return ret; uindices += kvm_arm_get_fw_num_regs(vcpu); ret = copy_timer_indices(vcpu, uindices); if (ret) return ret; uindices += NUM_TIMER_REGS; return kvm_arm_copy_sys_reg_indices(vcpu, uindices); } int kvm_arm_get_reg(struct kvm_vcpu *vcpu, const struct kvm_one_reg *reg) { /* We currently use nothing arch-specific in upper 32 bits */ if ((reg->id & ~KVM_REG_SIZE_MASK) >> 32 != KVM_REG_ARM64 >> 32) return -EINVAL; /* Register group 16 means we want a core register. */ if ((reg->id & KVM_REG_ARM_COPROC_MASK) == KVM_REG_ARM_CORE) return get_core_reg(vcpu, reg); if ((reg->id & KVM_REG_ARM_COPROC_MASK) == KVM_REG_ARM_FW) return kvm_arm_get_fw_reg(vcpu, reg); if (is_timer_reg(reg->id)) return get_timer_reg(vcpu, reg); return kvm_arm_sys_reg_get_reg(vcpu, reg); } int kvm_arm_set_reg(struct kvm_vcpu *vcpu, const struct kvm_one_reg *reg) { /* We currently use nothing arch-specific in upper 32 bits */ if ((reg->id & ~KVM_REG_SIZE_MASK) >> 32 != KVM_REG_ARM64 >> 32) return -EINVAL; /* Register group 16 means we set a core register. */ if ((reg->id & KVM_REG_ARM_COPROC_MASK) == KVM_REG_ARM_CORE) return set_core_reg(vcpu, reg); if ((reg->id & KVM_REG_ARM_COPROC_MASK) == KVM_REG_ARM_FW) return kvm_arm_set_fw_reg(vcpu, reg); if (is_timer_reg(reg->id)) return set_timer_reg(vcpu, reg); return kvm_arm_sys_reg_set_reg(vcpu, reg); } int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs) { return -EINVAL; } int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs) { return -EINVAL; } int __kvm_arm_vcpu_get_events(struct kvm_vcpu *vcpu, struct kvm_vcpu_events *events) { events->exception.serror_pending = !!(vcpu->arch.hcr_el2 & HCR_VSE); events->exception.serror_has_esr = cpus_have_const_cap(ARM64_HAS_RAS_EXTN); if (events->exception.serror_pending && events->exception.serror_has_esr) events->exception.serror_esr = vcpu_get_vsesr(vcpu); return 0; } int __kvm_arm_vcpu_set_events(struct kvm_vcpu *vcpu, struct kvm_vcpu_events *events) { bool serror_pending = events->exception.serror_pending; bool has_esr = events->exception.serror_has_esr; if (serror_pending && has_esr) { if (!cpus_have_const_cap(ARM64_HAS_RAS_EXTN)) return -EINVAL; if (!((events->exception.serror_esr) & ~ESR_ELx_ISS_MASK)) kvm_set_sei_esr(vcpu, events->exception.serror_esr); else return -EINVAL; } else if (serror_pending) { kvm_inject_vabt(vcpu); } return 0; } int __attribute_const__ kvm_target_cpu(void) { unsigned long implementor = read_cpuid_implementor(); unsigned long part_number = read_cpuid_part_number(); switch (implementor) { case ARM_CPU_IMP_ARM: switch (part_number) { case ARM_CPU_PART_AEM_V8: return KVM_ARM_TARGET_AEM_V8; case ARM_CPU_PART_FOUNDATION: return KVM_ARM_TARGET_FOUNDATION_V8; case ARM_CPU_PART_CORTEX_A53: return KVM_ARM_TARGET_CORTEX_A53; case ARM_CPU_PART_CORTEX_A57: return KVM_ARM_TARGET_CORTEX_A57; }; break; case ARM_CPU_IMP_APM: switch (part_number) { case APM_CPU_PART_POTENZA: return KVM_ARM_TARGET_XGENE_POTENZA; }; break; }; /* Return a default generic target */ return KVM_ARM_TARGET_GENERIC_V8; } int kvm_vcpu_preferred_target(struct kvm_vcpu_init *init) { int target = kvm_target_cpu(); if (target < 0) return -ENODEV; memset(init, 0, sizeof(*init)); /* * For now, we don't return any features. * In future, we might use features to return target * specific features available for the preferred * target type. */ init->target = (__u32)target; return 0; } int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu) { return -EINVAL; } int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu) { return -EINVAL; } int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu, struct kvm_translation *tr) { return -EINVAL; } #define KVM_GUESTDBG_VALID_MASK (KVM_GUESTDBG_ENABLE | \ KVM_GUESTDBG_USE_SW_BP | \ KVM_GUESTDBG_USE_HW | \ KVM_GUESTDBG_SINGLESTEP) /** * kvm_arch_vcpu_ioctl_set_guest_debug - set up guest debugging * @kvm: pointer to the KVM struct * @kvm_guest_debug: the ioctl data buffer * * This sets up and enables the VM for guest debugging. Userspace * passes in a control flag to enable different debug types and * potentially other architecture specific information in the rest of * the structure. */ int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu, struct kvm_guest_debug *dbg) { int ret = 0; trace_kvm_set_guest_debug(vcpu, dbg->control); if (dbg->control & ~KVM_GUESTDBG_VALID_MASK) { ret = -EINVAL; goto out; } if (dbg->control & KVM_GUESTDBG_ENABLE) { vcpu->guest_debug = dbg->control; /* Hardware assisted Break and Watch points */ if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW) { vcpu->arch.external_debug_state = dbg->arch; } } else { /* If not enabled clear all flags */ vcpu->guest_debug = 0; } out: return ret; } int kvm_arm_vcpu_arch_set_attr(struct kvm_vcpu *vcpu, struct kvm_device_attr *attr) { int ret; switch (attr->group) { case KVM_ARM_VCPU_PMU_V3_CTRL: ret = kvm_arm_pmu_v3_set_attr(vcpu, attr); break; case KVM_ARM_VCPU_TIMER_CTRL: ret = kvm_arm_timer_set_attr(vcpu, attr); break; default: ret = -ENXIO; break; } return ret; } int kvm_arm_vcpu_arch_get_attr(struct kvm_vcpu *vcpu, struct kvm_device_attr *attr) { int ret; switch (attr->group) { case KVM_ARM_VCPU_PMU_V3_CTRL: ret = kvm_arm_pmu_v3_get_attr(vcpu, attr); break; case KVM_ARM_VCPU_TIMER_CTRL: ret = kvm_arm_timer_get_attr(vcpu, attr); break; default: ret = -ENXIO; break; } return ret; } int kvm_arm_vcpu_arch_has_attr(struct kvm_vcpu *vcpu, struct kvm_device_attr *attr) { int ret; switch (attr->group) { case KVM_ARM_VCPU_PMU_V3_CTRL: ret = kvm_arm_pmu_v3_has_attr(vcpu, attr); break; case KVM_ARM_VCPU_TIMER_CTRL: ret = kvm_arm_timer_has_attr(vcpu, attr); break; default: ret = -ENXIO; break; } return ret; }
./CrossVul/dataset_final_sorted/CWE-20/c/good_405_0
crossvul-cpp_data_bad_4782_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M M AAA GGGG IIIII CCCC K K % % MM MM A A G I C K K % % M M M AAAAA G GGG I C KKK % % M M A A G G I C K K % % M M A A GGGG IIIII CCCC K K % % % % CCCC L IIIII % % C L I % % C L I % % C L I % % CCCC LLLLL IIIII % % % % Perform "Magick" on Images via the Command Line Interface % % % % Dragon Computing % % Anthony Thyssen % % January 2012 % % % % % % 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. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Read CLI arguments, script files, and pipelines, to provide options that % manipulate images from many different formats. % */ /* Include declarations. */ #include "MagickWand/studio.h" #include "MagickWand/MagickWand.h" #include "MagickWand/magick-wand-private.h" #include "MagickWand/wandcli.h" #include "MagickWand/wandcli-private.h" #include "MagickWand/operation.h" #include "MagickWand/magick-cli.h" #include "MagickWand/script-token.h" #include "MagickCore/utility-private.h" #include "MagickCore/exception-private.h" #include "MagickCore/version.h" /* verbose debugging, 0 - no debug lines 3 - show option details (better to use -debug Command now) 5 - image counts (after option runs) */ #define MagickCommandDebug 0 /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + P r o c e s s S c r i p t O p t i o n s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ProcessScriptOptions() reads options and processes options as they are % found in the given file, or pipeline. The filename to open and read % options is given as the 'index' argument of the argument array given. % % Other arguments following index may be read by special script options % as settings (strings), images, or as operations to be processed in various % ways. How they are treated is up to the script being processed. % % Note that a script not 'return' to the command line processing, nor can % they call (and return from) other scripts. At least not at this time. % % There are no 'ProcessOptionFlags' control flags at this time. % % The format of the ProcessScriptOptions method is: % % void ProcessScriptOptions(MagickCLI *cli_wand,const char *filename, % int argc,char **argv,int index) % % A description of each parameter follows: % % o cli_wand: the main CLI Wand to use. % % o filename: the filename of script to process % % o argc: the number of elements in the argument vector. (optional) % % o argv: A text array containing the command line arguments. (optional) % % o index: offset of next argment in argv (script arguments) (optional) % */ WandExport void ProcessScriptOptions(MagickCLI *cli_wand,const char *filename, int argc,char **argv,int index) { ScriptTokenInfo *token_info; CommandOptionFlags option_type; int count; char *option, *arg1, *arg2; assert(filename != (char *) NULL ); /* at least one argument - script name */ assert(cli_wand != (MagickCLI *) NULL); assert(cli_wand->signature == MagickWandSignature); if (cli_wand->wand.debug != MagickFalse) (void) LogMagickEvent(CommandEvent,GetMagickModule(), "Processing script \"%s\"", filename); /* open file script or stream, and set up tokenizer */ token_info = AcquireScriptTokenInfo(filename); if (token_info == (ScriptTokenInfo *) NULL) { CLIWandExceptionFile(OptionFatalError,"UnableToOpenScript",filename); return; } /* define the error location string for use in exceptions order of localtion format escapes: filename, line, column */ cli_wand->location="in \"%s\" at line %u,column %u"; if ( LocaleCompare("-", filename) == 0 ) cli_wand->filename="stdin"; else cli_wand->filename=filename; /* Process Options from Script */ option = arg1 = arg2 = (char*) NULL; DisableMSCWarning(4127) while (1) { RestoreMSCWarning { MagickBooleanType status = GetScriptToken(token_info); cli_wand->line=token_info->token_line; cli_wand->column=token_info->token_column; if (status == MagickFalse) break; /* error or end of options */ } do { /* use break to loop to exception handler and loop */ /* save option details */ CloneString(&option,token_info->token); /* get option, its argument count, and option type */ cli_wand->command = GetCommandOptionInfo(option); count=cli_wand->command->type; option_type=(CommandOptionFlags) cli_wand->command->flags; #if 0 (void) FormatLocaleFile(stderr, "Script: %u,%u: \"%s\" matched \"%s\"\n", cli_wand->line, cli_wand->line, option, cli_wand->command->mnemonic ); #endif /* handle a undefined option - image read - always for "magick-script" */ if ( option_type == UndefinedOptionFlag || (option_type & NonMagickOptionFlag) != 0 ) { #if MagickCommandDebug >= 3 (void) FormatLocaleFile(stderr, "Script %u,%u Non-Option: \"%s\"\n", cli_wand->line, cli_wand->line, option); #endif if (IsCommandOption(option) == MagickFalse) { /* non-option -- treat as a image read */ cli_wand->command=(const OptionInfo *) NULL; CLIOption(cli_wand,"-read",option); break; /* next option */ } CLIWandException(OptionFatalError,"UnrecognizedOption",option); break; /* next option */ } if ( count >= 1 ) { if (GetScriptToken(token_info) == MagickFalse) CLIWandException(OptionFatalError,"MissingArgument",option); CloneString(&arg1,token_info->token); } else CloneString(&arg1,(char *) NULL); if ( count >= 2 ) { if (GetScriptToken(token_info) == MagickFalse) CLIWandExceptionBreak(OptionFatalError,"MissingArgument",option); CloneString(&arg2,token_info->token); } else CloneString(&arg2,(char *) NULL); /* Process Options */ #if MagickCommandDebug >= 3 (void) FormatLocaleFile(stderr, "Script %u,%u Option: \"%s\" Count: %d Flags: %04x Args: \"%s\" \"%s\"\n", cli_wand->line,cli_wand->line,option,count,option_type,arg1,arg2); #endif /* Hard Deprecated Options, no code to execute - error */ if ( (option_type & DeprecateOptionFlag) != 0 ) { CLIWandException(OptionError,"DeprecatedOptionNoCode",option); break; /* next option */ } /* MagickCommandGenesis() options have no place in a magick script */ if ( (option_type & GenesisOptionFlag) != 0 ) { CLIWandException(OptionError,"InvalidUseOfOption",option); break; /* next option */ } /* handle any special 'script' options */ if ( (option_type & SpecialOptionFlag) != 0 ) { if ( LocaleCompare(option,"-exit") == 0 ) { goto loop_exit; /* break out of loop - return from script */ } if ( LocaleCompare(option,"-script") == 0 ) { /* FUTURE: call new script from this script - error for now */ CLIWandException(OptionError,"InvalidUseOfOption",option); break; /* next option */ } /* FUTURE: handle special script-argument options here */ /* handle any other special operators now */ CLIWandException(OptionError,"InvalidUseOfOption",option); break; /* next option */ } /* Process non-specific Option */ CLIOption(cli_wand, option, arg1, arg2); (void) fflush(stdout); (void) fflush(stderr); DisableMSCWarning(4127) } while (0); /* break block to next option */ RestoreMSCWarning #if MagickCommandDebug >= 5 fprintf(stderr, "Script Image Count = %ld\n", GetImageListLength(cli_wand->wand.images) ); #endif if (CLICatchException(cli_wand, MagickFalse) != MagickFalse) break; /* exit loop */ } /* Loop exit - check for some tokenization error */ loop_exit: #if MagickCommandDebug >= 3 (void) FormatLocaleFile(stderr, "Script End: %d\n", token_info->status); #endif switch( token_info->status ) { case TokenStatusOK: case TokenStatusEOF: if (cli_wand->image_list_stack != (Stack *) NULL) CLIWandException(OptionError,"UnbalancedParenthesis", "(eof)"); else if (cli_wand->image_info_stack != (Stack *) NULL) CLIWandException(OptionError,"UnbalancedBraces", "(eof)"); break; case TokenStatusBadQuotes: /* Ensure last token has a sane length for error report */ if( strlen(token_info->token) > INITAL_TOKEN_LENGTH-1 ) { token_info->token[INITAL_TOKEN_LENGTH-4] = '.'; token_info->token[INITAL_TOKEN_LENGTH-3] = '.'; token_info->token[INITAL_TOKEN_LENGTH-2] = '.'; token_info->token[INITAL_TOKEN_LENGTH-1] = '\0'; } CLIWandException(OptionFatalError,"ScriptUnbalancedQuotes", token_info->token); break; case TokenStatusMemoryFailed: CLIWandException(OptionFatalError,"ScriptTokenMemoryFailed",""); break; case TokenStatusBinary: CLIWandException(OptionFatalError,"ScriptIsBinary",""); break; } (void) fflush(stdout); (void) fflush(stderr); if (cli_wand->wand.debug != MagickFalse) (void) LogMagickEvent(CommandEvent,GetMagickModule(), "Script End \"%s\"", filename); /* Clean up */ token_info = DestroyScriptTokenInfo(token_info); CloneString(&option,(char *) NULL); CloneString(&arg1,(char *) NULL); CloneString(&arg2,(char *) NULL); return; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + P r o c e s s C o m m a n d O p t i o n s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ProcessCommandOptions() reads and processes arguments in the given % command line argument array. The 'index' defines where in the array we % should begin processing % % The 'process_flags' can be used to control and limit option processing. % For example, to only process one option, or how unknown and special options % are to be handled, and if the last argument in array is to be regarded as a % final image write argument (filename or special coder). % % The format of the ProcessCommandOptions method is: % % int ProcessCommandOptions(MagickCLI *cli_wand,int argc,char **argv, % int index) % % A description of each parameter follows: % % o cli_wand: the main CLI Wand to use. % % o argc: the number of elements in the argument vector. % % o argv: A text array containing the command line arguments. % % o process_flags: What type of arguments will be processed, ignored % or return errors. % % o index: index in the argv array to start processing from % % The function returns the index ot the next option to be processed. This % is really only releven if process_flags contains a ProcessOneOptionOnly % flag. % */ WandExport int ProcessCommandOptions(MagickCLI *cli_wand,int argc,char **argv, int index) { const char *option, *arg1, *arg2; int i, end, count; CommandOptionFlags option_type; assert(argc>=index); /* you may have no arguments left! */ assert(argv != (char **) NULL); assert(argv[index] != (char *) NULL); assert(argv[argc-1] != (char *) NULL); assert(cli_wand != (MagickCLI *) NULL); assert(cli_wand->signature == MagickWandSignature); /* define the error location string for use in exceptions order of localtion format escapes: filename, line, column */ cli_wand->location="at %s arg %u"; cli_wand->filename="CLI"; cli_wand->line=index; /* note first argument we will process */ if (cli_wand->wand.debug != MagickFalse) (void) CLILogEvent(cli_wand,CommandEvent,GetMagickModule(), "- Starting (\"%s\")", argv[index]); end = argc; if ( (cli_wand->process_flags & ProcessImplictWrite) != 0 ) end--; /* the last arument is an implied write, do not process directly */ for (i=index; i < end; i += count +1) { /* Finished processing one option? */ if ( (cli_wand->process_flags & ProcessOneOptionOnly) != 0 && i != index ) return(i); do { /* use break to loop to exception handler and loop */ option=argv[i]; cli_wand->line=i; /* note the argument for this option */ /* get option, its argument count, and option type */ cli_wand->command = GetCommandOptionInfo(argv[i]); count=cli_wand->command->type; option_type=(CommandOptionFlags) cli_wand->command->flags; #if 0 (void) FormatLocaleFile(stderr, "CLI %d: \"%s\" matched \"%s\"\n", i, argv[i], cli_wand->command->mnemonic ); #endif if ( option_type == UndefinedOptionFlag || (option_type & NonMagickOptionFlag) != 0 ) { #if MagickCommandDebug >= 3 (void) FormatLocaleFile(stderr, "CLI arg %d Non-Option: \"%s\"\n", i, option); #endif if (IsCommandOption(option) == MagickFalse) { if ( (cli_wand->process_flags & ProcessImplictRead) != 0 ) { /* non-option -- treat as a image read */ cli_wand->command=(const OptionInfo *) NULL; CLIOption(cli_wand,"-read",option); break; /* next option */ } } CLIWandException(OptionFatalError,"UnrecognizedOption",option); break; /* next option */ } if ( ((option_type & SpecialOptionFlag) != 0 ) && ((cli_wand->process_flags & ProcessScriptOption) != 0) && (LocaleCompare(option,"-script") == 0) ) { /* Call Script from CLI, with a filename as a zeroth argument. NOTE: -script may need to use the 'implict write filename' argument so it must be handled specially to prevent a 'missing argument' error. */ if ( (i+count) >= argc ) CLIWandException(OptionFatalError,"MissingArgument",option); ProcessScriptOptions(cli_wand,argv[i+1],argc,argv,i+count); return(argc); /* Script does not return to CLI -- Yet */ /* FUTURE: when it does, their may be no write arg! */ } if ((i+count) >= end ) { CLIWandException(OptionFatalError,"MissingArgument",option); if ( CLICatchException(cli_wand, MagickFalse) != MagickFalse ) return(end); break; /* next option - not that their is any! */ } arg1 = ( count >= 1 ) ? argv[i+1] : (char *) NULL; arg2 = ( count >= 2 ) ? argv[i+2] : (char *) NULL; /* Process Known Options */ #if MagickCommandDebug >= 3 (void) FormatLocaleFile(stderr, "CLI arg %u Option: \"%s\" Count: %d Flags: %04x Args: \"%s\" \"%s\"\n", i,option,count,option_type,arg1,arg2); #endif /* ignore 'genesis options' in command line args */ if ( (option_type & GenesisOptionFlag) != 0 ) break; /* next option */ /* Handle any special options for CLI (-script handled above) */ if ( (option_type & SpecialOptionFlag) != 0 ) { if ( (cli_wand->process_flags & ProcessExitOption) != 0 && LocaleCompare(option,"-exit") == 0 ) return(i+count); break; /* next option */ } /* Process standard image option */ CLIOption(cli_wand, option, arg1, arg2); DisableMSCWarning(4127) } while (0); /* break block to next option */ RestoreMSCWarning #if MagickCommandDebug >= 5 (void) FormatLocaleFile(stderr, "CLI-post Image Count = %ld\n", (long) GetImageListLength(cli_wand->wand.images) ); #endif if ( CLICatchException(cli_wand, MagickFalse) != MagickFalse ) return(i+count); } assert(i==end); if ( (cli_wand->process_flags & ProcessImplictWrite) == 0 ) return(end); /* no implied write -- just return to caller */ assert(end==argc-1); /* end should not include last argument */ /* Implicit Write of images to final CLI argument */ option=argv[i]; cli_wand->line=i; /* check that stacks are empty - or cause exception */ if (cli_wand->image_list_stack != (Stack *) NULL) CLIWandException(OptionError,"UnbalancedParenthesis", "(end of cli)"); else if (cli_wand->image_info_stack != (Stack *) NULL) CLIWandException(OptionError,"UnbalancedBraces", "(end of cli)"); if ( CLICatchException(cli_wand, MagickFalse) != MagickFalse ) return(argc); #if MagickCommandDebug >= 3 (void) FormatLocaleFile(stderr,"CLI arg %d Write File: \"%s\"\n",i,option); #endif /* Valid 'do no write' replacement option (instead of "null:") */ if (LocaleCompare(option,"-exit") == 0 ) return(argc); /* just exit, no image write */ /* If filename looks like an option, Or the common 'end of line' error of a single space. -- produce an error */ if (IsCommandOption(option) != MagickFalse || (option[0] == ' ' && option[1] == '\0') ) { CLIWandException(OptionError,"MissingOutputFilename",option); return(argc); } cli_wand->command=(const OptionInfo *) NULL; CLIOption(cli_wand,"-write",option); return(argc); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + M a g i c k I m a g e C o m m a n d % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickImageCommand() Handle special use CLI arguments and prepare a % CLI MagickCLI to process the command line or directly specified script. % % This is essentualy interface function between the MagickCore library % initialization function MagickCommandGenesis(), and the option MagickCLI % processing functions ProcessCommandOptions() or ProcessScriptOptions() % % The format of the MagickImageCommand method is: % % MagickBooleanType MagickImageCommand(ImageInfo *image_info,int argc, % char **argv,char **metadata,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the starting image_info structure % (for compatibilty with MagickCommandGenisis()) % % o argc: the number of elements in the argument vector. % % o argv: A text array containing the command line arguments. % % o metadata: any metadata (for VBS) is returned here. % (for compatibilty with MagickCommandGenisis()) % % o exception: return any errors or warnings in this structure. % */ static void MagickUsage(MagickBooleanType verbose) { const char *name; size_t len; name=GetClientName(); len=strlen(name); if (len>=7 && LocaleCompare("convert",name+len-7) == 0) { /* convert usage */ (void) FormatLocaleFile(stdout, "Usage: %s [ {option} | {image} ... ] {output_image}\n",name); (void) FormatLocaleFile(stdout, " %s -help | -version | -usage | -list {option}\n\n",name); return; } else if (len>=6 && LocaleCompare("script",name+len-6) == 0) { /* magick-script usage */ (void) FormatLocaleFile(stdout, "Usage: %s {filename} [ {script_args} ... ]\n",name); } else { /* magick usage */ (void) FormatLocaleFile(stdout, "Usage: %s [ {option} | {image} ... ] {output_image}\n",name); (void) FormatLocaleFile(stdout, " %s [ {option} | {image} ... ] -script {filename} [ {script_args} ...]\n", name); } (void) FormatLocaleFile(stdout, " %s -help | -version | -usage | -list {option}\n\n",name); if (verbose == MagickFalse) return; (void) FormatLocaleFile(stdout,"%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s\n", "All options are performed in a strict 'as you see them' order\n", "You must read-in images before you can operate on them.\n", "\n", "Magick Script files can use any of the following forms...\n", " #!/path/to/magick -script\n", "or\n", " #!/bin/sh\n", " :; exec magick -script \"$0\" \"$@\"; exit 10\n", " # Magick script from here...\n", "or\n", " #!/usr/bin/env magick-script\n", "The latter two forms do not require the path to the command hard coded.\n", "Note: \"magick-script\" needs to be linked to the \"magick\" command.\n", "\n", "For more information on usage, options, examples, and techniques\n", "see the ImageMagick website at ", MagickAuthoritativeURL); return; } /* Concatanate given file arguments to the given output argument. Used for a special -concatenate option used for specific 'delegates'. The option is not formally documented. magick -concatenate files... output This is much like the UNIX "cat" command, but for both UNIX and Windows, however the last argument provides the output filename. */ static MagickBooleanType ConcatenateImages(int argc,char **argv, ExceptionInfo *exception ) { FILE *input, *output; int c; register ssize_t i; if (ExpandFilenames(&argc,&argv) == MagickFalse) ThrowFileException(exception,ResourceLimitError,"MemoryAllocationFailed", GetExceptionMessage(errno)); output=fopen_utf8(argv[argc-1],"wb"); if (output == (FILE *) NULL) { ThrowFileException(exception,FileOpenError,"UnableToOpenFile",argv[argc-1]); return(MagickFalse); } for (i=2; i < (ssize_t) (argc-1); i++) { #if 0 fprintf(stderr, "DEBUG: Concatenate Image: \"%s\"\n", argv[i]); #endif input=fopen_utf8(argv[i],"rb"); if (input == (FILE *) NULL) { ThrowFileException(exception,FileOpenError,"UnableToOpenFile",argv[i]); continue; } for (c=fgetc(input); c != EOF; c=fgetc(input)) (void) fputc((char) c,output); (void) fclose(input); (void) remove_utf8(argv[i]); } (void) fclose(output); return(MagickTrue); } WandExport MagickBooleanType MagickImageCommand(ImageInfo *image_info,int argc, char **argv,char **metadata,ExceptionInfo *exception) { MagickCLI *cli_wand; size_t len; assert(image_info != (ImageInfo *) NULL); /* For specific OS command line requirements */ ReadCommandlLine(argc,&argv); /* Initialize special "CLI Wand" to hold images and settings (empty) */ cli_wand=AcquireMagickCLI(image_info,exception); cli_wand->location="Initializing"; cli_wand->filename=argv[0]; cli_wand->line=1; if (cli_wand->wand.debug != MagickFalse) (void) CLILogEvent(cli_wand,CommandEvent,GetMagickModule(), "\"%s\"",argv[0]); GetPathComponent(argv[0],TailPath,cli_wand->wand.name); SetClientName(cli_wand->wand.name); ConcatenateMagickString(cli_wand->wand.name,"-CLI",MagickPathExtent); len=strlen(argv[0]); /* precaution */ /* "convert" command - give a "deprecated" warning" */ if (len>=7 && LocaleCompare("convert",argv[0]+len-7) == 0) { cli_wand->process_flags = ConvertCommandOptionFlags; (void) FormatLocaleFile(stderr,"WARNING: %s\n", "The convert command is deprecated in IMv7, use \"magick\"\n"); } /* Special Case: If command name ends with "script" implied "-script" */ if (len>=6 && LocaleCompare("script",argv[0]+len-6) == 0) { if (argc >= 2 && ( (*(argv[1]) != '-') || (strlen(argv[1]) == 1) )) { GetPathComponent(argv[1],TailPath,cli_wand->wand.name); ProcessScriptOptions(cli_wand,argv[1],argc,argv,2); goto Magick_Command_Cleanup; } } /* Special Case: Version Information and Abort */ if (argc == 2) { if ((LocaleCompare("-version",argv[1]) == 0) || /* GNU standard option */ (LocaleCompare("--version",argv[1]) == 0) ) { /* just version */ CLIOption(cli_wand, "-version"); goto Magick_Command_Exit; } if ((LocaleCompare("-help",argv[1]) == 0) || /* GNU standard option */ (LocaleCompare("--help",argv[1]) == 0) ) { /* just a brief summary */ if (cli_wand->wand.debug != MagickFalse) (void) CLILogEvent(cli_wand,CommandEvent,GetMagickModule(), "- Special Option \"%s\"", argv[1]); MagickUsage(MagickFalse); goto Magick_Command_Exit; } if (LocaleCompare("-usage",argv[1]) == 0) { /* both version & usage */ if (cli_wand->wand.debug != MagickFalse) (void) CLILogEvent(cli_wand,CommandEvent,GetMagickModule(), "- Special Option \"%s\"", argv[1]); CLIOption(cli_wand, "-version" ); MagickUsage(MagickTrue); goto Magick_Command_Exit; } } /* not enough arguments -- including -help */ if (argc < 3) { (void) FormatLocaleFile(stderr, "Error: Invalid argument or not enough arguments\n\n"); MagickUsage(MagickFalse); goto Magick_Command_Exit; } /* Special "concatenate option (hidden) for delegate usage */ if (LocaleCompare("-concatenate",argv[1]) == 0) { if (cli_wand->wand.debug != MagickFalse) (void) CLILogEvent(cli_wand,CommandEvent,GetMagickModule(), "- Special Option \"%s\"", argv[1]); ConcatenateImages(argc,argv,exception); goto Magick_Command_Exit; } /* List Information and Abort */ if (argc == 3 && LocaleCompare("-list",argv[1]) == 0) { CLIOption(cli_wand, argv[1], argv[2]); goto Magick_Command_Exit; } /* ------------- */ /* The Main Call */ if (LocaleCompare("-script",argv[1]) == 0) { /* Start processing directly from script, no pre-script options Replace wand command name with script name First argument in the argv array is the script name to read. */ GetPathComponent(argv[2],TailPath,cli_wand->wand.name); ProcessScriptOptions(cli_wand,argv[2],argc,argv,3); } else { /* Normal Command Line, assumes output file as last option */ ProcessCommandOptions(cli_wand,argc,argv,1); } /* ------------- */ Magick_Command_Cleanup: cli_wand->location="Cleanup"; cli_wand->filename=argv[0]; if (cli_wand->wand.debug != MagickFalse) (void) CLILogEvent(cli_wand,CommandEvent,GetMagickModule(), "\"%s\"",argv[0]); /* recover original image_info and clean up stacks FUTURE: "-reset stacks" option */ while ((cli_wand->image_list_stack != (Stack *) NULL) && (cli_wand->image_list_stack->next != (Stack *) NULL)) CLIOption(cli_wand,")"); while ((cli_wand->image_info_stack != (Stack *) NULL) && (cli_wand->image_info_stack->next != (Stack *) NULL)) CLIOption(cli_wand,"}"); /* assert we have recovered the original structures */ assert(cli_wand->wand.image_info == image_info); assert(cli_wand->wand.exception == exception); /* Handle metadata for ImageMagickObject COM object for Windows VBS */ if (metadata != (char **) NULL) { const char *format; char *text; format="%w,%h,%m"; // Get this from image_info Option splaytree text=InterpretImageProperties(image_info,cli_wand->wand.images,format, exception); if (text == (char *) NULL) ThrowMagickException(exception,GetMagickModule(),ResourceLimitError, "MemoryAllocationFailed","`%s'", GetExceptionMessage(errno)); else { (void) ConcatenateString(&(*metadata),text); text=DestroyString(text); } } Magick_Command_Exit: cli_wand->location="Exiting"; cli_wand->filename=argv[0]; if (cli_wand->wand.debug != MagickFalse) (void) CLILogEvent(cli_wand,CommandEvent,GetMagickModule(), "\"%s\"",argv[0]); /* Destroy the special CLI Wand */ cli_wand->wand.image_info = (ImageInfo *) NULL; /* not these */ cli_wand->wand.exception = (ExceptionInfo *) NULL; cli_wand=DestroyMagickCLI(cli_wand); return(exception->severity < ErrorException ? MagickTrue : MagickFalse); }
./CrossVul/dataset_final_sorted/CWE-20/c/bad_4782_0
crossvul-cpp_data_bad_5115_0
/* * packet-pktap.c * Routines for dissecting Apple's PKTAP header * * Wireshark - Network traffic analyzer * By Gerald Combs <gerald@wireshark.org> * Copyright 2007 Gerald Combs * * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "config.h" #include <epan/packet.h> #include <epan/expert.h> #include <wsutil/pint.h> #include "packet-frame.h" #include "packet-eth.h" #include "packet-pktap.h" /* Needed for wtap_pcap_encap_to_wtap_encap(). */ #include <wiretap/pcap-encap.h> void proto_register_pktap(void); void proto_reg_handoff_pktap(void); /* * Apple's PKTAP header. */ /* * Minimum header length. * * XXX - I'm assuming the header begins with a length field so that it * can be transparently *extended*, not so that fields in the current * header can be *omitted*. */ #define MIN_PKTAP_HDR_LEN 108 /* * Record types. */ #define PKT_REC_NONE 0 /* nothing follows the header */ #define PKT_REC_PACKET 1 /* a packet follows the header */ /* Protocol */ static int proto_pktap = -1; static int hf_pktap_hdrlen = -1; static int hf_pktap_rectype = -1; static int hf_pktap_dlt = -1; static int hf_pktap_ifname = -1; static int hf_pktap_flags = -1; static int hf_pktap_pfamily = -1; static int hf_pktap_llhdrlen = -1; static int hf_pktap_lltrlrlen = -1; static int hf_pktap_pid = -1; static int hf_pktap_cmdname = -1; static int hf_pktap_svc_class = -1; static int hf_pktap_iftype = -1; static int hf_pktap_ifunit = -1; static int hf_pktap_epid = -1; static int hf_pktap_ecmdname = -1; static gint ett_pktap = -1; static expert_field ei_pktap_hdrlen_too_short = EI_INIT; static dissector_handle_t pktap_handle; /* * XXX - these are little-endian in the captures I've seen, but Apple * no longer make any big-endian machines (Macs use x86, iOS machines * use ARM and run it little-endian), so that might be by definition * or they might be host-endian. * * If a big-endian PKTAP file ever shows up, and it comes from a * big-endian machine, presumably these are host-endian, and we need * to just fetch the fields in host byte order here but byte-swap them * to host byte order in libwiretap. */ void capture_pktap(const guchar *pd, int len, packet_counts *ld) { guint32 hdrlen, rectype, dlt; hdrlen = pletoh32(pd); if (hdrlen < MIN_PKTAP_HDR_LEN || !BYTES_ARE_IN_FRAME(0, len, hdrlen)) { ld->other++; return; } rectype = pletoh32(pd+4); if (rectype != PKT_REC_PACKET) { ld->other++; return; } dlt = pletoh32(pd+4); /* XXX - We should probably combine this with capture_info.c:capture_info_packet() */ switch (dlt) { case 1: /* DLT_EN10MB */ capture_eth(pd, hdrlen, len, ld); return; default: break; } ld->other++; } static void dissect_pktap(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree) { proto_tree *pktap_tree = NULL; proto_item *ti = NULL; tvbuff_t *next_tvb; int offset = 0; guint32 pkt_len, rectype, dlt; col_set_str(pinfo->cinfo, COL_PROTOCOL, "PKTAP"); col_clear(pinfo->cinfo, COL_INFO); pkt_len = tvb_get_letohl(tvb, offset); col_add_fstr(pinfo->cinfo, COL_INFO, "PKTAP, %u byte header", pkt_len); /* Dissect the packet */ ti = proto_tree_add_item(tree, proto_pktap, tvb, offset, pkt_len, ENC_NA); pktap_tree = proto_item_add_subtree(ti, ett_pktap); proto_tree_add_item(pktap_tree, hf_pktap_hdrlen, tvb, offset, 4, ENC_LITTLE_ENDIAN); if (pkt_len < MIN_PKTAP_HDR_LEN) { proto_tree_add_expert(tree, pinfo, &ei_pktap_hdrlen_too_short, tvb, offset, 4); return; } offset += 4; proto_tree_add_item(pktap_tree, hf_pktap_rectype, tvb, offset, 4, ENC_LITTLE_ENDIAN); rectype = tvb_get_letohl(tvb, offset); offset += 4; proto_tree_add_item(pktap_tree, hf_pktap_dlt, tvb, offset, 4, ENC_LITTLE_ENDIAN); dlt = tvb_get_letohl(tvb, offset); offset += 4; proto_tree_add_item(pktap_tree, hf_pktap_ifname, tvb, offset, 24, ENC_ASCII|ENC_NA); offset += 24; proto_tree_add_item(pktap_tree, hf_pktap_flags, tvb, offset, 4, ENC_LITTLE_ENDIAN); offset += 4; proto_tree_add_item(pktap_tree, hf_pktap_pfamily, tvb, offset, 4, ENC_LITTLE_ENDIAN); offset += 4; proto_tree_add_item(pktap_tree, hf_pktap_llhdrlen, tvb, offset, 4, ENC_LITTLE_ENDIAN); offset += 4; proto_tree_add_item(pktap_tree, hf_pktap_lltrlrlen, tvb, offset, 4, ENC_LITTLE_ENDIAN); offset += 4; proto_tree_add_item(pktap_tree, hf_pktap_pid, tvb, offset, 4, ENC_LITTLE_ENDIAN); offset += 4; proto_tree_add_item(pktap_tree, hf_pktap_cmdname, tvb, offset, 20, ENC_UTF_8|ENC_NA); offset += 20; proto_tree_add_item(pktap_tree, hf_pktap_svc_class, tvb, offset, 4, ENC_LITTLE_ENDIAN); offset += 4; proto_tree_add_item(pktap_tree, hf_pktap_iftype, tvb, offset, 2, ENC_LITTLE_ENDIAN); offset += 2; proto_tree_add_item(pktap_tree, hf_pktap_ifunit, tvb, offset, 2, ENC_LITTLE_ENDIAN); offset += 2; proto_tree_add_item(pktap_tree, hf_pktap_epid, tvb, offset, 4, ENC_LITTLE_ENDIAN); offset += 4; proto_tree_add_item(pktap_tree, hf_pktap_ecmdname, tvb, offset, 20, ENC_UTF_8|ENC_NA); /*offset += 20;*/ if (rectype == PKT_REC_PACKET) { next_tvb = tvb_new_subset_remaining(tvb, pkt_len); dissector_try_uint(wtap_encap_dissector_table, wtap_pcap_encap_to_wtap_encap(dlt), next_tvb, pinfo, tree); } } void proto_register_pktap(void) { static hf_register_info hf[] = { { &hf_pktap_hdrlen, { "Header length", "pktap.hdrlen", FT_UINT32, BASE_DEC, NULL, 0x0, NULL, HFILL } }, { &hf_pktap_rectype, { "Record type", "pktap.rectype", FT_UINT32, BASE_DEC, NULL, 0x0, NULL, HFILL } }, { &hf_pktap_dlt, { "DLT", "pktap.dlt", FT_UINT32, BASE_DEC, NULL, 0x0, NULL, HFILL } }, { &hf_pktap_ifname, /* fixed length *and* null-terminated */ { "Interface name", "pktap.ifname", FT_STRINGZ, BASE_NONE, NULL, 0x0, NULL, HFILL } }, { &hf_pktap_flags, { "Flags", "pktap.flags", FT_UINT32, BASE_HEX, NULL, 0x0, NULL, HFILL } }, { &hf_pktap_pfamily, { "Protocol family", "pktap.pfamily", FT_UINT32, BASE_DEC, NULL, 0x0, NULL, HFILL } }, { &hf_pktap_llhdrlen, { "Link-layer header length", "pktap.llhdrlen", FT_UINT32, BASE_DEC, NULL, 0x0, NULL, HFILL } }, { &hf_pktap_lltrlrlen, { "Link-layer trailer length", "pktap.lltrlrlen", FT_UINT32, BASE_DEC, NULL, 0x0, NULL, HFILL } }, { &hf_pktap_pid, { "Process ID", "pktap.pid", FT_UINT32, BASE_DEC, NULL, 0x0, NULL, HFILL } }, { &hf_pktap_cmdname, /* fixed length *and* null-terminated */ { "Command name", "pktap.cmdname", FT_STRINGZ, BASE_NONE, NULL, 0x0, NULL, HFILL } }, { &hf_pktap_svc_class, { "Service class", "pktap.svc_class", FT_UINT32, BASE_DEC, NULL, 0x0, NULL, HFILL } }, { &hf_pktap_iftype, { "Interface type", "pktap.iftype", FT_UINT16, BASE_DEC, NULL, 0x0, NULL, HFILL } }, { &hf_pktap_ifunit, { "Interface unit", "pktap.ifunit", FT_UINT16, BASE_DEC, NULL, 0x0, NULL, HFILL } }, { &hf_pktap_epid, { "Effective process ID", "pktap.epid", FT_UINT32, BASE_DEC, NULL, 0x0, NULL, HFILL } }, { &hf_pktap_ecmdname, /* fixed length *and* null-terminated */ { "Effective command name", "pktap.ecmdname", FT_STRINGZ, BASE_NONE, NULL, 0x0, NULL, HFILL } }, }; static gint *ett[] = { &ett_pktap, }; static ei_register_info ei[] = { { &ei_pktap_hdrlen_too_short, { "pktap.hdrlen_too_short", PI_MALFORMED, PI_ERROR, "Header length is too short", EXPFILL }}, }; expert_module_t* expert_pktap; proto_pktap = proto_register_protocol("PKTAP packet header", "PKTAP", "pktap"); proto_register_field_array(proto_pktap, hf, array_length(hf)); proto_register_subtree_array(ett, array_length(ett)); expert_pktap = expert_register_protocol(proto_pktap); expert_register_field_array(expert_pktap, ei, array_length(ei)); pktap_handle = register_dissector("pktap", dissect_pktap, proto_pktap); } void proto_reg_handoff_pktap(void) { dissector_add_uint("wtap_encap", WTAP_ENCAP_PKTAP, pktap_handle); } /* * Editor modelines - http://www.wireshark.org/tools/modelines.html * * Local variables: * c-basic-offset: 8 * tab-width: 8 * indent-tabs-mode: t * End: * * vi: set shiftwidth=8 tabstop=8 noexpandtab: * :indentSize=8:tabSize=8:noTabs=false: */
./CrossVul/dataset_final_sorted/CWE-20/c/bad_5115_0
crossvul-cpp_data_bad_5845_5
/* * DDP: An implementation of the AppleTalk DDP protocol for * Ethernet 'ELAP'. * * Alan Cox <alan@lxorguk.ukuu.org.uk> * * With more than a little assistance from * * Wesley Craig <netatalk@umich.edu> * * Fixes: * Neil Horman : Added missing device ioctls * Michael Callahan : Made routing work * Wesley Craig : Fix probing to listen to a * passed node id. * Alan Cox : Added send/recvmsg support * Alan Cox : Moved at. to protinfo in * socket. * Alan Cox : Added firewall hooks. * Alan Cox : Supports new ARPHRD_LOOPBACK * Christer Weinigel : Routing and /proc fixes. * Bradford Johnson : LocalTalk. * Tom Dyas : Module support. * Alan Cox : Hooks for PPP (based on the * LocalTalk hook). * Alan Cox : Posix bits * Alan Cox/Mike Freeman : Possible fix to NBP problems * Bradford Johnson : IP-over-DDP (experimental) * Jay Schulist : Moved IP-over-DDP to its own * driver file. (ipddp.c & ipddp.h) * Jay Schulist : Made work as module with * AppleTalk drivers, cleaned it. * Rob Newberry : Added proxy AARP and AARP * procfs, moved probing to AARP * module. * Adrian Sun/ * Michael Zuelsdorff : fix for net.0 packets. don't * allow illegal ether/tokentalk * port assignment. we lose a * valid localtalk port as a * result. * Arnaldo C. de Melo : Cleanup, in preparation for * shared skb support 8) * Arnaldo C. de Melo : Move proc stuff to atalk_proc.c, * use seq_file * * 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/capability.h> #include <linux/module.h> #include <linux/if_arp.h> #include <linux/termios.h> /* For TIOCOUTQ/INQ */ #include <linux/compat.h> #include <linux/slab.h> #include <net/datalink.h> #include <net/psnap.h> #include <net/sock.h> #include <net/tcp_states.h> #include <net/route.h> #include <linux/atalk.h> #include <linux/highmem.h> struct datalink_proto *ddp_dl, *aarp_dl; static const struct proto_ops atalk_dgram_ops; /**************************************************************************\ * * * Handlers for the socket list. * * * \**************************************************************************/ HLIST_HEAD(atalk_sockets); DEFINE_RWLOCK(atalk_sockets_lock); static inline void __atalk_insert_socket(struct sock *sk) { sk_add_node(sk, &atalk_sockets); } static inline void atalk_remove_socket(struct sock *sk) { write_lock_bh(&atalk_sockets_lock); sk_del_node_init(sk); write_unlock_bh(&atalk_sockets_lock); } static struct sock *atalk_search_socket(struct sockaddr_at *to, struct atalk_iface *atif) { struct sock *s; read_lock_bh(&atalk_sockets_lock); sk_for_each(s, &atalk_sockets) { struct atalk_sock *at = at_sk(s); if (to->sat_port != at->src_port) continue; if (to->sat_addr.s_net == ATADDR_ANYNET && to->sat_addr.s_node == ATADDR_BCAST) goto found; if (to->sat_addr.s_net == at->src_net && (to->sat_addr.s_node == at->src_node || to->sat_addr.s_node == ATADDR_BCAST || to->sat_addr.s_node == ATADDR_ANYNODE)) goto found; /* XXXX.0 -- we got a request for this router. make sure * that the node is appropriately set. */ if (to->sat_addr.s_node == ATADDR_ANYNODE && to->sat_addr.s_net != ATADDR_ANYNET && atif->address.s_node == at->src_node) { to->sat_addr.s_node = atif->address.s_node; goto found; } } s = NULL; found: read_unlock_bh(&atalk_sockets_lock); return s; } /** * atalk_find_or_insert_socket - Try to find a socket matching ADDR * @sk: socket to insert in the list if it is not there already * @sat: address to search for * * Try to find a socket matching ADDR in the socket list, if found then return * it. If not, insert SK into the socket list. * * This entire operation must execute atomically. */ static struct sock *atalk_find_or_insert_socket(struct sock *sk, struct sockaddr_at *sat) { struct sock *s; struct atalk_sock *at; write_lock_bh(&atalk_sockets_lock); sk_for_each(s, &atalk_sockets) { at = at_sk(s); if (at->src_net == sat->sat_addr.s_net && at->src_node == sat->sat_addr.s_node && at->src_port == sat->sat_port) goto found; } s = NULL; __atalk_insert_socket(sk); /* Wheee, it's free, assign and insert. */ found: write_unlock_bh(&atalk_sockets_lock); return s; } static void atalk_destroy_timer(unsigned long data) { struct sock *sk = (struct sock *)data; if (sk_has_allocations(sk)) { sk->sk_timer.expires = jiffies + SOCK_DESTROY_TIME; add_timer(&sk->sk_timer); } else sock_put(sk); } static inline void atalk_destroy_socket(struct sock *sk) { atalk_remove_socket(sk); skb_queue_purge(&sk->sk_receive_queue); if (sk_has_allocations(sk)) { setup_timer(&sk->sk_timer, atalk_destroy_timer, (unsigned long)sk); sk->sk_timer.expires = jiffies + SOCK_DESTROY_TIME; add_timer(&sk->sk_timer); } else sock_put(sk); } /**************************************************************************\ * * * Routing tables for the AppleTalk socket layer. * * * \**************************************************************************/ /* Anti-deadlock ordering is atalk_routes_lock --> iface_lock -DaveM */ struct atalk_route *atalk_routes; DEFINE_RWLOCK(atalk_routes_lock); struct atalk_iface *atalk_interfaces; DEFINE_RWLOCK(atalk_interfaces_lock); /* For probing devices or in a routerless network */ struct atalk_route atrtr_default; /* AppleTalk interface control */ /* * Drop a device. Doesn't drop any of its routes - that is the caller's * problem. Called when we down the interface or delete the address. */ static void atif_drop_device(struct net_device *dev) { struct atalk_iface **iface = &atalk_interfaces; struct atalk_iface *tmp; write_lock_bh(&atalk_interfaces_lock); while ((tmp = *iface) != NULL) { if (tmp->dev == dev) { *iface = tmp->next; dev_put(dev); kfree(tmp); dev->atalk_ptr = NULL; } else iface = &tmp->next; } write_unlock_bh(&atalk_interfaces_lock); } static struct atalk_iface *atif_add_device(struct net_device *dev, struct atalk_addr *sa) { struct atalk_iface *iface = kzalloc(sizeof(*iface), GFP_KERNEL); if (!iface) goto out; dev_hold(dev); iface->dev = dev; dev->atalk_ptr = iface; iface->address = *sa; iface->status = 0; write_lock_bh(&atalk_interfaces_lock); iface->next = atalk_interfaces; atalk_interfaces = iface; write_unlock_bh(&atalk_interfaces_lock); out: return iface; } /* Perform phase 2 AARP probing on our tentative address */ static int atif_probe_device(struct atalk_iface *atif) { int netrange = ntohs(atif->nets.nr_lastnet) - ntohs(atif->nets.nr_firstnet) + 1; int probe_net = ntohs(atif->address.s_net); int probe_node = atif->address.s_node; int netct, nodect; /* Offset the network we start probing with */ if (probe_net == ATADDR_ANYNET) { probe_net = ntohs(atif->nets.nr_firstnet); if (netrange) probe_net += jiffies % netrange; } if (probe_node == ATADDR_ANYNODE) probe_node = jiffies & 0xFF; /* Scan the networks */ atif->status |= ATIF_PROBE; for (netct = 0; netct <= netrange; netct++) { /* Sweep the available nodes from a given start */ atif->address.s_net = htons(probe_net); for (nodect = 0; nodect < 256; nodect++) { atif->address.s_node = (nodect + probe_node) & 0xFF; if (atif->address.s_node > 0 && atif->address.s_node < 254) { /* Probe a proposed address */ aarp_probe_network(atif); if (!(atif->status & ATIF_PROBE_FAIL)) { atif->status &= ~ATIF_PROBE; return 0; } } atif->status &= ~ATIF_PROBE_FAIL; } probe_net++; if (probe_net > ntohs(atif->nets.nr_lastnet)) probe_net = ntohs(atif->nets.nr_firstnet); } atif->status &= ~ATIF_PROBE; return -EADDRINUSE; /* Network is full... */ } /* Perform AARP probing for a proxy address */ static int atif_proxy_probe_device(struct atalk_iface *atif, struct atalk_addr* proxy_addr) { int netrange = ntohs(atif->nets.nr_lastnet) - ntohs(atif->nets.nr_firstnet) + 1; /* we probe the interface's network */ int probe_net = ntohs(atif->address.s_net); int probe_node = ATADDR_ANYNODE; /* we'll take anything */ int netct, nodect; /* Offset the network we start probing with */ if (probe_net == ATADDR_ANYNET) { probe_net = ntohs(atif->nets.nr_firstnet); if (netrange) probe_net += jiffies % netrange; } if (probe_node == ATADDR_ANYNODE) probe_node = jiffies & 0xFF; /* Scan the networks */ for (netct = 0; netct <= netrange; netct++) { /* Sweep the available nodes from a given start */ proxy_addr->s_net = htons(probe_net); for (nodect = 0; nodect < 256; nodect++) { proxy_addr->s_node = (nodect + probe_node) & 0xFF; if (proxy_addr->s_node > 0 && proxy_addr->s_node < 254) { /* Tell AARP to probe a proposed address */ int ret = aarp_proxy_probe_network(atif, proxy_addr); if (ret != -EADDRINUSE) return ret; } } probe_net++; if (probe_net > ntohs(atif->nets.nr_lastnet)) probe_net = ntohs(atif->nets.nr_firstnet); } return -EADDRINUSE; /* Network is full... */ } struct atalk_addr *atalk_find_dev_addr(struct net_device *dev) { struct atalk_iface *iface = dev->atalk_ptr; return iface ? &iface->address : NULL; } static struct atalk_addr *atalk_find_primary(void) { struct atalk_iface *fiface = NULL; struct atalk_addr *retval; struct atalk_iface *iface; /* * Return a point-to-point interface only if * there is no non-ptp interface available. */ read_lock_bh(&atalk_interfaces_lock); for (iface = atalk_interfaces; iface; iface = iface->next) { if (!fiface && !(iface->dev->flags & IFF_LOOPBACK)) fiface = iface; if (!(iface->dev->flags & (IFF_LOOPBACK | IFF_POINTOPOINT))) { retval = &iface->address; goto out; } } if (fiface) retval = &fiface->address; else if (atalk_interfaces) retval = &atalk_interfaces->address; else retval = NULL; out: read_unlock_bh(&atalk_interfaces_lock); return retval; } /* * Find a match for 'any network' - ie any of our interfaces with that * node number will do just nicely. */ static struct atalk_iface *atalk_find_anynet(int node, struct net_device *dev) { struct atalk_iface *iface = dev->atalk_ptr; if (!iface || iface->status & ATIF_PROBE) goto out_err; if (node != ATADDR_BCAST && iface->address.s_node != node && node != ATADDR_ANYNODE) goto out_err; out: return iface; out_err: iface = NULL; goto out; } /* Find a match for a specific network:node pair */ static struct atalk_iface *atalk_find_interface(__be16 net, int node) { struct atalk_iface *iface; read_lock_bh(&atalk_interfaces_lock); for (iface = atalk_interfaces; iface; iface = iface->next) { if ((node == ATADDR_BCAST || node == ATADDR_ANYNODE || iface->address.s_node == node) && iface->address.s_net == net && !(iface->status & ATIF_PROBE)) break; /* XXXX.0 -- net.0 returns the iface associated with net */ if (node == ATADDR_ANYNODE && net != ATADDR_ANYNET && ntohs(iface->nets.nr_firstnet) <= ntohs(net) && ntohs(net) <= ntohs(iface->nets.nr_lastnet)) break; } read_unlock_bh(&atalk_interfaces_lock); return iface; } /* * Find a route for an AppleTalk packet. This ought to get cached in * the socket (later on...). We know about host routes and the fact * that a route must be direct to broadcast. */ static struct atalk_route *atrtr_find(struct atalk_addr *target) { /* * we must search through all routes unless we find a * host route, because some host routes might overlap * network routes */ struct atalk_route *net_route = NULL; struct atalk_route *r; read_lock_bh(&atalk_routes_lock); for (r = atalk_routes; r; r = r->next) { if (!(r->flags & RTF_UP)) continue; if (r->target.s_net == target->s_net) { if (r->flags & RTF_HOST) { /* * if this host route is for the target, * the we're done */ if (r->target.s_node == target->s_node) goto out; } else /* * this route will work if there isn't a * direct host route, so cache it */ net_route = r; } } /* * if we found a network route but not a direct host * route, then return it */ if (net_route) r = net_route; else if (atrtr_default.dev) r = &atrtr_default; else /* No route can be found */ r = NULL; out: read_unlock_bh(&atalk_routes_lock); return r; } /* * Given an AppleTalk network, find the device to use. This can be * a simple lookup. */ struct net_device *atrtr_get_dev(struct atalk_addr *sa) { struct atalk_route *atr = atrtr_find(sa); return atr ? atr->dev : NULL; } /* Set up a default router */ static void atrtr_set_default(struct net_device *dev) { atrtr_default.dev = dev; atrtr_default.flags = RTF_UP; atrtr_default.gateway.s_net = htons(0); atrtr_default.gateway.s_node = 0; } /* * Add a router. Basically make sure it looks valid and stuff the * entry in the list. While it uses netranges we always set them to one * entry to work like netatalk. */ static int atrtr_create(struct rtentry *r, struct net_device *devhint) { struct sockaddr_at *ta = (struct sockaddr_at *)&r->rt_dst; struct sockaddr_at *ga = (struct sockaddr_at *)&r->rt_gateway; struct atalk_route *rt; struct atalk_iface *iface, *riface; int retval = -EINVAL; /* * Fixme: Raise/Lower a routing change semaphore for these * operations. */ /* Validate the request */ if (ta->sat_family != AF_APPLETALK || (!devhint && ga->sat_family != AF_APPLETALK)) goto out; /* Now walk the routing table and make our decisions */ write_lock_bh(&atalk_routes_lock); for (rt = atalk_routes; rt; rt = rt->next) { if (r->rt_flags != rt->flags) continue; if (ta->sat_addr.s_net == rt->target.s_net) { if (!(rt->flags & RTF_HOST)) break; if (ta->sat_addr.s_node == rt->target.s_node) break; } } if (!devhint) { riface = NULL; read_lock_bh(&atalk_interfaces_lock); for (iface = atalk_interfaces; iface; iface = iface->next) { if (!riface && ntohs(ga->sat_addr.s_net) >= ntohs(iface->nets.nr_firstnet) && ntohs(ga->sat_addr.s_net) <= ntohs(iface->nets.nr_lastnet)) riface = iface; if (ga->sat_addr.s_net == iface->address.s_net && ga->sat_addr.s_node == iface->address.s_node) riface = iface; } read_unlock_bh(&atalk_interfaces_lock); retval = -ENETUNREACH; if (!riface) goto out_unlock; devhint = riface->dev; } if (!rt) { rt = kzalloc(sizeof(*rt), GFP_ATOMIC); retval = -ENOBUFS; if (!rt) goto out_unlock; rt->next = atalk_routes; atalk_routes = rt; } /* Fill in the routing entry */ rt->target = ta->sat_addr; dev_hold(devhint); rt->dev = devhint; rt->flags = r->rt_flags; rt->gateway = ga->sat_addr; retval = 0; out_unlock: write_unlock_bh(&atalk_routes_lock); out: return retval; } /* Delete a route. Find it and discard it */ static int atrtr_delete(struct atalk_addr * addr) { struct atalk_route **r = &atalk_routes; int retval = 0; struct atalk_route *tmp; write_lock_bh(&atalk_routes_lock); while ((tmp = *r) != NULL) { if (tmp->target.s_net == addr->s_net && (!(tmp->flags&RTF_GATEWAY) || tmp->target.s_node == addr->s_node)) { *r = tmp->next; dev_put(tmp->dev); kfree(tmp); goto out; } r = &tmp->next; } retval = -ENOENT; out: write_unlock_bh(&atalk_routes_lock); return retval; } /* * Called when a device is downed. Just throw away any routes * via it. */ static void atrtr_device_down(struct net_device *dev) { struct atalk_route **r = &atalk_routes; struct atalk_route *tmp; write_lock_bh(&atalk_routes_lock); while ((tmp = *r) != NULL) { if (tmp->dev == dev) { *r = tmp->next; dev_put(dev); kfree(tmp); } else r = &tmp->next; } write_unlock_bh(&atalk_routes_lock); if (atrtr_default.dev == dev) atrtr_set_default(NULL); } /* Actually down the interface */ static inline void atalk_dev_down(struct net_device *dev) { atrtr_device_down(dev); /* Remove all routes for the device */ aarp_device_down(dev); /* Remove AARP entries for the device */ atif_drop_device(dev); /* Remove the device */ } /* * A device event has occurred. Watch for devices going down and * delete our use of them (iface and route). */ static int ddp_device_event(struct notifier_block *this, unsigned long event, void *ptr) { struct net_device *dev = netdev_notifier_info_to_dev(ptr); if (!net_eq(dev_net(dev), &init_net)) return NOTIFY_DONE; if (event == NETDEV_DOWN) /* Discard any use of this */ atalk_dev_down(dev); return NOTIFY_DONE; } /* ioctl calls. Shouldn't even need touching */ /* Device configuration ioctl calls */ static int atif_ioctl(int cmd, void __user *arg) { static char aarp_mcast[6] = { 0x09, 0x00, 0x00, 0xFF, 0xFF, 0xFF }; struct ifreq atreq; struct atalk_netrange *nr; struct sockaddr_at *sa; struct net_device *dev; struct atalk_iface *atif; int ct; int limit; struct rtentry rtdef; int add_route; if (copy_from_user(&atreq, arg, sizeof(atreq))) return -EFAULT; dev = __dev_get_by_name(&init_net, atreq.ifr_name); if (!dev) return -ENODEV; sa = (struct sockaddr_at *)&atreq.ifr_addr; atif = atalk_find_dev(dev); switch (cmd) { case SIOCSIFADDR: if (!capable(CAP_NET_ADMIN)) return -EPERM; if (sa->sat_family != AF_APPLETALK) return -EINVAL; if (dev->type != ARPHRD_ETHER && dev->type != ARPHRD_LOOPBACK && dev->type != ARPHRD_LOCALTLK && dev->type != ARPHRD_PPP) return -EPROTONOSUPPORT; nr = (struct atalk_netrange *)&sa->sat_zero[0]; add_route = 1; /* * if this is a point-to-point iface, and we already * have an iface for this AppleTalk address, then we * should not add a route */ if ((dev->flags & IFF_POINTOPOINT) && atalk_find_interface(sa->sat_addr.s_net, sa->sat_addr.s_node)) { printk(KERN_DEBUG "AppleTalk: point-to-point " "interface added with " "existing address\n"); add_route = 0; } /* * Phase 1 is fine on LocalTalk but we don't do * EtherTalk phase 1. Anyone wanting to add it go ahead. */ if (dev->type == ARPHRD_ETHER && nr->nr_phase != 2) return -EPROTONOSUPPORT; if (sa->sat_addr.s_node == ATADDR_BCAST || sa->sat_addr.s_node == 254) return -EINVAL; if (atif) { /* Already setting address */ if (atif->status & ATIF_PROBE) return -EBUSY; atif->address.s_net = sa->sat_addr.s_net; atif->address.s_node = sa->sat_addr.s_node; atrtr_device_down(dev); /* Flush old routes */ } else { atif = atif_add_device(dev, &sa->sat_addr); if (!atif) return -ENOMEM; } atif->nets = *nr; /* * Check if the chosen address is used. If so we * error and atalkd will try another. */ if (!(dev->flags & IFF_LOOPBACK) && !(dev->flags & IFF_POINTOPOINT) && atif_probe_device(atif) < 0) { atif_drop_device(dev); return -EADDRINUSE; } /* Hey it worked - add the direct routes */ sa = (struct sockaddr_at *)&rtdef.rt_gateway; sa->sat_family = AF_APPLETALK; sa->sat_addr.s_net = atif->address.s_net; sa->sat_addr.s_node = atif->address.s_node; sa = (struct sockaddr_at *)&rtdef.rt_dst; rtdef.rt_flags = RTF_UP; sa->sat_family = AF_APPLETALK; sa->sat_addr.s_node = ATADDR_ANYNODE; if (dev->flags & IFF_LOOPBACK || dev->flags & IFF_POINTOPOINT) rtdef.rt_flags |= RTF_HOST; /* Routerless initial state */ if (nr->nr_firstnet == htons(0) && nr->nr_lastnet == htons(0xFFFE)) { sa->sat_addr.s_net = atif->address.s_net; atrtr_create(&rtdef, dev); atrtr_set_default(dev); } else { limit = ntohs(nr->nr_lastnet); if (limit - ntohs(nr->nr_firstnet) > 4096) { printk(KERN_WARNING "Too many routes/" "iface.\n"); return -EINVAL; } if (add_route) for (ct = ntohs(nr->nr_firstnet); ct <= limit; ct++) { sa->sat_addr.s_net = htons(ct); atrtr_create(&rtdef, dev); } } dev_mc_add_global(dev, aarp_mcast); return 0; case SIOCGIFADDR: if (!atif) return -EADDRNOTAVAIL; sa->sat_family = AF_APPLETALK; sa->sat_addr = atif->address; break; case SIOCGIFBRDADDR: if (!atif) return -EADDRNOTAVAIL; sa->sat_family = AF_APPLETALK; sa->sat_addr.s_net = atif->address.s_net; sa->sat_addr.s_node = ATADDR_BCAST; break; case SIOCATALKDIFADDR: case SIOCDIFADDR: if (!capable(CAP_NET_ADMIN)) return -EPERM; if (sa->sat_family != AF_APPLETALK) return -EINVAL; atalk_dev_down(dev); break; case SIOCSARP: if (!capable(CAP_NET_ADMIN)) return -EPERM; if (sa->sat_family != AF_APPLETALK) return -EINVAL; /* * for now, we only support proxy AARP on ELAP; * we should be able to do it for LocalTalk, too. */ if (dev->type != ARPHRD_ETHER) return -EPROTONOSUPPORT; /* * atif points to the current interface on this network; * we aren't concerned about its current status (at * least for now), but it has all the settings about * the network we're going to probe. Consequently, it * must exist. */ if (!atif) return -EADDRNOTAVAIL; nr = (struct atalk_netrange *)&(atif->nets); /* * Phase 1 is fine on Localtalk but we don't do * Ethertalk phase 1. Anyone wanting to add it go ahead. */ if (dev->type == ARPHRD_ETHER && nr->nr_phase != 2) return -EPROTONOSUPPORT; if (sa->sat_addr.s_node == ATADDR_BCAST || sa->sat_addr.s_node == 254) return -EINVAL; /* * Check if the chosen address is used. If so we * error and ATCP will try another. */ if (atif_proxy_probe_device(atif, &(sa->sat_addr)) < 0) return -EADDRINUSE; /* * We now have an address on the local network, and * the AARP code will defend it for us until we take it * down. We don't set up any routes right now, because * ATCP will install them manually via SIOCADDRT. */ break; case SIOCDARP: if (!capable(CAP_NET_ADMIN)) return -EPERM; if (sa->sat_family != AF_APPLETALK) return -EINVAL; if (!atif) return -EADDRNOTAVAIL; /* give to aarp module to remove proxy entry */ aarp_proxy_remove(atif->dev, &(sa->sat_addr)); return 0; } return copy_to_user(arg, &atreq, sizeof(atreq)) ? -EFAULT : 0; } /* Routing ioctl() calls */ static int atrtr_ioctl(unsigned int cmd, void __user *arg) { struct rtentry rt; if (copy_from_user(&rt, arg, sizeof(rt))) return -EFAULT; switch (cmd) { case SIOCDELRT: if (rt.rt_dst.sa_family != AF_APPLETALK) return -EINVAL; return atrtr_delete(&((struct sockaddr_at *) &rt.rt_dst)->sat_addr); case SIOCADDRT: { struct net_device *dev = NULL; if (rt.rt_dev) { char name[IFNAMSIZ]; if (copy_from_user(name, rt.rt_dev, IFNAMSIZ-1)) return -EFAULT; name[IFNAMSIZ-1] = '\0'; dev = __dev_get_by_name(&init_net, name); if (!dev) return -ENODEV; } return atrtr_create(&rt, dev); } } return -EINVAL; } /**************************************************************************\ * * * Handling for system calls applied via the various interfaces to an * * AppleTalk socket object. * * * \**************************************************************************/ /* * Checksum: This is 'optional'. It's quite likely also a good * candidate for assembler hackery 8) */ static unsigned long atalk_sum_partial(const unsigned char *data, int len, unsigned long sum) { /* This ought to be unwrapped neatly. I'll trust gcc for now */ while (len--) { sum += *data++; sum = rol16(sum, 1); } return sum; } /* Checksum skb data -- similar to skb_checksum */ static unsigned long atalk_sum_skb(const struct sk_buff *skb, int offset, int len, unsigned long sum) { int start = skb_headlen(skb); struct sk_buff *frag_iter; int i, copy; /* checksum stuff in header space */ if ( (copy = start - offset) > 0) { if (copy > len) copy = len; sum = atalk_sum_partial(skb->data + offset, copy, sum); if ( (len -= copy) == 0) return sum; offset += copy; } /* checksum stuff in frags */ for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) { int end; const skb_frag_t *frag = &skb_shinfo(skb)->frags[i]; WARN_ON(start > offset + len); end = start + skb_frag_size(frag); if ((copy = end - offset) > 0) { u8 *vaddr; if (copy > len) copy = len; vaddr = kmap_atomic(skb_frag_page(frag)); sum = atalk_sum_partial(vaddr + frag->page_offset + offset - start, copy, sum); kunmap_atomic(vaddr); if (!(len -= copy)) return sum; offset += copy; } start = end; } skb_walk_frags(skb, frag_iter) { int end; WARN_ON(start > offset + len); end = start + frag_iter->len; if ((copy = end - offset) > 0) { if (copy > len) copy = len; sum = atalk_sum_skb(frag_iter, offset - start, copy, sum); if ((len -= copy) == 0) return sum; offset += copy; } start = end; } BUG_ON(len > 0); return sum; } static __be16 atalk_checksum(const struct sk_buff *skb, int len) { unsigned long sum; /* skip header 4 bytes */ sum = atalk_sum_skb(skb, 4, len-4, 0); /* Use 0xFFFF for 0. 0 itself means none */ return sum ? htons((unsigned short)sum) : htons(0xFFFF); } static struct proto ddp_proto = { .name = "DDP", .owner = THIS_MODULE, .obj_size = sizeof(struct atalk_sock), }; /* * Create a socket. Initialise the socket, blank the addresses * set the state. */ static int atalk_create(struct net *net, struct socket *sock, int protocol, int kern) { struct sock *sk; int rc = -ESOCKTNOSUPPORT; if (!net_eq(net, &init_net)) return -EAFNOSUPPORT; /* * We permit SOCK_DGRAM and RAW is an extension. It is trivial to do * and gives you the full ELAP frame. Should be handy for CAP 8) */ if (sock->type != SOCK_RAW && sock->type != SOCK_DGRAM) goto out; rc = -ENOMEM; sk = sk_alloc(net, PF_APPLETALK, GFP_KERNEL, &ddp_proto); if (!sk) goto out; rc = 0; sock->ops = &atalk_dgram_ops; sock_init_data(sock, sk); /* Checksums on by default */ sock_set_flag(sk, SOCK_ZAPPED); out: return rc; } /* Free a socket. No work needed */ static int atalk_release(struct socket *sock) { struct sock *sk = sock->sk; if (sk) { sock_hold(sk); lock_sock(sk); sock_orphan(sk); sock->sk = NULL; atalk_destroy_socket(sk); release_sock(sk); sock_put(sk); } return 0; } /** * atalk_pick_and_bind_port - Pick a source port when one is not given * @sk: socket to insert into the tables * @sat: address to search for * * Pick a source port when one is not given. If we can find a suitable free * one, we insert the socket into the tables using it. * * This whole operation must be atomic. */ static int atalk_pick_and_bind_port(struct sock *sk, struct sockaddr_at *sat) { int retval; write_lock_bh(&atalk_sockets_lock); for (sat->sat_port = ATPORT_RESERVED; sat->sat_port < ATPORT_LAST; sat->sat_port++) { struct sock *s; sk_for_each(s, &atalk_sockets) { struct atalk_sock *at = at_sk(s); if (at->src_net == sat->sat_addr.s_net && at->src_node == sat->sat_addr.s_node && at->src_port == sat->sat_port) goto try_next_port; } /* Wheee, it's free, assign and insert. */ __atalk_insert_socket(sk); at_sk(sk)->src_port = sat->sat_port; retval = 0; goto out; try_next_port:; } retval = -EBUSY; out: write_unlock_bh(&atalk_sockets_lock); return retval; } static int atalk_autobind(struct sock *sk) { struct atalk_sock *at = at_sk(sk); struct sockaddr_at sat; struct atalk_addr *ap = atalk_find_primary(); int n = -EADDRNOTAVAIL; if (!ap || ap->s_net == htons(ATADDR_ANYNET)) goto out; at->src_net = sat.sat_addr.s_net = ap->s_net; at->src_node = sat.sat_addr.s_node = ap->s_node; n = atalk_pick_and_bind_port(sk, &sat); if (!n) sock_reset_flag(sk, SOCK_ZAPPED); out: return n; } /* Set the address 'our end' of the connection */ static int atalk_bind(struct socket *sock, struct sockaddr *uaddr, int addr_len) { struct sockaddr_at *addr = (struct sockaddr_at *)uaddr; struct sock *sk = sock->sk; struct atalk_sock *at = at_sk(sk); int err; if (!sock_flag(sk, SOCK_ZAPPED) || addr_len != sizeof(struct sockaddr_at)) return -EINVAL; if (addr->sat_family != AF_APPLETALK) return -EAFNOSUPPORT; lock_sock(sk); if (addr->sat_addr.s_net == htons(ATADDR_ANYNET)) { struct atalk_addr *ap = atalk_find_primary(); err = -EADDRNOTAVAIL; if (!ap) goto out; at->src_net = addr->sat_addr.s_net = ap->s_net; at->src_node = addr->sat_addr.s_node= ap->s_node; } else { err = -EADDRNOTAVAIL; if (!atalk_find_interface(addr->sat_addr.s_net, addr->sat_addr.s_node)) goto out; at->src_net = addr->sat_addr.s_net; at->src_node = addr->sat_addr.s_node; } if (addr->sat_port == ATADDR_ANYPORT) { err = atalk_pick_and_bind_port(sk, addr); if (err < 0) goto out; } else { at->src_port = addr->sat_port; err = -EADDRINUSE; if (atalk_find_or_insert_socket(sk, addr)) goto out; } sock_reset_flag(sk, SOCK_ZAPPED); err = 0; out: release_sock(sk); return err; } /* Set the address we talk to */ static int atalk_connect(struct socket *sock, struct sockaddr *uaddr, int addr_len, int flags) { struct sock *sk = sock->sk; struct atalk_sock *at = at_sk(sk); struct sockaddr_at *addr; int err; sk->sk_state = TCP_CLOSE; sock->state = SS_UNCONNECTED; if (addr_len != sizeof(*addr)) return -EINVAL; addr = (struct sockaddr_at *)uaddr; if (addr->sat_family != AF_APPLETALK) return -EAFNOSUPPORT; if (addr->sat_addr.s_node == ATADDR_BCAST && !sock_flag(sk, SOCK_BROADCAST)) { #if 1 pr_warn("atalk_connect: %s is broken and did not set SO_BROADCAST.\n", current->comm); #else return -EACCES; #endif } lock_sock(sk); err = -EBUSY; if (sock_flag(sk, SOCK_ZAPPED)) if (atalk_autobind(sk) < 0) goto out; err = -ENETUNREACH; if (!atrtr_get_dev(&addr->sat_addr)) goto out; at->dest_port = addr->sat_port; at->dest_net = addr->sat_addr.s_net; at->dest_node = addr->sat_addr.s_node; sock->state = SS_CONNECTED; sk->sk_state = TCP_ESTABLISHED; err = 0; out: release_sock(sk); return err; } /* * Find the name of an AppleTalk socket. Just copy the right * fields into the sockaddr. */ static int atalk_getname(struct socket *sock, struct sockaddr *uaddr, int *uaddr_len, int peer) { struct sockaddr_at sat; struct sock *sk = sock->sk; struct atalk_sock *at = at_sk(sk); int err; lock_sock(sk); err = -ENOBUFS; if (sock_flag(sk, SOCK_ZAPPED)) if (atalk_autobind(sk) < 0) goto out; *uaddr_len = sizeof(struct sockaddr_at); memset(&sat, 0, sizeof(sat)); if (peer) { err = -ENOTCONN; if (sk->sk_state != TCP_ESTABLISHED) goto out; sat.sat_addr.s_net = at->dest_net; sat.sat_addr.s_node = at->dest_node; sat.sat_port = at->dest_port; } else { sat.sat_addr.s_net = at->src_net; sat.sat_addr.s_node = at->src_node; sat.sat_port = at->src_port; } err = 0; sat.sat_family = AF_APPLETALK; memcpy(uaddr, &sat, sizeof(sat)); out: release_sock(sk); return err; } #if defined(CONFIG_IPDDP) || defined(CONFIG_IPDDP_MODULE) static __inline__ int is_ip_over_ddp(struct sk_buff *skb) { return skb->data[12] == 22; } static int handle_ip_over_ddp(struct sk_buff *skb) { struct net_device *dev = __dev_get_by_name(&init_net, "ipddp0"); struct net_device_stats *stats; /* This needs to be able to handle ipddp"N" devices */ if (!dev) { kfree_skb(skb); return NET_RX_DROP; } skb->protocol = htons(ETH_P_IP); skb_pull(skb, 13); skb->dev = dev; skb_reset_transport_header(skb); stats = netdev_priv(dev); stats->rx_packets++; stats->rx_bytes += skb->len + 13; return netif_rx(skb); /* Send the SKB up to a higher place. */ } #else /* make it easy for gcc to optimize this test out, i.e. kill the code */ #define is_ip_over_ddp(skb) 0 #define handle_ip_over_ddp(skb) 0 #endif static int atalk_route_packet(struct sk_buff *skb, struct net_device *dev, struct ddpehdr *ddp, __u16 len_hops, int origlen) { struct atalk_route *rt; struct atalk_addr ta; /* * Don't route multicast, etc., packets, or packets sent to "this * network" */ if (skb->pkt_type != PACKET_HOST || !ddp->deh_dnet) { /* * FIXME: * * Can it ever happen that a packet is from a PPP iface and * needs to be broadcast onto the default network? */ if (dev->type == ARPHRD_PPP) printk(KERN_DEBUG "AppleTalk: didn't forward broadcast " "packet received from PPP iface\n"); goto free_it; } ta.s_net = ddp->deh_dnet; ta.s_node = ddp->deh_dnode; /* Route the packet */ rt = atrtr_find(&ta); /* increment hops count */ len_hops += 1 << 10; if (!rt || !(len_hops & (15 << 10))) goto free_it; /* FIXME: use skb->cb to be able to use shared skbs */ /* * Route goes through another gateway, so set the target to the * gateway instead. */ if (rt->flags & RTF_GATEWAY) { ta.s_net = rt->gateway.s_net; ta.s_node = rt->gateway.s_node; } /* Fix up skb->len field */ skb_trim(skb, min_t(unsigned int, origlen, (rt->dev->hard_header_len + ddp_dl->header_length + (len_hops & 1023)))); /* FIXME: use skb->cb to be able to use shared skbs */ ddp->deh_len_hops = htons(len_hops); /* * Send the buffer onwards * * Now we must always be careful. If it's come from LocalTalk to * EtherTalk it might not fit * * Order matters here: If a packet has to be copied to make a new * headroom (rare hopefully) then it won't need unsharing. * * Note. ddp-> becomes invalid at the realloc. */ if (skb_headroom(skb) < 22) { /* 22 bytes - 12 ether, 2 len, 3 802.2 5 snap */ struct sk_buff *nskb = skb_realloc_headroom(skb, 32); kfree_skb(skb); skb = nskb; } else skb = skb_unshare(skb, GFP_ATOMIC); /* * If the buffer didn't vanish into the lack of space bitbucket we can * send it. */ if (skb == NULL) goto drop; if (aarp_send_ddp(rt->dev, skb, &ta, NULL) == NET_XMIT_DROP) return NET_RX_DROP; return NET_RX_SUCCESS; free_it: kfree_skb(skb); drop: return NET_RX_DROP; } /** * atalk_rcv - Receive a packet (in skb) from device dev * @skb - packet received * @dev - network device where the packet comes from * @pt - packet type * * Receive a packet (in skb) from device dev. This has come from the SNAP * decoder, and on entry skb->transport_header is the DDP header, skb->len * is the DDP header, skb->len is the DDP length. The physical headers * have been extracted. PPP should probably pass frames marked as for this * layer. [ie ARPHRD_ETHERTALK] */ static int atalk_rcv(struct sk_buff *skb, struct net_device *dev, struct packet_type *pt, struct net_device *orig_dev) { struct ddpehdr *ddp; struct sock *sock; struct atalk_iface *atif; struct sockaddr_at tosat; int origlen; __u16 len_hops; if (!net_eq(dev_net(dev), &init_net)) goto drop; /* Don't mangle buffer if shared */ if (!(skb = skb_share_check(skb, GFP_ATOMIC))) goto out; /* Size check and make sure header is contiguous */ if (!pskb_may_pull(skb, sizeof(*ddp))) goto drop; ddp = ddp_hdr(skb); len_hops = ntohs(ddp->deh_len_hops); /* Trim buffer in case of stray trailing data */ origlen = skb->len; skb_trim(skb, min_t(unsigned int, skb->len, len_hops & 1023)); /* * Size check to see if ddp->deh_len was crap * (Otherwise we'll detonate most spectacularly * in the middle of atalk_checksum() or recvmsg()). */ if (skb->len < sizeof(*ddp) || skb->len < (len_hops & 1023)) { pr_debug("AppleTalk: dropping corrupted frame (deh_len=%u, " "skb->len=%u)\n", len_hops & 1023, skb->len); goto drop; } /* * Any checksums. Note we don't do htons() on this == is assumed to be * valid for net byte orders all over the networking code... */ if (ddp->deh_sum && atalk_checksum(skb, len_hops & 1023) != ddp->deh_sum) /* Not a valid AppleTalk frame - dustbin time */ goto drop; /* Check the packet is aimed at us */ if (!ddp->deh_dnet) /* Net 0 is 'this network' */ atif = atalk_find_anynet(ddp->deh_dnode, dev); else atif = atalk_find_interface(ddp->deh_dnet, ddp->deh_dnode); if (!atif) { /* Not ours, so we route the packet via the correct * AppleTalk iface */ return atalk_route_packet(skb, dev, ddp, len_hops, origlen); } /* if IP over DDP is not selected this code will be optimized out */ if (is_ip_over_ddp(skb)) return handle_ip_over_ddp(skb); /* * Which socket - atalk_search_socket() looks for a *full match* * of the <net, node, port> tuple. */ tosat.sat_addr.s_net = ddp->deh_dnet; tosat.sat_addr.s_node = ddp->deh_dnode; tosat.sat_port = ddp->deh_dport; sock = atalk_search_socket(&tosat, atif); if (!sock) /* But not one of our sockets */ goto drop; /* Queue packet (standard) */ skb->sk = sock; if (sock_queue_rcv_skb(sock, skb) < 0) goto drop; return NET_RX_SUCCESS; drop: kfree_skb(skb); out: return NET_RX_DROP; } /* * Receive a LocalTalk frame. We make some demands on the caller here. * Caller must provide enough headroom on the packet to pull the short * header and append a long one. */ static int ltalk_rcv(struct sk_buff *skb, struct net_device *dev, struct packet_type *pt, struct net_device *orig_dev) { if (!net_eq(dev_net(dev), &init_net)) goto freeit; /* Expand any short form frames */ if (skb_mac_header(skb)[2] == 1) { struct ddpehdr *ddp; /* Find our address */ struct atalk_addr *ap = atalk_find_dev_addr(dev); if (!ap || skb->len < sizeof(__be16) || skb->len > 1023) goto freeit; /* Don't mangle buffer if shared */ if (!(skb = skb_share_check(skb, GFP_ATOMIC))) return 0; /* * The push leaves us with a ddephdr not an shdr, and * handily the port bytes in the right place preset. */ ddp = (struct ddpehdr *) skb_push(skb, sizeof(*ddp) - 4); /* Now fill in the long header */ /* * These two first. The mac overlays the new source/dest * network information so we MUST copy these before * we write the network numbers ! */ ddp->deh_dnode = skb_mac_header(skb)[0]; /* From physical header */ ddp->deh_snode = skb_mac_header(skb)[1]; /* From physical header */ ddp->deh_dnet = ap->s_net; /* Network number */ ddp->deh_snet = ap->s_net; ddp->deh_sum = 0; /* No checksum */ /* * Not sure about this bit... */ /* Non routable, so force a drop if we slip up later */ ddp->deh_len_hops = htons(skb->len + (DDP_MAXHOPS << 10)); } skb_reset_transport_header(skb); return atalk_rcv(skb, dev, pt, orig_dev); freeit: kfree_skb(skb); return 0; } static int atalk_sendmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t len) { struct sock *sk = sock->sk; struct atalk_sock *at = at_sk(sk); struct sockaddr_at *usat = (struct sockaddr_at *)msg->msg_name; int flags = msg->msg_flags; int loopback = 0; struct sockaddr_at local_satalk, gsat; struct sk_buff *skb; struct net_device *dev; struct ddpehdr *ddp; int size; struct atalk_route *rt; int err; if (flags & ~(MSG_DONTWAIT|MSG_CMSG_COMPAT)) return -EINVAL; if (len > DDP_MAXSZ) return -EMSGSIZE; lock_sock(sk); if (usat) { err = -EBUSY; if (sock_flag(sk, SOCK_ZAPPED)) if (atalk_autobind(sk) < 0) goto out; err = -EINVAL; if (msg->msg_namelen < sizeof(*usat) || usat->sat_family != AF_APPLETALK) goto out; err = -EPERM; /* netatalk didn't implement this check */ if (usat->sat_addr.s_node == ATADDR_BCAST && !sock_flag(sk, SOCK_BROADCAST)) { goto out; } } else { err = -ENOTCONN; if (sk->sk_state != TCP_ESTABLISHED) goto out; usat = &local_satalk; usat->sat_family = AF_APPLETALK; usat->sat_port = at->dest_port; usat->sat_addr.s_node = at->dest_node; usat->sat_addr.s_net = at->dest_net; } /* Build a packet */ SOCK_DEBUG(sk, "SK %p: Got address.\n", sk); /* For headers */ size = sizeof(struct ddpehdr) + len + ddp_dl->header_length; if (usat->sat_addr.s_net || usat->sat_addr.s_node == ATADDR_ANYNODE) { rt = atrtr_find(&usat->sat_addr); } else { struct atalk_addr at_hint; at_hint.s_node = 0; at_hint.s_net = at->src_net; rt = atrtr_find(&at_hint); } err = ENETUNREACH; if (!rt) goto out; dev = rt->dev; SOCK_DEBUG(sk, "SK %p: Size needed %d, device %s\n", sk, size, dev->name); size += dev->hard_header_len; release_sock(sk); skb = sock_alloc_send_skb(sk, size, (flags & MSG_DONTWAIT), &err); lock_sock(sk); if (!skb) goto out; skb->sk = sk; skb_reserve(skb, ddp_dl->header_length); skb_reserve(skb, dev->hard_header_len); skb->dev = dev; SOCK_DEBUG(sk, "SK %p: Begin build.\n", sk); ddp = (struct ddpehdr *)skb_put(skb, sizeof(struct ddpehdr)); ddp->deh_len_hops = htons(len + sizeof(*ddp)); ddp->deh_dnet = usat->sat_addr.s_net; ddp->deh_snet = at->src_net; ddp->deh_dnode = usat->sat_addr.s_node; ddp->deh_snode = at->src_node; ddp->deh_dport = usat->sat_port; ddp->deh_sport = at->src_port; SOCK_DEBUG(sk, "SK %p: Copy user data (%Zd bytes).\n", sk, len); err = memcpy_fromiovec(skb_put(skb, len), msg->msg_iov, len); if (err) { kfree_skb(skb); err = -EFAULT; goto out; } if (sk->sk_no_check == 1) ddp->deh_sum = 0; else ddp->deh_sum = atalk_checksum(skb, len + sizeof(*ddp)); /* * Loopback broadcast packets to non gateway targets (ie routes * to group we are in) */ if (ddp->deh_dnode == ATADDR_BCAST && !(rt->flags & RTF_GATEWAY) && !(dev->flags & IFF_LOOPBACK)) { struct sk_buff *skb2 = skb_copy(skb, GFP_KERNEL); if (skb2) { loopback = 1; SOCK_DEBUG(sk, "SK %p: send out(copy).\n", sk); /* * If it fails it is queued/sent above in the aarp queue */ aarp_send_ddp(dev, skb2, &usat->sat_addr, NULL); } } if (dev->flags & IFF_LOOPBACK || loopback) { SOCK_DEBUG(sk, "SK %p: Loop back.\n", sk); /* loop back */ skb_orphan(skb); if (ddp->deh_dnode == ATADDR_BCAST) { struct atalk_addr at_lo; at_lo.s_node = 0; at_lo.s_net = 0; rt = atrtr_find(&at_lo); if (!rt) { kfree_skb(skb); err = -ENETUNREACH; goto out; } dev = rt->dev; skb->dev = dev; } ddp_dl->request(ddp_dl, skb, dev->dev_addr); } else { SOCK_DEBUG(sk, "SK %p: send out.\n", sk); if (rt->flags & RTF_GATEWAY) { gsat.sat_addr = rt->gateway; usat = &gsat; } /* * If it fails it is queued/sent above in the aarp queue */ aarp_send_ddp(dev, skb, &usat->sat_addr, NULL); } SOCK_DEBUG(sk, "SK %p: Done write (%Zd).\n", sk, len); out: release_sock(sk); return err ? : len; } static int atalk_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t size, int flags) { struct sock *sk = sock->sk; struct sockaddr_at *sat = (struct sockaddr_at *)msg->msg_name; struct ddpehdr *ddp; int copied = 0; int offset = 0; int err = 0; struct sk_buff *skb; skb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT, flags & MSG_DONTWAIT, &err); lock_sock(sk); if (!skb) goto out; /* FIXME: use skb->cb to be able to use shared skbs */ ddp = ddp_hdr(skb); copied = ntohs(ddp->deh_len_hops) & 1023; if (sk->sk_type != SOCK_RAW) { offset = sizeof(*ddp); copied -= offset; } if (copied > size) { copied = size; msg->msg_flags |= MSG_TRUNC; } err = skb_copy_datagram_iovec(skb, offset, msg->msg_iov, copied); if (!err) { if (sat) { sat->sat_family = AF_APPLETALK; sat->sat_port = ddp->deh_sport; sat->sat_addr.s_node = ddp->deh_snode; sat->sat_addr.s_net = ddp->deh_snet; } msg->msg_namelen = sizeof(*sat); } skb_free_datagram(sk, skb); /* Free the datagram. */ out: release_sock(sk); return err ? : copied; } /* * AppleTalk ioctl calls. */ static int atalk_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg) { int rc = -ENOIOCTLCMD; struct sock *sk = sock->sk; void __user *argp = (void __user *)arg; switch (cmd) { /* Protocol layer */ case TIOCOUTQ: { long amount = sk->sk_sndbuf - sk_wmem_alloc_get(sk); if (amount < 0) amount = 0; rc = put_user(amount, (int __user *)argp); break; } case TIOCINQ: { /* * These two are safe on a single CPU system as only * user tasks fiddle here */ struct sk_buff *skb = skb_peek(&sk->sk_receive_queue); long amount = 0; if (skb) amount = skb->len - sizeof(struct ddpehdr); rc = put_user(amount, (int __user *)argp); break; } case SIOCGSTAMP: rc = sock_get_timestamp(sk, argp); break; case SIOCGSTAMPNS: rc = sock_get_timestampns(sk, argp); break; /* Routing */ case SIOCADDRT: case SIOCDELRT: rc = -EPERM; if (capable(CAP_NET_ADMIN)) rc = atrtr_ioctl(cmd, argp); break; /* Interface */ case SIOCGIFADDR: case SIOCSIFADDR: case SIOCGIFBRDADDR: case SIOCATALKDIFADDR: case SIOCDIFADDR: case SIOCSARP: /* proxy AARP */ case SIOCDARP: /* proxy AARP */ rtnl_lock(); rc = atif_ioctl(cmd, argp); rtnl_unlock(); break; } return rc; } #ifdef CONFIG_COMPAT static int atalk_compat_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg) { /* * SIOCATALKDIFADDR is a SIOCPROTOPRIVATE ioctl number, so we * cannot handle it in common code. The data we access if ifreq * here is compatible, so we can simply call the native * handler. */ if (cmd == SIOCATALKDIFADDR) return atalk_ioctl(sock, cmd, (unsigned long)compat_ptr(arg)); return -ENOIOCTLCMD; } #endif static const struct net_proto_family atalk_family_ops = { .family = PF_APPLETALK, .create = atalk_create, .owner = THIS_MODULE, }; static const struct proto_ops atalk_dgram_ops = { .family = PF_APPLETALK, .owner = THIS_MODULE, .release = atalk_release, .bind = atalk_bind, .connect = atalk_connect, .socketpair = sock_no_socketpair, .accept = sock_no_accept, .getname = atalk_getname, .poll = datagram_poll, .ioctl = atalk_ioctl, #ifdef CONFIG_COMPAT .compat_ioctl = atalk_compat_ioctl, #endif .listen = sock_no_listen, .shutdown = sock_no_shutdown, .setsockopt = sock_no_setsockopt, .getsockopt = sock_no_getsockopt, .sendmsg = atalk_sendmsg, .recvmsg = atalk_recvmsg, .mmap = sock_no_mmap, .sendpage = sock_no_sendpage, }; static struct notifier_block ddp_notifier = { .notifier_call = ddp_device_event, }; static struct packet_type ltalk_packet_type __read_mostly = { .type = cpu_to_be16(ETH_P_LOCALTALK), .func = ltalk_rcv, }; static struct packet_type ppptalk_packet_type __read_mostly = { .type = cpu_to_be16(ETH_P_PPPTALK), .func = atalk_rcv, }; static unsigned char ddp_snap_id[] = { 0x08, 0x00, 0x07, 0x80, 0x9B }; /* Export symbols for use by drivers when AppleTalk is a module */ EXPORT_SYMBOL(atrtr_get_dev); EXPORT_SYMBOL(atalk_find_dev_addr); static const char atalk_err_snap[] __initconst = KERN_CRIT "Unable to register DDP with SNAP.\n"; /* Called by proto.c on kernel start up */ static int __init atalk_init(void) { int rc = proto_register(&ddp_proto, 0); if (rc != 0) goto out; (void)sock_register(&atalk_family_ops); ddp_dl = register_snap_client(ddp_snap_id, atalk_rcv); if (!ddp_dl) printk(atalk_err_snap); dev_add_pack(&ltalk_packet_type); dev_add_pack(&ppptalk_packet_type); register_netdevice_notifier(&ddp_notifier); aarp_proto_init(); atalk_proc_init(); atalk_register_sysctl(); out: return rc; } module_init(atalk_init); /* * No explicit module reference count manipulation is needed in the * protocol. Socket layer sets module reference count for us * and interfaces reference counting is done * by the network device layer. * * Ergo, before the AppleTalk module can be removed, all AppleTalk * sockets be closed from user space. */ static void __exit atalk_exit(void) { #ifdef CONFIG_SYSCTL atalk_unregister_sysctl(); #endif /* CONFIG_SYSCTL */ atalk_proc_exit(); aarp_cleanup_module(); /* General aarp clean-up. */ unregister_netdevice_notifier(&ddp_notifier); dev_remove_pack(&ltalk_packet_type); dev_remove_pack(&ppptalk_packet_type); unregister_snap_client(ddp_dl); sock_unregister(PF_APPLETALK); proto_unregister(&ddp_proto); } module_exit(atalk_exit); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Alan Cox <alan@lxorguk.ukuu.org.uk>"); MODULE_DESCRIPTION("AppleTalk 0.20\n"); MODULE_ALIAS_NETPROTO(PF_APPLETALK);
./CrossVul/dataset_final_sorted/CWE-20/c/bad_5845_5
crossvul-cpp_data_good_1026_0
/* * Copyright (c) 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. * * sf-pcapng.c - pcapng-file-format-specific code from savefile.c */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <pcap/pcap-inttypes.h> #include <errno.h> #include <memory.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "pcap-int.h" #include "pcap-common.h" #ifdef HAVE_OS_PROTO_H #include "os-proto.h" #endif #include "sf-pcapng.h" /* * Block types. */ /* * Common part at the beginning of all blocks. */ struct block_header { bpf_u_int32 block_type; bpf_u_int32 total_length; }; /* * Common trailer at the end of all blocks. */ struct block_trailer { bpf_u_int32 total_length; }; /* * Common options. */ #define OPT_ENDOFOPT 0 /* end of options */ #define OPT_COMMENT 1 /* comment string */ /* * Option header. */ struct option_header { u_short option_code; u_short option_length; }; /* * Structures for the part of each block type following the common * part. */ /* * Section Header Block. */ #define BT_SHB 0x0A0D0D0A #define BT_SHB_INSANE_MAX 1024*1024*1 /* 1MB should be enough */ struct section_header_block { bpf_u_int32 byte_order_magic; u_short major_version; u_short minor_version; uint64_t section_length; /* followed by options and trailer */ }; /* * Byte-order magic value. */ #define BYTE_ORDER_MAGIC 0x1A2B3C4D /* * Current version number. If major_version isn't PCAP_NG_VERSION_MAJOR, * that means that this code can't read the file. */ #define PCAP_NG_VERSION_MAJOR 1 #define PCAP_NG_VERSION_MINOR 0 /* * Interface Description Block. */ #define BT_IDB 0x00000001 struct interface_description_block { u_short linktype; u_short reserved; bpf_u_int32 snaplen; /* followed by options and trailer */ }; /* * Options in the IDB. */ #define IF_NAME 2 /* interface name string */ #define IF_DESCRIPTION 3 /* interface description string */ #define IF_IPV4ADDR 4 /* interface's IPv4 address and netmask */ #define IF_IPV6ADDR 5 /* interface's IPv6 address and prefix length */ #define IF_MACADDR 6 /* interface's MAC address */ #define IF_EUIADDR 7 /* interface's EUI address */ #define IF_SPEED 8 /* interface's speed, in bits/s */ #define IF_TSRESOL 9 /* interface's time stamp resolution */ #define IF_TZONE 10 /* interface's time zone */ #define IF_FILTER 11 /* filter used when capturing on interface */ #define IF_OS 12 /* string OS on which capture on this interface was done */ #define IF_FCSLEN 13 /* FCS length for this interface */ #define IF_TSOFFSET 14 /* time stamp offset for this interface */ /* * Enhanced Packet Block. */ #define BT_EPB 0x00000006 struct enhanced_packet_block { bpf_u_int32 interface_id; bpf_u_int32 timestamp_high; bpf_u_int32 timestamp_low; bpf_u_int32 caplen; bpf_u_int32 len; /* followed by packet data, options, and trailer */ }; /* * Simple Packet Block. */ #define BT_SPB 0x00000003 struct simple_packet_block { bpf_u_int32 len; /* followed by packet data and trailer */ }; /* * Packet Block. */ #define BT_PB 0x00000002 struct packet_block { u_short interface_id; u_short drops_count; bpf_u_int32 timestamp_high; bpf_u_int32 timestamp_low; bpf_u_int32 caplen; bpf_u_int32 len; /* followed by packet data, options, and trailer */ }; /* * Block cursor - used when processing the contents of a block. * Contains a pointer into the data being processed and a count * of bytes remaining in the block. */ struct block_cursor { u_char *data; size_t data_remaining; bpf_u_int32 block_type; }; typedef enum { PASS_THROUGH, SCALE_UP_DEC, SCALE_DOWN_DEC, SCALE_UP_BIN, SCALE_DOWN_BIN } tstamp_scale_type_t; /* * Per-interface information. */ struct pcap_ng_if { uint64_t tsresol; /* time stamp resolution */ tstamp_scale_type_t scale_type; /* how to scale */ uint64_t scale_factor; /* time stamp scale factor for power-of-10 tsresol */ uint64_t tsoffset; /* time stamp offset */ }; /* * Per-pcap_t private data. * * max_blocksize is the maximum size of a block that we'll accept. We * reject blocks bigger than this, so we don't consume too much memory * with a truly huge block. It can change as we see IDBs with different * link-layer header types. (Currently, we don't support IDBs with * different link-layer header types, but we will support it in the * future, when we offer file-reading APIs that support it.) * * XXX - that's an issue on ILP32 platforms, where the maximum block * size of 2^31-1 would eat all but one byte of the entire address space. * It's less of an issue on ILP64/LLP64 platforms, but the actual size * of the address space may be limited by 1) the number of *significant* * address bits (currently, x86-64 only supports 48 bits of address), 2) * any limitations imposed by the operating system; 3) any limitations * imposed by the amount of available backing store for anonymous pages, * so we impose a limit regardless of the size of a pointer. */ struct pcap_ng_sf { uint64_t user_tsresol; /* time stamp resolution requested by the user */ u_int max_blocksize; /* don't grow buffer size past this */ bpf_u_int32 ifcount; /* number of interfaces seen in this capture */ bpf_u_int32 ifaces_size; /* size of array below */ struct pcap_ng_if *ifaces; /* array of interface information */ }; /* * The maximum block size we start with; we use an arbitrary value of * 16 MiB. */ #define INITIAL_MAX_BLOCKSIZE (16*1024*1024) /* * Maximum block size for a given maximum snapshot length; we define it * as the size of an EPB with a max_snaplen-sized packet and 128KB of * options. */ #define MAX_BLOCKSIZE_FOR_SNAPLEN(max_snaplen) \ (sizeof (struct block_header) + \ sizeof (struct enhanced_packet_block) + \ (max_snaplen) + 131072 + \ sizeof (struct block_trailer)) static void pcap_ng_cleanup(pcap_t *p); static int pcap_ng_next_packet(pcap_t *p, struct pcap_pkthdr *hdr, u_char **data); static int read_bytes(FILE *fp, void *buf, size_t bytes_to_read, int fail_on_eof, char *errbuf) { size_t amt_read; amt_read = fread(buf, 1, bytes_to_read, fp); if (amt_read != bytes_to_read) { if (ferror(fp)) { pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE, errno, "error reading dump file"); } else { if (amt_read == 0 && !fail_on_eof) return (0); /* EOF */ pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "truncated pcapng dump file; tried to read %" PRIsize " bytes, only got %" PRIsize, bytes_to_read, amt_read); } return (-1); } return (1); } static int read_block(FILE *fp, pcap_t *p, struct block_cursor *cursor, char *errbuf) { struct pcap_ng_sf *ps; int status; struct block_header bhdr; struct block_trailer *btrlr; u_char *bdata; size_t data_remaining; ps = p->priv; status = read_bytes(fp, &bhdr, sizeof(bhdr), 0, errbuf); if (status <= 0) return (status); /* error or EOF */ if (p->swapped) { bhdr.block_type = SWAPLONG(bhdr.block_type); bhdr.total_length = SWAPLONG(bhdr.total_length); } /* * Is this block "too small" - i.e., is it shorter than a block * header plus a block trailer? */ if (bhdr.total_length < sizeof(struct block_header) + sizeof(struct block_trailer)) { pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "block in pcapng dump file has a length of %u < %" PRIsize, bhdr.total_length, sizeof(struct block_header) + sizeof(struct block_trailer)); return (-1); } /* * Is the block total length a multiple of 4? */ if ((bhdr.total_length % 4) != 0) { /* * No. Report that as an error. */ pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "block in pcapng dump file has a length of %u that is not a multiple of 4" PRIsize, bhdr.total_length); return (-1); } /* * Is the buffer big enough? */ if (p->bufsize < bhdr.total_length) { /* * No - make it big enough, unless it's too big, in * which case we fail. */ void *bigger_buffer; if (bhdr.total_length > ps->max_blocksize) { pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "pcapng block size %u > maximum %u", bhdr.total_length, ps->max_blocksize); return (-1); } bigger_buffer = realloc(p->buffer, bhdr.total_length); if (bigger_buffer == NULL) { pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "out of memory"); return (-1); } p->buffer = bigger_buffer; } /* * Copy the stuff we've read to the buffer, and read the rest * of the block. */ memcpy(p->buffer, &bhdr, sizeof(bhdr)); bdata = (u_char *)p->buffer + sizeof(bhdr); data_remaining = bhdr.total_length - sizeof(bhdr); if (read_bytes(fp, bdata, data_remaining, 1, errbuf) == -1) return (-1); /* * Get the block size from the trailer. */ btrlr = (struct block_trailer *)(bdata + data_remaining - sizeof (struct block_trailer)); if (p->swapped) btrlr->total_length = SWAPLONG(btrlr->total_length); /* * Is the total length from the trailer the same as the total * length from the header? */ if (bhdr.total_length != btrlr->total_length) { /* * No. */ pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "block total length in header and trailer don't match"); return (-1); } /* * Initialize the cursor. */ cursor->data = bdata; cursor->data_remaining = data_remaining - sizeof(struct block_trailer); cursor->block_type = bhdr.block_type; return (1); } static void * get_from_block_data(struct block_cursor *cursor, size_t chunk_size, char *errbuf) { void *data; /* * Make sure we have the specified amount of data remaining in * the block data. */ if (cursor->data_remaining < chunk_size) { pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "block of type %u in pcapng dump file is too short", cursor->block_type); return (NULL); } /* * Return the current pointer, and skip past the chunk. */ data = cursor->data; cursor->data += chunk_size; cursor->data_remaining -= chunk_size; return (data); } static struct option_header * get_opthdr_from_block_data(pcap_t *p, struct block_cursor *cursor, char *errbuf) { struct option_header *opthdr; opthdr = get_from_block_data(cursor, sizeof(*opthdr), errbuf); if (opthdr == NULL) { /* * Option header is cut short. */ return (NULL); } /* * Byte-swap it if necessary. */ if (p->swapped) { opthdr->option_code = SWAPSHORT(opthdr->option_code); opthdr->option_length = SWAPSHORT(opthdr->option_length); } return (opthdr); } static void * get_optvalue_from_block_data(struct block_cursor *cursor, struct option_header *opthdr, char *errbuf) { size_t padded_option_len; void *optvalue; /* Pad option length to 4-byte boundary */ padded_option_len = opthdr->option_length; padded_option_len = ((padded_option_len + 3)/4)*4; optvalue = get_from_block_data(cursor, padded_option_len, errbuf); if (optvalue == NULL) { /* * Option value is cut short. */ return (NULL); } return (optvalue); } static int process_idb_options(pcap_t *p, struct block_cursor *cursor, uint64_t *tsresol, uint64_t *tsoffset, int *is_binary, char *errbuf) { struct option_header *opthdr; void *optvalue; int saw_tsresol, saw_tsoffset; uint8_t tsresol_opt; u_int i; saw_tsresol = 0; saw_tsoffset = 0; while (cursor->data_remaining != 0) { /* * Get the option header. */ opthdr = get_opthdr_from_block_data(p, cursor, errbuf); if (opthdr == NULL) { /* * Option header is cut short. */ return (-1); } /* * Get option value. */ optvalue = get_optvalue_from_block_data(cursor, opthdr, errbuf); if (optvalue == NULL) { /* * Option value is cut short. */ return (-1); } switch (opthdr->option_code) { case OPT_ENDOFOPT: if (opthdr->option_length != 0) { pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Interface Description Block has opt_endofopt option with length %u != 0", opthdr->option_length); return (-1); } goto done; case IF_TSRESOL: if (opthdr->option_length != 1) { pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Interface Description Block has if_tsresol option with length %u != 1", opthdr->option_length); return (-1); } if (saw_tsresol) { pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Interface Description Block has more than one if_tsresol option"); return (-1); } saw_tsresol = 1; memcpy(&tsresol_opt, optvalue, sizeof(tsresol_opt)); if (tsresol_opt & 0x80) { /* * Resolution is negative power of 2. */ uint8_t tsresol_shift = (tsresol_opt & 0x7F); if (tsresol_shift > 63) { /* * Resolution is too high; 2^-{res} * won't fit in a 64-bit value. */ pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Interface Description Block if_tsresol option resolution 2^-%u is too high", tsresol_shift); return (-1); } *is_binary = 1; *tsresol = ((uint64_t)1) << tsresol_shift; } else { /* * Resolution is negative power of 10. */ if (tsresol_opt > 19) { /* * Resolution is too high; 2^-{res} * won't fit in a 64-bit value (the * largest power of 10 that fits * in a 64-bit value is 10^19, as * the largest 64-bit unsigned * value is ~1.8*10^19). */ pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Interface Description Block if_tsresol option resolution 10^-%u is too high", tsresol_opt); return (-1); } *is_binary = 0; *tsresol = 1; for (i = 0; i < tsresol_opt; i++) *tsresol *= 10; } break; case IF_TSOFFSET: if (opthdr->option_length != 8) { pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Interface Description Block has if_tsoffset option with length %u != 8", opthdr->option_length); return (-1); } if (saw_tsoffset) { pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Interface Description Block has more than one if_tsoffset option"); return (-1); } saw_tsoffset = 1; memcpy(tsoffset, optvalue, sizeof(*tsoffset)); if (p->swapped) *tsoffset = SWAPLL(*tsoffset); break; default: break; } } done: return (0); } static int add_interface(pcap_t *p, struct block_cursor *cursor, char *errbuf) { struct pcap_ng_sf *ps; uint64_t tsresol; uint64_t tsoffset; int is_binary; ps = p->priv; /* * Count this interface. */ ps->ifcount++; /* * Grow the array of per-interface information as necessary. */ if (ps->ifcount > ps->ifaces_size) { /* * We need to grow the array. */ bpf_u_int32 new_ifaces_size; struct pcap_ng_if *new_ifaces; if (ps->ifaces_size == 0) { /* * It's currently empty. * * (The Clang static analyzer doesn't do enough, * err, umm, dataflow *analysis* to realize that * ps->ifaces_size == 0 if ps->ifaces == NULL, * and so complains about a possible zero argument * to realloc(), so we check for the former * condition to shut it up. * * However, it doesn't complain that one of the * multiplications below could overflow, which is * a real, albeit extremely unlikely, problem (you'd * need a pcapng file with tens of millions of * interfaces).) */ new_ifaces_size = 1; new_ifaces = malloc(sizeof (struct pcap_ng_if)); } else { /* * It's not currently empty; double its size. * (Perhaps overkill once we have a lot of interfaces.) * * Check for overflow if we double it. */ if (ps->ifaces_size * 2 < ps->ifaces_size) { /* * The maximum number of interfaces before * ps->ifaces_size overflows is the largest * possible 32-bit power of 2, as we do * size doubling. */ pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "more than %u interfaces in the file", 0x80000000U); return (0); } /* * ps->ifaces_size * 2 doesn't overflow, so it's * safe to multiply. */ new_ifaces_size = ps->ifaces_size * 2; /* * Now make sure that's not so big that it overflows * if we multiply by sizeof (struct pcap_ng_if). * * That can happen on 32-bit platforms, with a 32-bit * size_t; it shouldn't happen on 64-bit platforms, * with a 64-bit size_t, as new_ifaces_size is * 32 bits. */ if (new_ifaces_size * sizeof (struct pcap_ng_if) < new_ifaces_size) { /* * As this fails only with 32-bit size_t, * the multiplication was 32x32->32, and * the largest 32-bit value that can safely * be multiplied by sizeof (struct pcap_ng_if) * without overflow is the largest 32-bit * (unsigned) value divided by * sizeof (struct pcap_ng_if). */ pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "more than %u interfaces in the file", 0xFFFFFFFFU / ((u_int)sizeof (struct pcap_ng_if))); return (0); } new_ifaces = realloc(ps->ifaces, new_ifaces_size * sizeof (struct pcap_ng_if)); } if (new_ifaces == NULL) { /* * We ran out of memory. * Give up. */ pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "out of memory for per-interface information (%u interfaces)", ps->ifcount); return (0); } ps->ifaces_size = new_ifaces_size; ps->ifaces = new_ifaces; } /* * Set the default time stamp resolution and offset. */ tsresol = 1000000; /* microsecond resolution */ is_binary = 0; /* which is a power of 10 */ tsoffset = 0; /* absolute timestamps */ /* * Now look for various time stamp options, so we know * how to interpret the time stamps for this interface. */ if (process_idb_options(p, cursor, &tsresol, &tsoffset, &is_binary, errbuf) == -1) return (0); ps->ifaces[ps->ifcount - 1].tsresol = tsresol; ps->ifaces[ps->ifcount - 1].tsoffset = tsoffset; /* * Determine whether we're scaling up or down or not * at all for this interface. */ if (tsresol == ps->user_tsresol) { /* * The resolution is the resolution the user wants, * so we don't have to do scaling. */ ps->ifaces[ps->ifcount - 1].scale_type = PASS_THROUGH; } else if (tsresol > ps->user_tsresol) { /* * The resolution is greater than what the user wants, * so we have to scale the timestamps down. */ if (is_binary) ps->ifaces[ps->ifcount - 1].scale_type = SCALE_DOWN_BIN; else { /* * Calculate the scale factor. */ ps->ifaces[ps->ifcount - 1].scale_factor = tsresol/ps->user_tsresol; ps->ifaces[ps->ifcount - 1].scale_type = SCALE_DOWN_DEC; } } else { /* * The resolution is less than what the user wants, * so we have to scale the timestamps up. */ if (is_binary) ps->ifaces[ps->ifcount - 1].scale_type = SCALE_UP_BIN; else { /* * Calculate the scale factor. */ ps->ifaces[ps->ifcount - 1].scale_factor = ps->user_tsresol/tsresol; ps->ifaces[ps->ifcount - 1].scale_type = SCALE_UP_DEC; } } return (1); } /* * Check whether this is a pcapng savefile and, if it is, extract the * relevant information from the header. */ pcap_t * pcap_ng_check_header(const uint8_t *magic, FILE *fp, u_int precision, char *errbuf, int *err) { bpf_u_int32 magic_int; size_t amt_read; bpf_u_int32 total_length; bpf_u_int32 byte_order_magic; struct block_header *bhdrp; struct section_header_block *shbp; pcap_t *p; int swapped = 0; struct pcap_ng_sf *ps; int status; struct block_cursor cursor; struct interface_description_block *idbp; /* * Assume no read errors. */ *err = 0; /* * Check whether the first 4 bytes of the file are the block * type for a pcapng savefile. */ memcpy(&magic_int, magic, sizeof(magic_int)); if (magic_int != BT_SHB) { /* * XXX - check whether this looks like what the block * type would be after being munged by mapping between * UN*X and DOS/Windows text file format and, if it * does, look for the byte-order magic number in * the appropriate place and, if we find it, report * this as possibly being a pcapng file transferred * between UN*X and Windows in text file format? */ return (NULL); /* nope */ } /* * OK, they are. However, that's just \n\r\r\n, so it could, * conceivably, be an ordinary text file. * * It could not, however, conceivably be any other type of * capture file, so we can read the rest of the putative * Section Header Block; put the block type in the common * header, read the rest of the common header and the * fixed-length portion of the SHB, and look for the byte-order * magic value. */ amt_read = fread(&total_length, 1, sizeof(total_length), fp); if (amt_read < sizeof(total_length)) { if (ferror(fp)) { pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE, errno, "error reading dump file"); *err = 1; return (NULL); /* fail */ } /* * Possibly a weird short text file, so just say * "not pcapng". */ return (NULL); } amt_read = fread(&byte_order_magic, 1, sizeof(byte_order_magic), fp); if (amt_read < sizeof(byte_order_magic)) { if (ferror(fp)) { pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE, errno, "error reading dump file"); *err = 1; return (NULL); /* fail */ } /* * Possibly a weird short text file, so just say * "not pcapng". */ return (NULL); } if (byte_order_magic != BYTE_ORDER_MAGIC) { byte_order_magic = SWAPLONG(byte_order_magic); if (byte_order_magic != BYTE_ORDER_MAGIC) { /* * Not a pcapng file. */ return (NULL); } swapped = 1; total_length = SWAPLONG(total_length); } /* * Check the sanity of the total length. */ if (total_length < sizeof(*bhdrp) + sizeof(*shbp) + sizeof(struct block_trailer) || (total_length > BT_SHB_INSANE_MAX)) { pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Section Header Block in pcapng dump file has invalid length %" PRIsize " < _%lu_ < %lu (BT_SHB_INSANE_MAX)", sizeof(*bhdrp) + sizeof(*shbp) + sizeof(struct block_trailer), total_length, BT_SHB_INSANE_MAX); *err = 1; return (NULL); } /* * OK, this is a good pcapng file. * Allocate a pcap_t for it. */ p = pcap_open_offline_common(errbuf, sizeof (struct pcap_ng_sf)); if (p == NULL) { /* Allocation failed. */ *err = 1; return (NULL); } p->swapped = swapped; ps = p->priv; /* * What precision does the user want? */ switch (precision) { case PCAP_TSTAMP_PRECISION_MICRO: ps->user_tsresol = 1000000; break; case PCAP_TSTAMP_PRECISION_NANO: ps->user_tsresol = 1000000000; break; default: pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "unknown time stamp resolution %u", precision); free(p); *err = 1; return (NULL); } p->opt.tstamp_precision = precision; /* * Allocate a buffer into which to read blocks. We default to * the maximum of: * * the total length of the SHB for which we read the header; * * 2K, which should be more than large enough for an Enhanced * Packet Block containing a full-size Ethernet frame, and * leaving room for some options. * * If we find a bigger block, we reallocate the buffer, up to * the maximum size. We start out with a maximum size of * INITIAL_MAX_BLOCKSIZE; if we see any link-layer header types * with a maximum snapshot that results in a larger maximum * block length, we boost the maximum. */ p->bufsize = 2048; if (p->bufsize < total_length) p->bufsize = total_length; p->buffer = malloc(p->bufsize); if (p->buffer == NULL) { pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "out of memory"); free(p); *err = 1; return (NULL); } ps->max_blocksize = INITIAL_MAX_BLOCKSIZE; /* * Copy the stuff we've read to the buffer, and read the rest * of the SHB. */ bhdrp = (struct block_header *)p->buffer; shbp = (struct section_header_block *)((u_char *)p->buffer + sizeof(struct block_header)); bhdrp->block_type = magic_int; bhdrp->total_length = total_length; shbp->byte_order_magic = byte_order_magic; if (read_bytes(fp, (u_char *)p->buffer + (sizeof(magic_int) + sizeof(total_length) + sizeof(byte_order_magic)), total_length - (sizeof(magic_int) + sizeof(total_length) + sizeof(byte_order_magic)), 1, errbuf) == -1) goto fail; if (p->swapped) { /* * Byte-swap the fields we've read. */ shbp->major_version = SWAPSHORT(shbp->major_version); shbp->minor_version = SWAPSHORT(shbp->minor_version); /* * XXX - we don't care about the section length. */ } /* currently only SHB version 1.0 is supported */ if (! (shbp->major_version == PCAP_NG_VERSION_MAJOR && shbp->minor_version == PCAP_NG_VERSION_MINOR)) { pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "unsupported pcapng savefile version %u.%u", shbp->major_version, shbp->minor_version); goto fail; } p->version_major = shbp->major_version; p->version_minor = shbp->minor_version; /* * Save the time stamp resolution the user requested. */ p->opt.tstamp_precision = precision; /* * Now start looking for an Interface Description Block. */ for (;;) { /* * Read the next block. */ status = read_block(fp, p, &cursor, errbuf); if (status == 0) { /* EOF - no IDB in this file */ pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "the capture file has no Interface Description Blocks"); goto fail; } if (status == -1) goto fail; /* error */ switch (cursor.block_type) { case BT_IDB: /* * Get a pointer to the fixed-length portion of the * IDB. */ idbp = get_from_block_data(&cursor, sizeof(*idbp), errbuf); if (idbp == NULL) goto fail; /* error */ /* * Byte-swap it if necessary. */ if (p->swapped) { idbp->linktype = SWAPSHORT(idbp->linktype); idbp->snaplen = SWAPLONG(idbp->snaplen); } /* * Try to add this interface. */ if (!add_interface(p, &cursor, errbuf)) goto fail; goto done; case BT_EPB: case BT_SPB: case BT_PB: /* * Saw a packet before we saw any IDBs. That's * not valid, as we don't know what link-layer * encapsulation the packet has. */ pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "the capture file has a packet block before any Interface Description Blocks"); goto fail; default: /* * Just ignore it. */ break; } } done: p->tzoff = 0; /* XXX - not used in pcap */ p->linktype = linktype_to_dlt(idbp->linktype); p->snapshot = pcap_adjust_snapshot(p->linktype, idbp->snaplen); p->linktype_ext = 0; /* * If the maximum block size for a packet with the maximum * snapshot length for this DLT_ is bigger than the current * maximum block size, increase the maximum. */ if (MAX_BLOCKSIZE_FOR_SNAPLEN(max_snaplen_for_dlt(p->linktype)) > ps->max_blocksize) ps->max_blocksize = MAX_BLOCKSIZE_FOR_SNAPLEN(max_snaplen_for_dlt(p->linktype)); p->next_packet_op = pcap_ng_next_packet; p->cleanup_op = pcap_ng_cleanup; return (p); fail: free(ps->ifaces); free(p->buffer); free(p); *err = 1; return (NULL); } static void pcap_ng_cleanup(pcap_t *p) { struct pcap_ng_sf *ps = p->priv; free(ps->ifaces); sf_cleanup(p); } /* * Read and return the next packet from the savefile. Return the header * in hdr and a pointer to the contents in data. Return 0 on success, 1 * if there were no more packets, and -1 on an error. */ static int pcap_ng_next_packet(pcap_t *p, struct pcap_pkthdr *hdr, u_char **data) { struct pcap_ng_sf *ps = p->priv; struct block_cursor cursor; int status; struct enhanced_packet_block *epbp; struct simple_packet_block *spbp; struct packet_block *pbp; bpf_u_int32 interface_id = 0xFFFFFFFF; struct interface_description_block *idbp; struct section_header_block *shbp; FILE *fp = p->rfile; uint64_t t, sec, frac; /* * Look for an Enhanced Packet Block, a Simple Packet Block, * or a Packet Block. */ for (;;) { /* * Read the block type and length; those are common * to all blocks. */ status = read_block(fp, p, &cursor, p->errbuf); if (status == 0) return (1); /* EOF */ if (status == -1) return (-1); /* error */ switch (cursor.block_type) { case BT_EPB: /* * Get a pointer to the fixed-length portion of the * EPB. */ epbp = get_from_block_data(&cursor, sizeof(*epbp), p->errbuf); if (epbp == NULL) return (-1); /* error */ /* * Byte-swap it if necessary. */ if (p->swapped) { /* these were written in opposite byte order */ interface_id = SWAPLONG(epbp->interface_id); hdr->caplen = SWAPLONG(epbp->caplen); hdr->len = SWAPLONG(epbp->len); t = ((uint64_t)SWAPLONG(epbp->timestamp_high)) << 32 | SWAPLONG(epbp->timestamp_low); } else { interface_id = epbp->interface_id; hdr->caplen = epbp->caplen; hdr->len = epbp->len; t = ((uint64_t)epbp->timestamp_high) << 32 | epbp->timestamp_low; } goto found; case BT_SPB: /* * Get a pointer to the fixed-length portion of the * SPB. */ spbp = get_from_block_data(&cursor, sizeof(*spbp), p->errbuf); if (spbp == NULL) return (-1); /* error */ /* * SPB packets are assumed to have arrived on * the first interface. */ interface_id = 0; /* * Byte-swap it if necessary. */ if (p->swapped) { /* these were written in opposite byte order */ hdr->len = SWAPLONG(spbp->len); } else hdr->len = spbp->len; /* * The SPB doesn't give the captured length; * it's the minimum of the snapshot length * and the packet length. */ hdr->caplen = hdr->len; if (hdr->caplen > (bpf_u_int32)p->snapshot) hdr->caplen = p->snapshot; t = 0; /* no time stamps */ goto found; case BT_PB: /* * Get a pointer to the fixed-length portion of the * PB. */ pbp = get_from_block_data(&cursor, sizeof(*pbp), p->errbuf); if (pbp == NULL) return (-1); /* error */ /* * Byte-swap it if necessary. */ if (p->swapped) { /* these were written in opposite byte order */ interface_id = SWAPSHORT(pbp->interface_id); hdr->caplen = SWAPLONG(pbp->caplen); hdr->len = SWAPLONG(pbp->len); t = ((uint64_t)SWAPLONG(pbp->timestamp_high)) << 32 | SWAPLONG(pbp->timestamp_low); } else { interface_id = pbp->interface_id; hdr->caplen = pbp->caplen; hdr->len = pbp->len; t = ((uint64_t)pbp->timestamp_high) << 32 | pbp->timestamp_low; } goto found; case BT_IDB: /* * Interface Description Block. Get a pointer * to its fixed-length portion. */ idbp = get_from_block_data(&cursor, sizeof(*idbp), p->errbuf); if (idbp == NULL) return (-1); /* error */ /* * Byte-swap it if necessary. */ if (p->swapped) { idbp->linktype = SWAPSHORT(idbp->linktype); idbp->snaplen = SWAPLONG(idbp->snaplen); } /* * If the link-layer type or snapshot length * differ from the ones for the first IDB we * saw, quit. * * XXX - just discard packets from those * interfaces? */ if (p->linktype != idbp->linktype) { pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "an interface has a type %u different from the type of the first interface", idbp->linktype); return (-1); } /* * Check against the *adjusted* value of this IDB's * snapshot length. */ if ((bpf_u_int32)p->snapshot != pcap_adjust_snapshot(p->linktype, idbp->snaplen)) { pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "an interface has a snapshot length %u different from the type of the first interface", idbp->snaplen); return (-1); } /* * Try to add this interface. */ if (!add_interface(p, &cursor, p->errbuf)) return (-1); break; case BT_SHB: /* * Section Header Block. Get a pointer * to its fixed-length portion. */ shbp = get_from_block_data(&cursor, sizeof(*shbp), p->errbuf); if (shbp == NULL) return (-1); /* error */ /* * Assume the byte order of this section is * the same as that of the previous section. * We'll check for that later. */ if (p->swapped) { shbp->byte_order_magic = SWAPLONG(shbp->byte_order_magic); shbp->major_version = SWAPSHORT(shbp->major_version); } /* * Make sure the byte order doesn't change; * pcap_is_swapped() shouldn't change its * return value in the middle of reading a capture. */ switch (shbp->byte_order_magic) { case BYTE_ORDER_MAGIC: /* * OK. */ break; case SWAPLONG(BYTE_ORDER_MAGIC): /* * Byte order changes. */ pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "the file has sections with different byte orders"); return (-1); default: /* * Not a valid SHB. */ pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "the file has a section with a bad byte order magic field"); return (-1); } /* * Make sure the major version is the version * we handle. */ if (shbp->major_version != PCAP_NG_VERSION_MAJOR) { pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "unknown pcapng savefile major version number %u", shbp->major_version); return (-1); } /* * Reset the interface count; this section should * have its own set of IDBs. If any of them * don't have the same interface type, snapshot * length, or resolution as the first interface * we saw, we'll fail. (And if we don't see * any IDBs, we'll fail when we see a packet * block.) */ ps->ifcount = 0; break; default: /* * Not a packet block, IDB, or SHB; ignore it. */ break; } } found: /* * Is the interface ID an interface we know? */ if (interface_id >= ps->ifcount) { /* * Yes. Fail. */ pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "a packet arrived on interface %u, but there's no Interface Description Block for that interface", interface_id); return (-1); } if (hdr->caplen > (bpf_u_int32)p->snapshot) { pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "invalid packet capture length %u, bigger than " "snaplen of %d", hdr->caplen, p->snapshot); return (-1); } /* * Convert the time stamp to seconds and fractions of a second, * with the fractions being in units of the file-supplied resolution. */ sec = t / ps->ifaces[interface_id].tsresol + ps->ifaces[interface_id].tsoffset; frac = t % ps->ifaces[interface_id].tsresol; /* * Convert the fractions from units of the file-supplied resolution * to units of the user-requested resolution. */ switch (ps->ifaces[interface_id].scale_type) { case PASS_THROUGH: /* * The interface resolution is what the user wants, * so we're done. */ break; case SCALE_UP_DEC: /* * The interface resolution is less than what the user * wants; scale the fractional part up to the units of * the resolution the user requested by multiplying by * the quotient of the user-requested resolution and the * file-supplied resolution. * * Those resolutions are both powers of 10, and the user- * requested resolution is greater than the file-supplied * resolution, so the quotient in question is an integer. * We've calculated that quotient already, so we just * multiply by it. */ frac *= ps->ifaces[interface_id].scale_factor; break; case SCALE_UP_BIN: /* * The interface resolution is less than what the user * wants; scale the fractional part up to the units of * the resolution the user requested by multiplying by * the quotient of the user-requested resolution and the * file-supplied resolution. * * The file-supplied resolution is a power of 2, so the * quotient is not an integer, so, in order to do this * entirely with integer arithmetic, we multiply by the * user-requested resolution and divide by the file- * supplied resolution. * * XXX - Is there something clever we could do here, * given that we know that the file-supplied resolution * is a power of 2? Doing a multiplication followed by * a division runs the risk of overflowing, and involves * two non-simple arithmetic operations. */ frac *= ps->user_tsresol; frac /= ps->ifaces[interface_id].tsresol; break; case SCALE_DOWN_DEC: /* * The interface resolution is greater than what the user * wants; scale the fractional part up to the units of * the resolution the user requested by multiplying by * the quotient of the user-requested resolution and the * file-supplied resolution. * * Those resolutions are both powers of 10, and the user- * requested resolution is less than the file-supplied * resolution, so the quotient in question isn't an * integer, but its reciprocal is, and we can just divide * by the reciprocal of the quotient. We've calculated * the reciprocal of that quotient already, so we must * divide by it. */ frac /= ps->ifaces[interface_id].scale_factor; break; case SCALE_DOWN_BIN: /* * The interface resolution is greater than what the user * wants; convert the fractional part to units of the * resolution the user requested by multiplying by the * quotient of the user-requested resolution and the * file-supplied resolution. We do that by multiplying * by the user-requested resolution and dividing by the * file-supplied resolution, as the quotient might not * fit in an integer. * * The file-supplied resolution is a power of 2, so the * quotient is not an integer, and neither is its * reciprocal, so, in order to do this entirely with * integer arithmetic, we multiply by the user-requested * resolution and divide by the file-supplied resolution. * * XXX - Is there something clever we could do here, * given that we know that the file-supplied resolution * is a power of 2? Doing a multiplication followed by * a division runs the risk of overflowing, and involves * two non-simple arithmetic operations. */ frac *= ps->user_tsresol; frac /= ps->ifaces[interface_id].tsresol; break; } #ifdef _WIN32 /* * tv_sec and tv_used in the Windows struct timeval are both * longs. */ hdr->ts.tv_sec = (long)sec; hdr->ts.tv_usec = (long)frac; #else /* * tv_sec in the UN*X struct timeval is a time_t; tv_usec is * suseconds_t in UN*Xes that work the way the current Single * UNIX Standard specify - but not all older UN*Xes necessarily * support that type, so just cast to int. */ hdr->ts.tv_sec = (time_t)sec; hdr->ts.tv_usec = (int)frac; #endif /* * Get a pointer to the packet data. */ *data = get_from_block_data(&cursor, hdr->caplen, p->errbuf); if (*data == NULL) return (-1); if (p->swapped) swap_pseudo_headers(p->linktype, hdr, *data); return (0); }
./CrossVul/dataset_final_sorted/CWE-20/c/good_1026_0
crossvul-cpp_data_good_5411_0
/* $Id$ */ #include <stdio.h> #include <math.h> #include <string.h> #include <stdlib.h> #include <stdarg.h> #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "gd_intern.h" /* 2.03: don't include zlib here or we can't build without PNG */ #include "gd.h" #include "gdhelpers.h" #include "gd_color.h" #include "gd_errors.h" /* 2.0.12: this now checks the clipping rectangle */ #define gdImageBoundsSafeMacro(im, x, y) (!((((y) < (im)->cy1) || ((y) > (im)->cy2)) || (((x) < (im)->cx1) || ((x) > (im)->cx2)))) #ifdef _OSD_POSIX /* BS2000 uses the EBCDIC char set instead of ASCII */ #define CHARSET_EBCDIC #define __attribute__(any) /*nothing */ #endif /*_OSD_POSIX*/ #ifndef CHARSET_EBCDIC #define ASC(ch) ch #else /*CHARSET_EBCDIC */ #define ASC(ch) gd_toascii[(unsigned char)ch] static const unsigned char gd_toascii[256] = { /*00 */ 0x00, 0x01, 0x02, 0x03, 0x85, 0x09, 0x86, 0x7f, 0x87, 0x8d, 0x8e, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, /*................ */ /*10 */ 0x10, 0x11, 0x12, 0x13, 0x8f, 0x0a, 0x08, 0x97, 0x18, 0x19, 0x9c, 0x9d, 0x1c, 0x1d, 0x1e, 0x1f, /*................ */ /*20 */ 0x80, 0x81, 0x82, 0x83, 0x84, 0x92, 0x17, 0x1b, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x05, 0x06, 0x07, /*................ */ /*30 */ 0x90, 0x91, 0x16, 0x93, 0x94, 0x95, 0x96, 0x04, 0x98, 0x99, 0x9a, 0x9b, 0x14, 0x15, 0x9e, 0x1a, /*................ */ /*40 */ 0x20, 0xa0, 0xe2, 0xe4, 0xe0, 0xe1, 0xe3, 0xe5, 0xe7, 0xf1, 0x60, 0x2e, 0x3c, 0x28, 0x2b, 0x7c, /* .........`.<(+| */ /*50 */ 0x26, 0xe9, 0xea, 0xeb, 0xe8, 0xed, 0xee, 0xef, 0xec, 0xdf, 0x21, 0x24, 0x2a, 0x29, 0x3b, 0x9f, /*&.........!$*);. */ /*60 */ 0x2d, 0x2f, 0xc2, 0xc4, 0xc0, 0xc1, 0xc3, 0xc5, 0xc7, 0xd1, 0x5e, 0x2c, 0x25, 0x5f, 0x3e, 0x3f, /*-/........^,%_>?*/ /*70 */ 0xf8, 0xc9, 0xca, 0xcb, 0xc8, 0xcd, 0xce, 0xcf, 0xcc, 0xa8, 0x3a, 0x23, 0x40, 0x27, 0x3d, 0x22, /*..........:#@'=" */ /*80 */ 0xd8, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0xab, 0xbb, 0xf0, 0xfd, 0xfe, 0xb1, /*.abcdefghi...... */ /*90 */ 0xb0, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0xaa, 0xba, 0xe6, 0xb8, 0xc6, 0xa4, /*.jklmnopqr...... */ /*a0 */ 0xb5, 0xaf, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0xa1, 0xbf, 0xd0, 0xdd, 0xde, 0xae, /*..stuvwxyz...... */ /*b0 */ 0xa2, 0xa3, 0xa5, 0xb7, 0xa9, 0xa7, 0xb6, 0xbc, 0xbd, 0xbe, 0xac, 0x5b, 0x5c, 0x5d, 0xb4, 0xd7, /*...........[\].. */ /*c0 */ 0xf9, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0xad, 0xf4, 0xf6, 0xf2, 0xf3, 0xf5, /*.ABCDEFGHI...... */ /*d0 */ 0xa6, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0xb9, 0xfb, 0xfc, 0xdb, 0xfa, 0xff, /*.JKLMNOPQR...... */ /*e0 */ 0xd9, 0xf7, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0xb2, 0xd4, 0xd6, 0xd2, 0xd3, 0xd5, /*..STUVWXYZ...... */ /*f0 */ 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0xb3, 0x7b, 0xdc, 0x7d, 0xda, 0x7e /*0123456789.{.}.~ */ }; #endif /*CHARSET_EBCDIC */ extern const int gdCosT[]; extern const int gdSinT[]; /** * Group: Error Handling */ void gd_stderr_error(int priority, const char *format, va_list args) { switch (priority) { case GD_ERROR: fputs("GD Error: ", stderr); break; case GD_WARNING: fputs("GD Warning: ", stderr); break; case GD_NOTICE: fputs("GD Notice: ", stderr); break; case GD_INFO: fputs("GD Info: ", stderr); break; case GD_DEBUG: fputs("GD Debug: ", stderr); break; } vfprintf(stderr, format, args); fflush(stderr); } static gdErrorMethod gd_error_method = gd_stderr_error; static void _gd_error_ex(int priority, const char *format, va_list args) { if (gd_error_method) { gd_error_method(priority, format, args); } } void gd_error(const char *format, ...) { va_list args; va_start(args, format); _gd_error_ex(GD_WARNING, format, args); va_end(args); } void gd_error_ex(int priority, const char *format, ...) { va_list args; va_start(args, format); _gd_error_ex(priority, format, args); va_end(args); } /* Function: gdSetErrorMethod */ BGD_DECLARE(void) gdSetErrorMethod(gdErrorMethod error_method) { gd_error_method = error_method; } /* Function: gdClearErrorMethod */ BGD_DECLARE(void) gdClearErrorMethod(void) { gd_error_method = gd_stderr_error; } static void gdImageBrushApply (gdImagePtr im, int x, int y); static void gdImageTileApply (gdImagePtr im, int x, int y); BGD_DECLARE(int) gdImageGetTrueColorPixel (gdImagePtr im, int x, int y); /** * Group: Creation and Destruction */ /* Function: gdImageCreate gdImageCreate is called to create palette-based images, with no more than 256 colors. The image must eventually be destroyed using gdImageDestroy(). Parameters: sx - The image width. sy - The image height. Returns: A pointer to the new image or NULL if an error occurred. Example: (start code) gdImagePtr im; im = gdImageCreate(64, 64); // ... Use the image ... gdImageDestroy(im); (end code) See Also: <gdImageCreateTrueColor> */ BGD_DECLARE(gdImagePtr) gdImageCreate (int sx, int sy) { int i; gdImagePtr im; if (overflow2(sx, sy)) { return NULL; } if (overflow2(sizeof (unsigned char *), sy)) { return NULL; } if (overflow2(sizeof (unsigned char), sx)) { return NULL; } im = (gdImage *) gdCalloc(1, sizeof(gdImage)); if (!im) { return NULL; } /* Row-major ever since gd 1.3 */ im->pixels = (unsigned char **) gdMalloc (sizeof (unsigned char *) * sy); if (!im->pixels) { gdFree(im); return NULL; } im->polyInts = 0; im->polyAllocated = 0; im->brush = 0; im->tile = 0; im->style = 0; for (i = 0; (i < sy); i++) { /* Row-major ever since gd 1.3 */ im->pixels[i] = (unsigned char *) gdCalloc (sx, sizeof (unsigned char)); if (!im->pixels[i]) { for (--i ; i >= 0; i--) { gdFree(im->pixels[i]); } gdFree(im->pixels); gdFree(im); return NULL; } } im->sx = sx; im->sy = sy; im->colorsTotal = 0; im->transparent = (-1); im->interlace = 0; im->thick = 1; im->AA = 0; for (i = 0; (i < gdMaxColors); i++) { im->open[i] = 1; }; im->trueColor = 0; im->tpixels = 0; im->cx1 = 0; im->cy1 = 0; im->cx2 = im->sx - 1; im->cy2 = im->sy - 1; im->res_x = GD_RESOLUTION; im->res_y = GD_RESOLUTION; im->interpolation = NULL; im->interpolation_id = GD_BILINEAR_FIXED; return im; } /* Function: gdImageCreateTrueColor <gdImageCreateTrueColor> is called to create truecolor images, with an essentially unlimited number of colors. Invoke <gdImageCreateTrueColor> with the x and y dimensions of the desired image. <gdImageCreateTrueColor> returns a <gdImagePtr> to the new image, or NULL if unable to allocate the image. The image must eventually be destroyed using <gdImageDestroy>(). Truecolor images are always filled with black at creation time. There is no concept of a "background" color index. Parameters: sx - The image width. sy - The image height. Returns: A pointer to the new image or NULL if an error occurred. Example: (start code) gdImagePtr im; im = gdImageCreateTrueColor(64, 64); // ... Use the image ... gdImageDestroy(im); (end code) See Also: <gdImageCreateTrueColor> */ BGD_DECLARE(gdImagePtr) gdImageCreateTrueColor (int sx, int sy) { int i; gdImagePtr im; if (overflow2(sx, sy)) { return NULL; } if (overflow2(sizeof (int *), sy)) { return 0; } if (overflow2(sizeof(int), sx)) { return NULL; } im = (gdImage *) gdMalloc (sizeof (gdImage)); if (!im) { return 0; } memset (im, 0, sizeof (gdImage)); im->tpixels = (int **) gdMalloc (sizeof (int *) * sy); if (!im->tpixels) { gdFree(im); return 0; } im->polyInts = 0; im->polyAllocated = 0; im->brush = 0; im->tile = 0; im->style = 0; for (i = 0; (i < sy); i++) { im->tpixels[i] = (int *) gdCalloc (sx, sizeof (int)); if (!im->tpixels[i]) { /* 2.0.34 */ i--; while (i >= 0) { gdFree(im->tpixels[i]); i--; } gdFree(im->tpixels); gdFree(im); return 0; } } im->sx = sx; im->sy = sy; im->transparent = (-1); im->interlace = 0; im->trueColor = 1; /* 2.0.2: alpha blending is now on by default, and saving of alpha is off by default. This allows font antialiasing to work as expected on the first try in JPEGs -- quite important -- and also allows for smaller PNGs when saving of alpha channel is not really desired, which it usually isn't! */ im->saveAlphaFlag = 0; im->alphaBlendingFlag = 1; im->thick = 1; im->AA = 0; im->cx1 = 0; im->cy1 = 0; im->cx2 = im->sx - 1; im->cy2 = im->sy - 1; im->res_x = GD_RESOLUTION; im->res_y = GD_RESOLUTION; im->interpolation = NULL; im->interpolation_id = GD_BILINEAR_FIXED; return im; } /* Function: gdImageDestroy <gdImageDestroy> is used to free the memory associated with an image. It is important to invoke <gdImageDestroy> before exiting your program or assigning a new image to a <gdImagePtr> variable. Parameters: im - Pointer to the gdImage to delete. Returns: Nothing. Example: (start code) gdImagePtr im; im = gdImageCreate(10, 10); // ... Use the image ... // Now destroy it gdImageDestroy(im); (end code) */ BGD_DECLARE(void) gdImageDestroy (gdImagePtr im) { int i; if (im->pixels) { for (i = 0; (i < im->sy); i++) { gdFree (im->pixels[i]); } gdFree (im->pixels); } if (im->tpixels) { for (i = 0; (i < im->sy); i++) { gdFree (im->tpixels[i]); } gdFree (im->tpixels); } if (im->polyInts) { gdFree (im->polyInts); } if (im->style) { gdFree (im->style); } gdFree (im); } /** * Group: Color */ /** * Function: gdImageColorClosest * * Gets the closest color of the image * * This is a simplified variant of <gdImageColorClosestAlpha> where the alpha * channel is always opaque. * * Parameters: * im - The image. * r - The value of the red component. * g - The value of the green component. * b - The value of the blue component. * * Returns: * The closest color already available in the palette for palette images; * the color value of the given components for truecolor images. * * See also: * - <gdImageColorExact> */ BGD_DECLARE(int) gdImageColorClosest (gdImagePtr im, int r, int g, int b) { return gdImageColorClosestAlpha (im, r, g, b, gdAlphaOpaque); } /** * Function: gdImageColorClosestAlpha * * Gets the closest color of the image * * Parameters: * im - The image. * r - The value of the red component. * g - The value of the green component. * b - The value of the blue component. * a - The value of the alpha component. * * Returns: * The closest color already available in the palette for palette images; * the color value of the given components for truecolor images. * * See also: * - <gdImageColorExactAlpha> */ BGD_DECLARE(int) gdImageColorClosestAlpha (gdImagePtr im, int r, int g, int b, int a) { int i; long rd, gd, bd, ad; int ct = (-1); int first = 1; long mindist = 0; if (im->trueColor) { return gdTrueColorAlpha (r, g, b, a); } for (i = 0; (i < (im->colorsTotal)); i++) { long dist; if (im->open[i]) { continue; } rd = (im->red[i] - r); gd = (im->green[i] - g); bd = (im->blue[i] - b); /* gd 2.02: whoops, was - b (thanks to David Marwood) */ /* gd 2.16: was blue rather than alpha! Geez! Thanks to Artur Jakub Jerzak */ ad = (im->alpha[i] - a); dist = rd * rd + gd * gd + bd * bd + ad * ad; if (first || (dist < mindist)) { mindist = dist; ct = i; first = 0; } } return ct; } /* This code is taken from http://www.acm.org/jgt/papers/SmithLyons96/hwb_rgb.html, an article * on colour conversion to/from RBG and HWB colour systems. * It has been modified to return the converted value as a * parameter. */ #define RETURN_HWB(h, w, b) {HWB->H = h; HWB->W = w; HWB->B = b; return HWB;} #define RETURN_RGB(r, g, b) {RGB->R = r; RGB->G = g; RGB->B = b; return RGB;} #define HWB_UNDEFINED -1 #define SETUP_RGB(s, r, g, b) {s.R = r/255.0; s.G = g/255.0; s.B = b/255.0;} #define MIN(a,b) ((a)<(b)?(a):(b)) #define MIN3(a,b,c) ((a)<(b)?(MIN(a,c)):(MIN(b,c))) #define MAX(a,b) ((a)<(b)?(b):(a)) #define MAX3(a,b,c) ((a)<(b)?(MAX(b,c)):(MAX(a,c))) /* * Theoretically, hue 0 (pure red) is identical to hue 6 in these transforms. Pure * red always maps to 6 in this implementation. Therefore UNDEFINED can be * defined as 0 in situations where only unsigned numbers are desired. */ typedef struct { float R, G, B; } RGBType; typedef struct { float H, W, B; } HWBType; static HWBType * RGB_to_HWB (RGBType RGB, HWBType * HWB) { /* * RGB are each on [0, 1]. W and B are returned on [0, 1] and H is * returned on [0, 6]. Exception: H is returned UNDEFINED if W == 1 - B. */ float R = RGB.R, G = RGB.G, B = RGB.B, w, v, b, f; int i; w = MIN3 (R, G, B); v = MAX3 (R, G, B); b = 1 - v; if (v == w) RETURN_HWB (HWB_UNDEFINED, w, b); f = (R == w) ? G - B : ((G == w) ? B - R : R - G); i = (R == w) ? 3 : ((G == w) ? 5 : 1); RETURN_HWB (i - f / (v - w), w, b); } static float HWB_Diff (int r1, int g1, int b1, int r2, int g2, int b2) { RGBType RGB1, RGB2; HWBType HWB1, HWB2; float diff; SETUP_RGB (RGB1, r1, g1, b1); SETUP_RGB (RGB2, r2, g2, b2); RGB_to_HWB (RGB1, &HWB1); RGB_to_HWB (RGB2, &HWB2); /* * I made this bit up; it seems to produce OK results, and it is certainly * more visually correct than the current RGB metric. (PJW) */ if ((HWB1.H == HWB_UNDEFINED) || (HWB2.H == HWB_UNDEFINED)) { diff = 0; /* Undefined hues always match... */ } else { diff = fabs (HWB1.H - HWB2.H); if (diff > 3) { diff = 6 - diff; /* Remember, it's a colour circle */ } } diff = diff * diff + (HWB1.W - HWB2.W) * (HWB1.W - HWB2.W) + (HWB1.B - HWB2.B) * (HWB1.B - HWB2.B); return diff; } #if 0 /* * This is not actually used, but is here for completeness, in case someone wants to * use the HWB stuff for anything else... */ static RGBType * HWB_to_RGB (HWBType HWB, RGBType * RGB) { /* * H is given on [0, 6] or UNDEFINED. W and B are given on [0, 1]. * RGB are each returned on [0, 1]. */ float h = HWB.H, w = HWB.W, b = HWB.B, v, n, f; int i; v = 1 - b; if (h == HWB_UNDEFINED) RETURN_RGB (v, v, v); i = floor (h); f = h - i; if (i & 1) f = 1 - f; /* if i is odd */ n = w + f * (v - w); /* linear interpolation between w and v */ switch (i) { case 6: case 0: RETURN_RGB (v, n, w); case 1: RETURN_RGB (n, v, w); case 2: RETURN_RGB (w, v, n); case 3: RETURN_RGB (w, n, v); case 4: RETURN_RGB (n, w, v); case 5: RETURN_RGB (v, w, n); } return RGB; } #endif /* Function: gdImageColorClosestHWB */ BGD_DECLARE(int) gdImageColorClosestHWB (gdImagePtr im, int r, int g, int b) { int i; /* long rd, gd, bd; */ int ct = (-1); int first = 1; float mindist = 0; if (im->trueColor) { return gdTrueColor (r, g, b); } for (i = 0; (i < (im->colorsTotal)); i++) { float dist; if (im->open[i]) { continue; } dist = HWB_Diff (im->red[i], im->green[i], im->blue[i], r, g, b); if (first || (dist < mindist)) { mindist = dist; ct = i; first = 0; } } return ct; } /** * Function: gdImageColorExact * * Gets the exact color of the image * * This is a simplified variant of <gdImageColorExactAlpha> where the alpha * channel is always opaque. * * Parameters: * im - The image. * r - The value of the red component. * g - The value of the green component. * b - The value of the blue component. * * Returns: * The exact color already available in the palette for palette images; if * there is no exact color, -1 is returned. * For truecolor images the color value of the given components is returned. * * See also: * - <gdImageColorClosest> */ BGD_DECLARE(int) gdImageColorExact (gdImagePtr im, int r, int g, int b) { return gdImageColorExactAlpha (im, r, g, b, gdAlphaOpaque); } /** * Function: gdImageColorExactAlpha * * Gets the exact color of the image * * Parameters: * im - The image. * r - The value of the red component. * g - The value of the green component. * b - The value of the blue component. * a - The value of the alpha component. * * Returns: * The exact color already available in the palette for palette images; if * there is no exact color, -1 is returned. * For truecolor images the color value of the given components is returned. * * See also: * - <gdImageColorClosestAlpha> * - <gdTrueColorAlpha> */ BGD_DECLARE(int) gdImageColorExactAlpha (gdImagePtr im, int r, int g, int b, int a) { int i; if (im->trueColor) { return gdTrueColorAlpha (r, g, b, a); } for (i = 0; (i < (im->colorsTotal)); i++) { if (im->open[i]) { continue; } if ((im->red[i] == r) && (im->green[i] == g) && (im->blue[i] == b) && (im->alpha[i] == a)) { return i; } } return -1; } /** * Function: gdImageColorAllocate * * Allocates a color * * This is a simplified variant of <gdImageColorAllocateAlpha> where the alpha * channel is always opaque. * * Parameters: * im - The image. * r - The value of the red component. * g - The value of the green component. * b - The value of the blue component. * * Returns: * The color value. * * See also: * - <gdImageColorDeallocate> */ BGD_DECLARE(int) gdImageColorAllocate (gdImagePtr im, int r, int g, int b) { return gdImageColorAllocateAlpha (im, r, g, b, gdAlphaOpaque); } /** * Function: gdImageColorAllocateAlpha * * Allocates a color * * This is typically used for palette images, but can be used for truecolor * images as well. * * Parameters: * im - The image. * r - The value of the red component. * g - The value of the green component. * b - The value of the blue component. * * Returns: * The color value. * * See also: * - <gdImageColorDeallocate> */ BGD_DECLARE(int) gdImageColorAllocateAlpha (gdImagePtr im, int r, int g, int b, int a) { int i; int ct = (-1); if (im->trueColor) { return gdTrueColorAlpha (r, g, b, a); } for (i = 0; (i < (im->colorsTotal)); i++) { if (im->open[i]) { ct = i; break; } } if (ct == (-1)) { ct = im->colorsTotal; if (ct == gdMaxColors) { return -1; } im->colorsTotal++; } im->red[ct] = r; im->green[ct] = g; im->blue[ct] = b; im->alpha[ct] = a; im->open[ct] = 0; return ct; } /* Function: gdImageColorResolve gdImageColorResolve is an alternative for the code fragment (start code) if ((color=gdImageColorExact(im,R,G,B)) < 0) if ((color=gdImageColorAllocate(im,R,G,B)) < 0) color=gdImageColorClosest(im,R,G,B); (end code) in a single function. Its advantage is that it is guaranteed to return a color index in one search over the color table. */ BGD_DECLARE(int) gdImageColorResolve (gdImagePtr im, int r, int g, int b) { return gdImageColorResolveAlpha (im, r, g, b, gdAlphaOpaque); } /* Function: gdImageColorResolveAlpha */ BGD_DECLARE(int) gdImageColorResolveAlpha (gdImagePtr im, int r, int g, int b, int a) { int c; int ct = -1; int op = -1; long rd, gd, bd, ad, dist; long mindist = 4 * 255 * 255; /* init to max poss dist */ if (im->trueColor) { return gdTrueColorAlpha (r, g, b, a); } for (c = 0; c < im->colorsTotal; c++) { if (im->open[c]) { op = c; /* Save open slot */ continue; /* Color not in use */ } if (c == im->transparent) { /* don't ever resolve to the color that has * been designated as the transparent color */ continue; } rd = (long) (im->red[c] - r); gd = (long) (im->green[c] - g); bd = (long) (im->blue[c] - b); ad = (long) (im->alpha[c] - a); dist = rd * rd + gd * gd + bd * bd + ad * ad; if (dist < mindist) { if (dist == 0) { return c; /* Return exact match color */ } mindist = dist; ct = c; } } /* no exact match. We now know closest, but first try to allocate exact */ if (op == -1) { op = im->colorsTotal; if (op == gdMaxColors) { /* No room for more colors */ return ct; /* Return closest available color */ } im->colorsTotal++; } im->red[op] = r; im->green[op] = g; im->blue[op] = b; im->alpha[op] = a; im->open[op] = 0; return op; /* Return newly allocated color */ } /** * Function: gdImageColorDeallocate * * Removes a palette entry * * This is a no-op for truecolor images. * * Parameters: * im - The image. * color - The palette index. * * See also: * - <gdImageColorAllocate> * - <gdImageColorAllocateAlpha> */ BGD_DECLARE(void) gdImageColorDeallocate (gdImagePtr im, int color) { if (im->trueColor || (color >= gdMaxColors) || (color < 0)) { return; } /* Mark it open. */ im->open[color] = 1; } /** * Function: gdImageColorTransparent * * Sets the transparent color of the image * * Parameter: * im - The image. * color - The color. * * See also: * - <gdImageGetTransparent> */ BGD_DECLARE(void) gdImageColorTransparent (gdImagePtr im, int color) { if (color < 0) { return; } if (!im->trueColor) { if((color < -1) || (color >= gdMaxColors)) { return; } if (im->transparent != -1) { im->alpha[im->transparent] = gdAlphaOpaque; } if (color != -1) { im->alpha[color] = gdAlphaTransparent; } } im->transparent = color; } /* Function: gdImagePaletteCopy */ BGD_DECLARE(void) gdImagePaletteCopy (gdImagePtr to, gdImagePtr from) { int i; int x, y, p; int xlate[256]; if (to->trueColor) { return; } if (from->trueColor) { return; } for (i = 0; i < 256; i++) { xlate[i] = -1; }; for (y = 0; y < (to->sy); y++) { for (x = 0; x < (to->sx); x++) { /* Optimization: no gdImageGetPixel */ p = to->pixels[y][x]; if (xlate[p] == -1) { /* This ought to use HWB, but we don't have an alpha-aware version of that yet. */ xlate[p] = gdImageColorClosestAlpha (from, to->red[p], to->green[p], to->blue[p], to->alpha[p]); /*printf("Mapping %d (%d, %d, %d, %d) to %d (%d, %d, %d, %d)\n", */ /* p, to->red[p], to->green[p], to->blue[p], to->alpha[p], */ /* xlate[p], from->red[xlate[p]], from->green[xlate[p]], from->blue[xlate[p]], from->alpha[xlate[p]]); */ }; /* Optimization: no gdImageSetPixel */ to->pixels[y][x] = xlate[p]; }; }; for (i = 0; (i < (from->colorsTotal)); i++) { /*printf("Copying color %d (%d, %d, %d, %d)\n", i, from->red[i], from->blue[i], from->green[i], from->alpha[i]); */ to->red[i] = from->red[i]; to->blue[i] = from->blue[i]; to->green[i] = from->green[i]; to->alpha[i] = from->alpha[i]; to->open[i] = 0; }; for (i = from->colorsTotal; (i < to->colorsTotal); i++) { to->open[i] = 1; }; to->colorsTotal = from->colorsTotal; } /* Function: gdImageColorReplace */ BGD_DECLARE(int) gdImageColorReplace (gdImagePtr im, int src, int dst) { register int x, y; int n = 0; if (src == dst) { return 0; } #define REPLACING_LOOP(pixel) do { \ for (y = im->cy1; y <= im->cy2; y++) { \ for (x = im->cx1; x <= im->cx2; x++) { \ if (pixel(im, x, y) == src) { \ gdImageSetPixel(im, x, y, dst); \ n++; \ } \ } \ } \ } while (0) if (im->trueColor) { REPLACING_LOOP(gdImageTrueColorPixel); } else { REPLACING_LOOP(gdImagePalettePixel); } #undef REPLACING_LOOP return n; } /* Function: gdImageColorReplaceThreshold */ BGD_DECLARE(int) gdImageColorReplaceThreshold (gdImagePtr im, int src, int dst, float threshold) { register int x, y; int n = 0; if (src == dst) { return 0; } #define REPLACING_LOOP(pixel) do { \ for (y = im->cy1; y <= im->cy2; y++) { \ for (x = im->cx1; x <= im->cx2; x++) { \ if (gdColorMatch(im, src, pixel(im, x, y), threshold)) { \ gdImageSetPixel(im, x, y, dst); \ n++; \ } \ } \ } \ } while (0) if (im->trueColor) { REPLACING_LOOP(gdImageTrueColorPixel); } else { REPLACING_LOOP(gdImagePalettePixel); } #undef REPLACING_LOOP return n; } static int colorCmp (const void *x, const void *y) { int a = *(int const *)x; int b = *(int const *)y; return (a > b) - (a < b); } /* Function: gdImageColorReplaceArray */ BGD_DECLARE(int) gdImageColorReplaceArray (gdImagePtr im, int len, int *src, int *dst) { register int x, y; int c, *d, *base; int i, n = 0; if (len <= 0 || src == dst) { return 0; } if (len == 1) { return gdImageColorReplace(im, src[0], dst[0]); } if (overflow2(len, sizeof(int)<<1)) { return -1; } base = (int *)gdMalloc(len * (sizeof(int)<<1)); if (!base) { return -1; } for (i = 0; i < len; i++) { base[(i<<1)] = src[i]; base[(i<<1)+1] = dst[i]; } qsort(base, len, sizeof(int)<<1, colorCmp); #define REPLACING_LOOP(pixel) do { \ for (y = im->cy1; y <= im->cy2; y++) { \ for (x = im->cx1; x <= im->cx2; x++) { \ c = pixel(im, x, y); \ if ( (d = (int *)bsearch(&c, base, len, sizeof(int)<<1, colorCmp)) ) { \ gdImageSetPixel(im, x, y, d[1]); \ n++; \ } \ } \ } \ } while (0) if (im->trueColor) { REPLACING_LOOP(gdImageTrueColorPixel); } else { REPLACING_LOOP(gdImagePalettePixel); } #undef REPLACING_LOOP gdFree(base); return n; } /* Function: gdImageColorReplaceCallback */ BGD_DECLARE(int) gdImageColorReplaceCallback (gdImagePtr im, gdCallbackImageColor callback) { int c, d, n = 0; if (!callback) { return 0; } if (im->trueColor) { register int x, y; for (y = im->cy1; y <= im->cy2; y++) { for (x = im->cx1; x <= im->cx2; x++) { c = gdImageTrueColorPixel(im, x, y); if ( (d = callback(im, c)) != c) { gdImageSetPixel(im, x, y, d); n++; } } } } else { /* palette */ int *sarr, *darr; int k, len = 0; sarr = (int *)gdCalloc(im->colorsTotal, sizeof(int)); if (!sarr) { return -1; } for (c = 0; c < im->colorsTotal; c++) { if (!im->open[c]) { sarr[len++] = c; } } darr = (int *)gdCalloc(len, sizeof(int)); if (!darr) { gdFree(sarr); return -1; } for (k = 0; k < len; k++) { darr[k] = callback(im, sarr[k]); } n = gdImageColorReplaceArray(im, k, sarr, darr); gdFree(darr); gdFree(sarr); } return n; } /* 2.0.10: before the drawing routines, some code to clip points that are * outside the drawing window. Nick Atty (nick@canalplan.org.uk) * * This is the Sutherland Hodgman Algorithm, as implemented by * Duvanenko, Robbins and Gyurcsik - SH(DRG) for short. See Dr Dobb's * Journal, January 1996, pp107-110 and 116-117 * * Given the end points of a line, and a bounding rectangle (which we * know to be from (0,0) to (SX,SY)), adjust the endpoints to be on * the edges of the rectangle if the line should be drawn at all, * otherwise return a failure code */ /* this does "one-dimensional" clipping: note that the second time it is called, all the x parameters refer to height and the y to width - the comments ignore this (if you can understand it when it's looking at the X parameters, it should become clear what happens on the second call!) The code is simplified from that in the article, as we know that gd images always start at (0,0) */ /* 2.0.26, TBB: we now have to respect a clipping rectangle, it won't necessarily start at 0. */ static int clip_1d (int *x0, int *y0, int *x1, int *y1, int mindim, int maxdim) { double m; /* gradient of line */ if (*x0 < mindim) { /* start of line is left of window */ if (*x1 < mindim) /* as is the end, so the line never cuts the window */ return 0; m = (*y1 - *y0) / (double) (*x1 - *x0); /* calculate the slope of the line */ /* adjust x0 to be on the left boundary (ie to be zero), and y0 to match */ *y0 -= (int)(m * (*x0 - mindim)); *x0 = mindim; /* now, perhaps, adjust the far end of the line as well */ if (*x1 > maxdim) { *y1 += m * (maxdim - *x1); *x1 = maxdim; } return 1; } if (*x0 > maxdim) { /* start of line is right of window - complement of above */ if (*x1 > maxdim) /* as is the end, so the line misses the window */ return 0; m = (*y1 - *y0) / (double) (*x1 - *x0); /* calculate the slope of the line */ *y0 += (int)(m * (maxdim - *x0)); /* adjust so point is on the right boundary */ *x0 = maxdim; /* now, perhaps, adjust the end of the line */ if (*x1 < mindim) { *y1 -= (int)(m * (*x1 - mindim)); *x1 = mindim; } return 1; } /* the final case - the start of the line is inside the window */ if (*x1 > maxdim) { /* other end is outside to the right */ m = (*y1 - *y0) / (double) (*x1 - *x0); /* calculate the slope of the line */ *y1 += (int)(m * (maxdim - *x1)); *x1 = maxdim; return 1; } if (*x1 < mindim) { /* other end is outside to the left */ m = (*y1 - *y0) / (double) (*x1 - *x0); /* calculate the slope of the line */ *y1 -= (int)(m * (*x1 - mindim)); *x1 = mindim; return 1; } /* only get here if both points are inside the window */ return 1; } /* end of line clipping code */ /** * Group: Pixels */ /* Function: gdImageSetPixel */ BGD_DECLARE(void) gdImageSetPixel (gdImagePtr im, int x, int y, int color) { int p; switch (color) { case gdStyled: if (!im->style) { /* Refuse to draw if no style is set. */ return; } else { p = im->style[im->stylePos++]; } if (p != (gdTransparent)) { gdImageSetPixel (im, x, y, p); } im->stylePos = im->stylePos % im->styleLength; break; case gdStyledBrushed: if (!im->style) { /* Refuse to draw if no style is set. */ return; } p = im->style[im->stylePos++]; if ((p != gdTransparent) && (p != 0)) { gdImageSetPixel (im, x, y, gdBrushed); } im->stylePos = im->stylePos % im->styleLength; break; case gdBrushed: gdImageBrushApply (im, x, y); break; case gdTiled: gdImageTileApply (im, x, y); break; case gdAntiAliased: /* This shouldn't happen (2.0.26) because we just call gdImageAALine now, but do something sane. */ gdImageSetPixel(im, x, y, im->AA_color); break; default: if (gdImageBoundsSafeMacro (im, x, y)) { if (im->trueColor) { switch (im->alphaBlendingFlag) { default: case gdEffectReplace: im->tpixels[y][x] = color; break; case gdEffectAlphaBlend: case gdEffectNormal: im->tpixels[y][x] = gdAlphaBlend(im->tpixels[y][x], color); break; case gdEffectOverlay : im->tpixels[y][x] = gdLayerOverlay(im->tpixels[y][x], color); break; case gdEffectMultiply : im->tpixels[y][x] = gdLayerMultiply(im->tpixels[y][x], color); break; } } else { im->pixels[y][x] = color; } } break; } } static void gdImageBrushApply (gdImagePtr im, int x, int y) { int lx, ly; int hy; int hx; int x1, y1, x2, y2; int srcx, srcy; if (!im->brush) { return; } hy = gdImageSY (im->brush) / 2; y1 = y - hy; y2 = y1 + gdImageSY (im->brush); hx = gdImageSX (im->brush) / 2; x1 = x - hx; x2 = x1 + gdImageSX (im->brush); srcy = 0; if (im->trueColor) { if (im->brush->trueColor) { for (ly = y1; (ly < y2); ly++) { srcx = 0; for (lx = x1; (lx < x2); lx++) { int p; p = gdImageGetTrueColorPixel (im->brush, srcx, srcy); /* 2.0.9, Thomas Winzig: apply simple full transparency */ if (p != gdImageGetTransparent (im->brush)) { gdImageSetPixel (im, lx, ly, p); } srcx++; } srcy++; } } else { /* 2.0.12: Brush palette, image truecolor (thanks to Thorben Kundinger for pointing out the issue) */ for (ly = y1; (ly < y2); ly++) { srcx = 0; for (lx = x1; (lx < x2); lx++) { int p, tc; p = gdImageGetPixel (im->brush, srcx, srcy); tc = gdImageGetTrueColorPixel (im->brush, srcx, srcy); /* 2.0.9, Thomas Winzig: apply simple full transparency */ if (p != gdImageGetTransparent (im->brush)) { gdImageSetPixel (im, lx, ly, tc); } srcx++; } srcy++; } } } else { for (ly = y1; (ly < y2); ly++) { srcx = 0; for (lx = x1; (lx < x2); lx++) { int p; p = gdImageGetPixel (im->brush, srcx, srcy); /* Allow for non-square brushes! */ if (p != gdImageGetTransparent (im->brush)) { /* Truecolor brush. Very slow on a palette destination. */ if (im->brush->trueColor) { gdImageSetPixel (im, lx, ly, gdImageColorResolveAlpha (im, gdTrueColorGetRed (p), gdTrueColorGetGreen (p), gdTrueColorGetBlue (p), gdTrueColorGetAlpha (p))); } else { gdImageSetPixel (im, lx, ly, im->brushColorMap[p]); } } srcx++; } srcy++; } } } static void gdImageTileApply (gdImagePtr im, int x, int y) { gdImagePtr tile = im->tile; int srcx, srcy; int p; if (!tile) { return; } srcx = x % gdImageSX (tile); srcy = y % gdImageSY (tile); if (im->trueColor) { p = gdImageGetPixel (tile, srcx, srcy); if (p != gdImageGetTransparent (tile)) { if (!tile->trueColor) { p = gdTrueColorAlpha(tile->red[p], tile->green[p], tile->blue[p], tile->alpha[p]); } gdImageSetPixel (im, x, y, p); } } else { p = gdImageGetPixel (tile, srcx, srcy); /* Allow for transparency */ if (p != gdImageGetTransparent (tile)) { if (tile->trueColor) { /* Truecolor tile. Very slow on a palette destination. */ gdImageSetPixel (im, x, y, gdImageColorResolveAlpha (im, gdTrueColorGetRed (p), gdTrueColorGetGreen (p), gdTrueColorGetBlue (p), gdTrueColorGetAlpha (p))); } else { gdImageSetPixel (im, x, y, im->tileColorMap[p]); } } } } /** * Function: gdImageGetPixel * * Gets a pixel color as stored in the image. * * Parameters: * im - The image. * x - The x-coordinate. * y - The y-coordinate. * * See also: * - <gdImageGetTrueColorPixel> * - <gdImagePalettePixel> * - <gdImageTrueColorPixel> */ BGD_DECLARE(int) gdImageGetPixel (gdImagePtr im, int x, int y) { if (gdImageBoundsSafeMacro (im, x, y)) { if (im->trueColor) { return im->tpixels[y][x]; } else { return im->pixels[y][x]; } } else { return 0; } } /** * Function: gdImageGetTrueColorPixel * * Gets a pixel color always as truecolor value. * * Parameters: * im - The image. * x - The x-coordinate. * y - The y-coordinate. * * See also: * - <gdImageGetPixel> * - <gdImageTrueColorPixel> */ BGD_DECLARE(int) gdImageGetTrueColorPixel (gdImagePtr im, int x, int y) { int p = gdImageGetPixel (im, x, y); if (!im->trueColor) { return gdTrueColorAlpha (im->red[p], im->green[p], im->blue[p], (im->transparent == p) ? gdAlphaTransparent : im->alpha[p]); } else { return p; } } /** * Group: Primitives */ /* Function: gdImageAABlend NO-OP, kept for library compatibility. */ BGD_DECLARE(void) gdImageAABlend (gdImagePtr im) { (void)im; } static void gdImageAALine (gdImagePtr im, int x1, int y1, int x2, int y2, int col); static void _gdImageFilledHRectangle (gdImagePtr im, int x1, int y1, int x2, int y2, int color); static void gdImageHLine(gdImagePtr im, int y, int x1, int x2, int col) { if (im->thick > 1) { int thickhalf = im->thick >> 1; _gdImageFilledHRectangle(im, x1, y - thickhalf, x2, y + im->thick - thickhalf - 1, col); } else { if (x2 < x1) { int t = x2; x2 = x1; x1 = t; } for (; x1 <= x2; x1++) { gdImageSetPixel(im, x1, y, col); } } return; } static void gdImageVLine(gdImagePtr im, int x, int y1, int y2, int col) { if (im->thick > 1) { int thickhalf = im->thick >> 1; gdImageFilledRectangle(im, x - thickhalf, y1, x + im->thick - thickhalf - 1, y2, col); } else { if (y2 < y1) { int t = y1; y1 = y2; y2 = t; } for (; y1 <= y2; y1++) { gdImageSetPixel(im, x, y1, col); } } return; } /* Function: gdImageLine Bresenham as presented in Foley & Van Dam. */ BGD_DECLARE(void) gdImageLine (gdImagePtr im, int x1, int y1, int x2, int y2, int color) { int dx, dy, incr1, incr2, d, x, y, xend, yend, xdirflag, ydirflag; int wid; int w, wstart; int thick; if (color == gdAntiAliased) { /* gdAntiAliased passed as color: use the much faster, much cheaper and equally attractive gdImageAALine implementation. That clips too, so don't clip twice. */ gdImageAALine(im, x1, y1, x2, y2, im->AA_color); return; } /* 2.0.10: Nick Atty: clip to edges of drawing rectangle, return if no points need to be drawn. 2.0.26, TBB: clip to edges of clipping rectangle. We were getting away with this because gdImageSetPixel is used for actual drawing, but this is still more efficient and opens the way to skip per-pixel bounds checking in the future. */ if (clip_1d (&x1, &y1, &x2, &y2, im->cx1, im->cx2) == 0) return; if (clip_1d (&y1, &x1, &y2, &x2, im->cy1, im->cy2) == 0) return; thick = im->thick; dx = abs (x2 - x1); dy = abs (y2 - y1); if (dx == 0) { gdImageVLine(im, x1, y1, y2, color); return; } else if (dy == 0) { gdImageHLine(im, y1, x1, x2, color); return; } if (dy <= dx) { /* More-or-less horizontal. use wid for vertical stroke */ /* Doug Claar: watch out for NaN in atan2 (2.0.5) */ /* 2.0.12: Michael Schwartz: divide rather than multiply; TBB: but watch out for /0! */ double ac = cos (atan2 (dy, dx)); if (ac != 0) { wid = thick / ac; } else { wid = 1; } if (wid == 0) { wid = 1; } d = 2 * dy - dx; incr1 = 2 * dy; incr2 = 2 * (dy - dx); if (x1 > x2) { x = x2; y = y2; ydirflag = (-1); xend = x1; } else { x = x1; y = y1; ydirflag = 1; xend = x2; } /* Set up line thickness */ wstart = y - wid / 2; for (w = wstart; w < wstart + wid; w++) gdImageSetPixel (im, x, w, color); if (((y2 - y1) * ydirflag) > 0) { while (x < xend) { x++; if (d < 0) { d += incr1; } else { y++; d += incr2; } wstart = y - wid / 2; for (w = wstart; w < wstart + wid; w++) gdImageSetPixel (im, x, w, color); } } else { while (x < xend) { x++; if (d < 0) { d += incr1; } else { y--; d += incr2; } wstart = y - wid / 2; for (w = wstart; w < wstart + wid; w++) gdImageSetPixel (im, x, w, color); } } } else { /* More-or-less vertical. use wid for horizontal stroke */ /* 2.0.12: Michael Schwartz: divide rather than multiply; TBB: but watch out for /0! */ double as = sin (atan2 (dy, dx)); if (as != 0) { wid = thick / as; } else { wid = 1; } if (wid == 0) wid = 1; d = 2 * dx - dy; incr1 = 2 * dx; incr2 = 2 * (dx - dy); if (y1 > y2) { y = y2; x = x2; yend = y1; xdirflag = (-1); } else { y = y1; x = x1; yend = y2; xdirflag = 1; } /* Set up line thickness */ wstart = x - wid / 2; for (w = wstart; w < wstart + wid; w++) gdImageSetPixel (im, w, y, color); if (((x2 - x1) * xdirflag) > 0) { while (y < yend) { y++; if (d < 0) { d += incr1; } else { x++; d += incr2; } wstart = x - wid / 2; for (w = wstart; w < wstart + wid; w++) gdImageSetPixel (im, w, y, color); } } else { while (y < yend) { y++; if (d < 0) { d += incr1; } else { x--; d += incr2; } wstart = x - wid / 2; for (w = wstart; w < wstart + wid; w++) gdImageSetPixel (im, w, y, color); } } } } static void dashedSet (gdImagePtr im, int x, int y, int color, int *onP, int *dashStepP, int wid, int vert); /* Function: gdImageDashedLine */ BGD_DECLARE(void) gdImageDashedLine (gdImagePtr im, int x1, int y1, int x2, int y2, int color) { int dx, dy, incr1, incr2, d, x, y, xend, yend, xdirflag, ydirflag; int dashStep = 0; int on = 1; int wid; int vert; int thick = im->thick; dx = abs (x2 - x1); dy = abs (y2 - y1); if (dy <= dx) { /* More-or-less horizontal. use wid for vertical stroke */ /* 2.0.12: Michael Schwartz: divide rather than multiply; TBB: but watch out for /0! */ double as = sin (atan2 (dy, dx)); if (as != 0) { wid = thick / as; } else { wid = 1; } vert = 1; d = 2 * dy - dx; incr1 = 2 * dy; incr2 = 2 * (dy - dx); if (x1 > x2) { x = x2; y = y2; ydirflag = (-1); xend = x1; } else { x = x1; y = y1; ydirflag = 1; xend = x2; } dashedSet (im, x, y, color, &on, &dashStep, wid, vert); if (((y2 - y1) * ydirflag) > 0) { while (x < xend) { x++; if (d < 0) { d += incr1; } else { y++; d += incr2; } dashedSet (im, x, y, color, &on, &dashStep, wid, vert); } } else { while (x < xend) { x++; if (d < 0) { d += incr1; } else { y--; d += incr2; } dashedSet (im, x, y, color, &on, &dashStep, wid, vert); } } } else { /* 2.0.12: Michael Schwartz: divide rather than multiply; TBB: but watch out for /0! */ double as = sin (atan2 (dy, dx)); if (as != 0) { wid = thick / as; } else { wid = 1; } vert = 0; d = 2 * dx - dy; incr1 = 2 * dx; incr2 = 2 * (dx - dy); if (y1 > y2) { y = y2; x = x2; yend = y1; xdirflag = (-1); } else { y = y1; x = x1; yend = y2; xdirflag = 1; } dashedSet (im, x, y, color, &on, &dashStep, wid, vert); if (((x2 - x1) * xdirflag) > 0) { while (y < yend) { y++; if (d < 0) { d += incr1; } else { x++; d += incr2; } dashedSet (im, x, y, color, &on, &dashStep, wid, vert); } } else { while (y < yend) { y++; if (d < 0) { d += incr1; } else { x--; d += incr2; } dashedSet (im, x, y, color, &on, &dashStep, wid, vert); } } } } static void dashedSet (gdImagePtr im, int x, int y, int color, int *onP, int *dashStepP, int wid, int vert) { int dashStep = *dashStepP; int on = *onP; int w, wstart; dashStep++; if (dashStep == gdDashSize) { dashStep = 0; on = !on; } if (on) { if (vert) { wstart = y - wid / 2; for (w = wstart; w < wstart + wid; w++) gdImageSetPixel (im, x, w, color); } else { wstart = x - wid / 2; for (w = wstart; w < wstart + wid; w++) gdImageSetPixel (im, w, y, color); } } *dashStepP = dashStep; *onP = on; } /* Function: gdImageBoundsSafe */ BGD_DECLARE(int) gdImageBoundsSafe (gdImagePtr im, int x, int y) { return gdImageBoundsSafeMacro (im, x, y); } /** * Function: gdImageChar * * Draws a single character. * * Parameters: * im - The image to draw onto. * f - The raster font. * x - The x coordinate of the upper left pixel. * y - The y coordinate of the upper left pixel. * c - The character. * color - The color. * * Variants: * - <gdImageCharUp> * * See also: * - <gdFontPtr> */ BGD_DECLARE(void) gdImageChar (gdImagePtr im, gdFontPtr f, int x, int y, int c, int color) { int cx, cy; int px, py; int fline; cx = 0; cy = 0; #ifdef CHARSET_EBCDIC c = ASC (c); #endif /*CHARSET_EBCDIC */ if ((c < f->offset) || (c >= (f->offset + f->nchars))) { return; } fline = (c - f->offset) * f->h * f->w; for (py = y; (py < (y + f->h)); py++) { for (px = x; (px < (x + f->w)); px++) { if (f->data[fline + cy * f->w + cx]) { gdImageSetPixel (im, px, py, color); } cx++; } cx = 0; cy++; } } /** * Function: gdImageCharUp */ BGD_DECLARE(void) gdImageCharUp (gdImagePtr im, gdFontPtr f, int x, int y, int c, int color) { int cx, cy; int px, py; int fline; cx = 0; cy = 0; #ifdef CHARSET_EBCDIC c = ASC (c); #endif /*CHARSET_EBCDIC */ if ((c < f->offset) || (c >= (f->offset + f->nchars))) { return; } fline = (c - f->offset) * f->h * f->w; for (py = y; (py > (y - f->w)); py--) { for (px = x; (px < (x + f->h)); px++) { if (f->data[fline + cy * f->w + cx]) { gdImageSetPixel (im, px, py, color); } cy++; } cy = 0; cx++; } } /** * Function: gdImageString * * Draws a character string. * * Parameters: * im - The image to draw onto. * f - The raster font. * x - The x coordinate of the upper left pixel. * y - The y coordinate of the upper left pixel. * c - The character string. * color - The color. * * Variants: * - <gdImageStringUp> * - <gdImageString16> * - <gdImageStringUp16> * * See also: * - <gdFontPtr> * - <gdImageStringTTF> */ BGD_DECLARE(void) gdImageString (gdImagePtr im, gdFontPtr f, int x, int y, unsigned char *s, int color) { int i; int l; l = strlen ((char *) s); for (i = 0; (i < l); i++) { gdImageChar (im, f, x, y, s[i], color); x += f->w; } } /** * Function: gdImageStringUp */ BGD_DECLARE(void) gdImageStringUp (gdImagePtr im, gdFontPtr f, int x, int y, unsigned char *s, int color) { int i; int l; l = strlen ((char *) s); for (i = 0; (i < l); i++) { gdImageCharUp (im, f, x, y, s[i], color); y -= f->w; } } static int strlen16 (unsigned short *s); /** * Function: gdImageString16 */ BGD_DECLARE(void) gdImageString16 (gdImagePtr im, gdFontPtr f, int x, int y, unsigned short *s, int color) { int i; int l; l = strlen16 (s); for (i = 0; (i < l); i++) { gdImageChar (im, f, x, y, s[i], color); x += f->w; } } /** * Function: gdImageStringUp16 */ BGD_DECLARE(void) gdImageStringUp16 (gdImagePtr im, gdFontPtr f, int x, int y, unsigned short *s, int color) { int i; int l; l = strlen16 (s); for (i = 0; (i < l); i++) { gdImageCharUp (im, f, x, y, s[i], color); y -= f->w; } } static int strlen16 (unsigned short *s) { int len = 0; while (*s) { s++; len++; } return len; } #ifndef HAVE_LSQRT /* If you don't have a nice square root function for longs, you can use ** this hack */ long lsqrt (long n) { long result = (long) sqrt ((double) n); return result; } #endif /* s and e are integers modulo 360 (degrees), with 0 degrees being the rightmost extreme and degrees changing clockwise. cx and cy are the center in pixels; w and h are the horizontal and vertical diameter in pixels. */ /* Function: gdImageArc */ BGD_DECLARE(void) gdImageArc (gdImagePtr im, int cx, int cy, int w, int h, int s, int e, int color) { gdImageFilledArc (im, cx, cy, w, h, s, e, color, gdNoFill); } /* Function: gdImageFilledArc */ BGD_DECLARE(void) gdImageFilledArc (gdImagePtr im, int cx, int cy, int w, int h, int s, int e, int color, int style) { gdPoint pts[363]; int i, pti; int lx = 0, ly = 0; int fx = 0, fy = 0; if ((s % 360) == (e % 360)) { s = 0; e = 360; } else { if (s > 360) { s = s % 360; } if (e > 360) { e = e % 360; } while (s < 0) { s += 360; } while (e < s) { e += 360; } if (s == e) { s = 0; e = 360; } } for (i = s, pti = 1; (i <= e); i++, pti++) { int x, y; x = ((long) gdCosT[i % 360] * (long) w / (2 * 1024)) + cx; y = ((long) gdSinT[i % 360] * (long) h / (2 * 1024)) + cy; if (i != s) { if (!(style & gdChord)) { if (style & gdNoFill) { gdImageLine (im, lx, ly, x, y, color); } else { if (y == ly) { pti--; /* don't add this point */ if (((i > 270 || i < 90) && x > lx) || ((i > 90 && i < 270) && x < lx)) { /* replace the old x coord, if increasing on the right side or decreasing on the left side */ pts[pti].x = x; } } else { pts[pti].x = x; pts[pti].y = y; } } } } else { fx = x; fy = y; if (!(style & (gdChord | gdNoFill))) { pts[0].x = cx; pts[0].y = cy; pts[pti].x = x; pts[pti].y = y; } } lx = x; ly = y; } if (style & gdChord) { if (style & gdNoFill) { if (style & gdEdged) { gdImageLine (im, cx, cy, lx, ly, color); gdImageLine (im, cx, cy, fx, fy, color); } gdImageLine (im, fx, fy, lx, ly, color); } else { pts[0].x = fx; pts[0].y = fy; pts[1].x = lx; pts[1].y = ly; pts[2].x = cx; pts[2].y = cy; gdImageFilledPolygon (im, pts, 3, color); } } else { if (style & gdNoFill) { if (style & gdEdged) { gdImageLine (im, cx, cy, lx, ly, color); gdImageLine (im, cx, cy, fx, fy, color); } } else { pts[pti].x = cx; pts[pti].y = cy; gdImageFilledPolygon(im, pts, pti+1, color); } } } /* Function: gdImageEllipse */ BGD_DECLARE(void) gdImageEllipse(gdImagePtr im, int mx, int my, int w, int h, int c) { int x=0,mx1=0,mx2=0,my1=0,my2=0; long aq,bq,dx,dy,r,rx,ry,a,b; a=w>>1; b=h>>1; gdImageSetPixel(im,mx+a, my, c); gdImageSetPixel(im,mx-a, my, c); mx1 = mx-a; my1 = my; mx2 = mx+a; my2 = my; aq = a * a; bq = b * b; dx = aq << 1; dy = bq << 1; r = a * bq; rx = r << 1; ry = 0; x = a; while (x > 0) { if (r > 0) { my1++; my2--; ry +=dx; r -=ry; } if (r <= 0) { x--; mx1++; mx2--; rx -=dy; r +=rx; } gdImageSetPixel(im,mx1, my1, c); gdImageSetPixel(im,mx1, my2, c); gdImageSetPixel(im,mx2, my1, c); gdImageSetPixel(im,mx2, my2, c); } } /* Function: gdImageFilledEllipse */ BGD_DECLARE(void) gdImageFilledEllipse (gdImagePtr im, int mx, int my, int w, int h, int c) { int x=0,mx1=0,mx2=0,my1=0,my2=0; long aq,bq,dx,dy,r,rx,ry,a,b; int i; int old_y2; a=w>>1; b=h>>1; for (x = mx-a; x <= mx+a; x++) { gdImageSetPixel(im, x, my, c); } mx1 = mx-a; my1 = my; mx2 = mx+a; my2 = my; aq = a * a; bq = b * b; dx = aq << 1; dy = bq << 1; r = a * bq; rx = r << 1; ry = 0; x = a; old_y2=-2; while (x > 0) { if (r > 0) { my1++; my2--; ry +=dx; r -=ry; } if (r <= 0) { x--; mx1++; mx2--; rx -=dy; r +=rx; } if(old_y2!=my2) { for(i=mx1; i<=mx2; i++) { gdImageSetPixel(im,i,my2,c); gdImageSetPixel(im,i,my1,c); } } old_y2 = my2; } } /* Function: gdImageFillToBorder */ BGD_DECLARE(void) gdImageFillToBorder (gdImagePtr im, int x, int y, int border, int color) { int lastBorder; /* Seek left */ int leftLimit, rightLimit; int i; int restoreAlphaBleding; if (border < 0 || color < 0) { /* Refuse to fill to a non-solid border */ return; } if (!im->trueColor) { if ((color > (im->colorsTotal - 1)) || (border > (im->colorsTotal - 1)) || (color < 0)) { return; } } leftLimit = (-1); restoreAlphaBleding = im->alphaBlendingFlag; im->alphaBlendingFlag = 0; if (x >= im->sx) { x = im->sx - 1; } else if (x < 0) { x = 0; } if (y >= im->sy) { y = im->sy - 1; } else if (y < 0) { y = 0; } for (i = x; (i >= 0); i--) { if (gdImageGetPixel (im, i, y) == border) { break; } gdImageSetPixel (im, i, y, color); leftLimit = i; } if (leftLimit == (-1)) { im->alphaBlendingFlag = restoreAlphaBleding; return; } /* Seek right */ rightLimit = x; for (i = (x + 1); (i < im->sx); i++) { if (gdImageGetPixel (im, i, y) == border) { break; } gdImageSetPixel (im, i, y, color); rightLimit = i; } /* Look at lines above and below and start paints */ /* Above */ if (y > 0) { lastBorder = 1; for (i = leftLimit; (i <= rightLimit); i++) { int c; c = gdImageGetPixel (im, i, y - 1); if (lastBorder) { if ((c != border) && (c != color)) { gdImageFillToBorder (im, i, y - 1, border, color); lastBorder = 0; } } else if ((c == border) || (c == color)) { lastBorder = 1; } } } /* Below */ if (y < ((im->sy) - 1)) { lastBorder = 1; for (i = leftLimit; (i <= rightLimit); i++) { int c = gdImageGetPixel (im, i, y + 1); if (lastBorder) { if ((c != border) && (c != color)) { gdImageFillToBorder (im, i, y + 1, border, color); lastBorder = 0; } } else if ((c == border) || (c == color)) { lastBorder = 1; } } } im->alphaBlendingFlag = restoreAlphaBleding; } /* * set the pixel at (x,y) and its 4-connected neighbors * with the same pixel value to the new pixel value nc (new color). * A 4-connected neighbor: pixel above, below, left, or right of a pixel. * ideas from comp.graphics discussions. * For tiled fill, the use of a flag buffer is mandatory. As the tile image can * contain the same color as the color to fill. To do not bloat normal filling * code I added a 2nd private function. */ static int gdImageTileGet (gdImagePtr im, int x, int y) { int srcx, srcy; int tileColor,p; if (!im->tile) { return -1; } srcx = x % gdImageSX(im->tile); srcy = y % gdImageSY(im->tile); p = gdImageGetPixel(im->tile, srcx, srcy); if (p == im->tile->transparent) { tileColor = im->transparent; } else if (im->trueColor) { if (im->tile->trueColor) { tileColor = p; } else { tileColor = gdTrueColorAlpha( gdImageRed(im->tile,p), gdImageGreen(im->tile,p), gdImageBlue (im->tile,p), gdImageAlpha (im->tile,p)); } } else { if (im->tile->trueColor) { tileColor = gdImageColorResolveAlpha(im, gdTrueColorGetRed (p), gdTrueColorGetGreen (p), gdTrueColorGetBlue (p), gdTrueColorGetAlpha (p)); } else { tileColor = gdImageColorResolveAlpha(im, gdImageRed (im->tile,p), gdImageGreen (im->tile,p), gdImageBlue (im->tile,p), gdImageAlpha (im->tile,p)); } } return tileColor; } /* horizontal segment of scan line y */ struct seg { int y, xl, xr, dy; }; /* max depth of stack */ #define FILL_MAX ((int)(im->sy*im->sx)/4) #define FILL_PUSH(Y, XL, XR, DY) \ if (sp<stack+FILL_MAX && Y+(DY)>=0 && Y+(DY)<wy2) \ {sp->y = Y; sp->xl = XL; sp->xr = XR; sp->dy = DY; sp++;} #define FILL_POP(Y, XL, XR, DY) \ {sp--; Y = sp->y+(DY = sp->dy); XL = sp->xl; XR = sp->xr;} static void _gdImageFillTiled(gdImagePtr im, int x, int y, int nc); /* Function: gdImageFill */ BGD_DECLARE(void) gdImageFill(gdImagePtr im, int x, int y, int nc) { int l, x1, x2, dy; int oc; /* old pixel value */ int wx2,wy2; int alphablending_bak; /* stack of filled segments */ /* struct seg stack[FILL_MAX],*sp = stack; */ struct seg *stack; struct seg *sp; if (!im->trueColor && nc > (im->colorsTotal - 1)) { return; } alphablending_bak = im->alphaBlendingFlag; im->alphaBlendingFlag = 0; if (nc==gdTiled) { _gdImageFillTiled(im,x,y,nc); im->alphaBlendingFlag = alphablending_bak; return; } wx2=im->sx; wy2=im->sy; oc = gdImageGetPixel(im, x, y); if (oc==nc || x<0 || x>wx2 || y<0 || y>wy2) { im->alphaBlendingFlag = alphablending_bak; return; } /* Do not use the 4 neighbors implementation with * small images */ if (im->sx < 4) { int ix = x, iy = y, c; do { do { c = gdImageGetPixel(im, ix, iy); if (c != oc) { goto done; } gdImageSetPixel(im, ix, iy, nc); } while(ix++ < (im->sx -1)); ix = x; } while(iy++ < (im->sy -1)); goto done; } if(overflow2(im->sy, im->sx)) { return; } if(overflow2(sizeof(struct seg), ((im->sy * im->sx) / 4))) { return; } stack = (struct seg *)gdMalloc(sizeof(struct seg) * ((int)(im->sy*im->sx)/4)); if (!stack) { return; } sp = stack; /* required! */ FILL_PUSH(y,x,x,1); /* seed segment (popped 1st) */ FILL_PUSH(y+1, x, x, -1); while (sp>stack) { FILL_POP(y, x1, x2, dy); for (x=x1; x>=0 && gdImageGetPixel(im,x, y)==oc; x--) { gdImageSetPixel(im,x, y, nc); } if (x>=x1) { goto skip; } l = x+1; /* leak on left? */ if (l<x1) { FILL_PUSH(y, l, x1-1, -dy); } x = x1+1; do { for (; x<=wx2 && gdImageGetPixel(im,x, y)==oc; x++) { gdImageSetPixel(im, x, y, nc); } FILL_PUSH(y, l, x-1, dy); /* leak on right? */ if (x>x2+1) { FILL_PUSH(y, x2+1, x-1, -dy); } skip: for (x++; x<=x2 && (gdImageGetPixel(im, x, y)!=oc); x++); l = x; } while (x<=x2); } gdFree(stack); done: im->alphaBlendingFlag = alphablending_bak; } static void _gdImageFillTiled(gdImagePtr im, int x, int y, int nc) { int l, x1, x2, dy; int oc; /* old pixel value */ int wx2,wy2; /* stack of filled segments */ struct seg *stack; struct seg *sp; char *pts; if (!im->tile) { return; } wx2=im->sx; wy2=im->sy; if(overflow2(im->sy, im->sx)) { return; } if(overflow2(sizeof(struct seg), ((im->sy * im->sx) / 4))) { return; } pts = (char *) gdCalloc(im->sy * im->sx, sizeof(char)); if (!pts) { return; } stack = (struct seg *)gdMalloc(sizeof(struct seg) * ((int)(im->sy*im->sx)/4)); if (!stack) { gdFree(pts); return; } sp = stack; oc = gdImageGetPixel(im, x, y); /* required! */ FILL_PUSH(y,x,x,1); /* seed segment (popped 1st) */ FILL_PUSH(y+1, x, x, -1); while (sp>stack) { FILL_POP(y, x1, x2, dy); for (x=x1; x>=0 && (!pts[y + x*wy2] && gdImageGetPixel(im,x,y)==oc); x--) { nc = gdImageTileGet(im,x,y); pts[y + x*wy2]=1; gdImageSetPixel(im,x, y, nc); } if (x>=x1) { goto skip; } l = x+1; /* leak on left? */ if (l<x1) { FILL_PUSH(y, l, x1-1, -dy); } x = x1+1; do { for (; x<wx2 && (!pts[y + x*wy2] && gdImageGetPixel(im,x, y)==oc) ; x++) { if (pts[y + x*wy2]) { /* we should never be here */ break; } nc = gdImageTileGet(im,x,y); pts[y + x*wy2]=1; gdImageSetPixel(im, x, y, nc); } FILL_PUSH(y, l, x-1, dy); /* leak on right? */ if (x>x2+1) { FILL_PUSH(y, x2+1, x-1, -dy); } skip: for (x++; x<=x2 && (pts[y + x*wy2] || gdImageGetPixel(im,x, y)!=oc); x++); l = x; } while (x<=x2); } gdFree(pts); gdFree(stack); } /** * Function: gdImageRectangle * * Draws a rectangle. * * Parameters: * im - The image. * x1 - The x-coordinate of one of the corners. * y1 - The y-coordinate of one of the corners. * x2 - The x-coordinate of another corner. * y2 - The y-coordinate of another corner. * color - The color. * * See also: * - <gdImageFilledRectangle> */ BGD_DECLARE(void) gdImageRectangle (gdImagePtr im, int x1, int y1, int x2, int y2, int color) { int thick = im->thick; if (x1 == x2 && y1 == y2 && thick == 1) { gdImageSetPixel(im, x1, y1, color); return; } if (y2 < y1) { int t = y1; y1 = y2; y2 = t; } if (x2 < x1) { int t = x1; x1 = x2; x2 = t; } if (thick > 1) { int cx, cy, x1ul, y1ul, x2lr, y2lr; int half = thick >> 1; x1ul = x1 - half; y1ul = y1 - half; x2lr = x2 + half; y2lr = y2 + half; cy = y1ul + thick; while (cy-- > y1ul) { cx = x1ul - 1; while (cx++ < x2lr) { gdImageSetPixel(im, cx, cy, color); } } cy = y2lr - thick; while (cy++ < y2lr) { cx = x1ul - 1; while (cx++ < x2lr) { gdImageSetPixel(im, cx, cy, color); } } cy = y1ul + thick - 1; while (cy++ < y2lr -thick) { cx = x1ul - 1; while (cx++ < x1ul + thick) { gdImageSetPixel(im, cx, cy, color); } } cy = y1ul + thick - 1; while (cy++ < y2lr -thick) { cx = x2lr - thick - 1; while (cx++ < x2lr) { gdImageSetPixel(im, cx, cy, color); } } return; } else { if (x1 == x2 || y1 == y2) { gdImageLine(im, x1, y1, x2, y2, color); } else { gdImageLine(im, x1, y1, x2, y1, color); gdImageLine(im, x1, y2, x2, y2, color); gdImageLine(im, x1, y1 + 1, x1, y2 - 1, color); gdImageLine(im, x2, y1 + 1, x2, y2 - 1, color); } } } static void _gdImageFilledHRectangle (gdImagePtr im, int x1, int y1, int x2, int y2, int color) { int x, y; if (x1 == x2 && y1 == y2) { gdImageSetPixel(im, x1, y1, color); return; } if (x1 > x2) { x = x1; x1 = x2; x2 = x; } if (y1 > y2) { y = y1; y1 = y2; y2 = y; } if (x1 < 0) { x1 = 0; } if (x2 >= gdImageSX(im)) { x2 = gdImageSX(im) - 1; } if (y1 < 0) { y1 = 0; } if (y2 >= gdImageSY(im)) { y2 = gdImageSY(im) - 1; } for (x = x1; (x <= x2); x++) { for (y = y1; (y <= y2); y++) { gdImageSetPixel (im, x, y, color); } } } static void _gdImageFilledVRectangle (gdImagePtr im, int x1, int y1, int x2, int y2, int color) { int x, y; if (x1 == x2 && y1 == y2) { gdImageSetPixel(im, x1, y1, color); return; } if (x1 > x2) { x = x1; x1 = x2; x2 = x; } if (y1 > y2) { y = y1; y1 = y2; y2 = y; } if (x1 < 0) { x1 = 0; } if (x2 >= gdImageSX(im)) { x2 = gdImageSX(im) - 1; } if (y1 < 0) { y1 = 0; } if (y2 >= gdImageSY(im)) { y2 = gdImageSY(im) - 1; } for (y = y1; (y <= y2); y++) { for (x = x1; (x <= x2); x++) { gdImageSetPixel (im, x, y, color); } } } /* Function: gdImageFilledRectangle */ BGD_DECLARE(void) gdImageFilledRectangle (gdImagePtr im, int x1, int y1, int x2, int y2, int color) { _gdImageFilledVRectangle(im, x1, y1, x2, y2, color); } /** * Group: Cloning and Copying */ /** * Function: gdImageClone * * Clones an image * * Creates an exact duplicate of the given image. * * Parameters: * src - The source image. * * Returns: * The cloned image on success, NULL on failure. */ BGD_DECLARE(gdImagePtr) gdImageClone (gdImagePtr src) { gdImagePtr dst; register int i, x; if (src->trueColor) { dst = gdImageCreateTrueColor(src->sx , src->sy); } else { dst = gdImageCreate(src->sx , src->sy); } if (dst == NULL) { return NULL; } if (src->trueColor == 0) { dst->colorsTotal = src->colorsTotal; for (i = 0; i < gdMaxColors; i++) { dst->red[i] = src->red[i]; dst->green[i] = src->green[i]; dst->blue[i] = src->blue[i]; dst->alpha[i] = src->alpha[i]; dst->open[i] = src->open[i]; } for (i = 0; i < src->sy; i++) { for (x = 0; x < src->sx; x++) { dst->pixels[i][x] = src->pixels[i][x]; } } } else { for (i = 0; i < src->sy; i++) { for (x = 0; x < src->sx; x++) { dst->tpixels[i][x] = src->tpixels[i][x]; } } } if (src->styleLength > 0) { dst->styleLength = src->styleLength; dst->stylePos = src->stylePos; for (i = 0; i < src->styleLength; i++) { dst->style[i] = src->style[i]; } } dst->interlace = src->interlace; dst->alphaBlendingFlag = src->alphaBlendingFlag; dst->saveAlphaFlag = src->saveAlphaFlag; dst->AA = src->AA; dst->AA_color = src->AA_color; dst->AA_dont_blend = src->AA_dont_blend; dst->cx1 = src->cx1; dst->cy1 = src->cy1; dst->cx2 = src->cx2; dst->cy2 = src->cy2; dst->res_x = src->res_x; dst->res_y = src->res_y; dst->paletteQuantizationMethod = src->paletteQuantizationMethod; dst->paletteQuantizationSpeed = src->paletteQuantizationSpeed; dst->paletteQuantizationMinQuality = src->paletteQuantizationMinQuality; dst->paletteQuantizationMinQuality = src->paletteQuantizationMinQuality; dst->interpolation_id = src->interpolation_id; dst->interpolation = src->interpolation; if (src->brush) { dst->brush = gdImageClone(src->brush); } if (src->tile) { dst->tile = gdImageClone(src->tile); } if (src->style) { gdImageSetStyle(dst, src->style, src->styleLength); } for (i = 0; i < gdMaxColors; i++) { dst->brushColorMap[i] = src->brushColorMap[i]; dst->tileColorMap[i] = src->tileColorMap[i]; } if (src->polyAllocated > 0) { dst->polyAllocated = src->polyAllocated; for (i = 0; i < src->polyAllocated; i++) { dst->polyInts[i] = src->polyInts[i]; } } return dst; } /** * Function: gdImageCopy * * Copy an area of an image to another image * * Parameters: * dst - The destination image. * src - The source image. * dstX - The x-coordinate of the upper left corner to copy to. * dstY - The y-coordinate of the upper left corner to copy to. * srcX - The x-coordinate of the upper left corner to copy from. * srcY - The y-coordinate of the upper left corner to copy from. * w - The width of the area to copy. * h - The height of the area to copy. * * See also: * - <gdImageCopyMerge> * - <gdImageCopyMergeGray> */ BGD_DECLARE(void) gdImageCopy (gdImagePtr dst, gdImagePtr src, int dstX, int dstY, int srcX, int srcY, int w, int h) { int c; int x, y; int tox, toy; int i; int colorMap[gdMaxColors]; if (dst->trueColor) { /* 2.0: much easier when the destination is truecolor. */ /* 2.0.10: needs a transparent-index check that is still valid if * * the source is not truecolor. Thanks to Frank Warmerdam. */ if (src->trueColor) { for (y = 0; (y < h); y++) { for (x = 0; (x < w); x++) { int c = gdImageGetTrueColorPixel (src, srcX + x, srcY + y); if (c != src->transparent) { gdImageSetPixel (dst, dstX + x, dstY + y, c); } } } } else { /* source is palette based */ for (y = 0; (y < h); y++) { for (x = 0; (x < w); x++) { int c = gdImageGetPixel (src, srcX + x, srcY + y); if (c != src->transparent) { gdImageSetPixel(dst, dstX + x, dstY + y, gdTrueColorAlpha(src->red[c], src->green[c], src->blue[c], src->alpha[c])); } } } } return; } for (i = 0; (i < gdMaxColors); i++) { colorMap[i] = (-1); } toy = dstY; for (y = srcY; (y < (srcY + h)); y++) { tox = dstX; for (x = srcX; (x < (srcX + w)); x++) { int nc; int mapTo; c = gdImageGetPixel (src, x, y); /* Added 7/24/95: support transparent copies */ if (gdImageGetTransparent (src) == c) { tox++; continue; } /* Have we established a mapping for this color? */ if (src->trueColor) { /* 2.05: remap to the palette available in the destination image. This is slow and works badly, but it beats crashing! Thanks to Padhrig McCarthy. */ mapTo = gdImageColorResolveAlpha (dst, gdTrueColorGetRed (c), gdTrueColorGetGreen (c), gdTrueColorGetBlue (c), gdTrueColorGetAlpha (c)); } else if (colorMap[c] == (-1)) { /* If it's the same image, mapping is trivial */ if (dst == src) { nc = c; } else { /* Get best match possible. This function never returns error. */ nc = gdImageColorResolveAlpha (dst, src->red[c], src->green[c], src->blue[c], src->alpha[c]); } colorMap[c] = nc; mapTo = colorMap[c]; } else { mapTo = colorMap[c]; } gdImageSetPixel (dst, tox, toy, mapTo); tox++; } toy++; } } /** * Function: gdImageCopyMerge * * Copy an area of an image to another image ignoring alpha * * The source area will be copied to the destination are by merging the pixels. * * Note: * This function is a substitute for real alpha channel operations, * so it doesn't pay attention to the alpha channel. * * Parameters: * dst - The destination image. * src - The source image. * dstX - The x-coordinate of the upper left corner to copy to. * dstY - The y-coordinate of the upper left corner to copy to. * srcX - The x-coordinate of the upper left corner to copy from. * srcY - The y-coordinate of the upper left corner to copy from. * w - The width of the area to copy. * h - The height of the area to copy. * pct - The percentage in range 0..100. * * See also: * - <gdImageCopy> * - <gdImageCopyMergeGray> */ BGD_DECLARE(void) gdImageCopyMerge (gdImagePtr dst, gdImagePtr src, int dstX, int dstY, int srcX, int srcY, int w, int h, int pct) { int c, dc; int x, y; int tox, toy; int ncR, ncG, ncB; toy = dstY; for (y = srcY; (y < (srcY + h)); y++) { tox = dstX; for (x = srcX; (x < (srcX + w)); x++) { int nc; c = gdImageGetPixel (src, x, y); /* Added 7/24/95: support transparent copies */ if (gdImageGetTransparent (src) == c) { tox++; continue; } /* If it's the same image, mapping is trivial */ if (dst == src) { nc = c; } else { dc = gdImageGetPixel (dst, tox, toy); ncR = gdImageRed (src, c) * (pct / 100.0) + gdImageRed (dst, dc) * ((100 - pct) / 100.0); ncG = gdImageGreen (src, c) * (pct / 100.0) + gdImageGreen (dst, dc) * ((100 - pct) / 100.0); ncB = gdImageBlue (src, c) * (pct / 100.0) + gdImageBlue (dst, dc) * ((100 - pct) / 100.0); /* Find a reasonable color */ nc = gdImageColorResolve (dst, ncR, ncG, ncB); } gdImageSetPixel (dst, tox, toy, nc); tox++; } toy++; } } /** * Function: gdImageCopyMergeGray * * Copy an area of an image to another image ignoring alpha * * The source area will be copied to the grayscaled destination area by merging * the pixels. * * Note: * This function is a substitute for real alpha channel operations, * so it doesn't pay attention to the alpha channel. * * Parameters: * dst - The destination image. * src - The source image. * dstX - The x-coordinate of the upper left corner to copy to. * dstY - The y-coordinate of the upper left corner to copy to. * srcX - The x-coordinate of the upper left corner to copy from. * srcY - The y-coordinate of the upper left corner to copy from. * w - The width of the area to copy. * h - The height of the area to copy. * pct - The percentage of the source color intensity in range 0..100. * * See also: * - <gdImageCopy> * - <gdImageCopyMerge> */ BGD_DECLARE(void) gdImageCopyMergeGray (gdImagePtr dst, gdImagePtr src, int dstX, int dstY, int srcX, int srcY, int w, int h, int pct) { int c, dc; int x, y; int tox, toy; int ncR, ncG, ncB; float g; toy = dstY; for (y = srcY; (y < (srcY + h)); y++) { tox = dstX; for (x = srcX; (x < (srcX + w)); x++) { int nc; c = gdImageGetPixel (src, x, y); /* Added 7/24/95: support transparent copies */ if (gdImageGetTransparent (src) == c) { tox++; continue; } /* * If it's the same image, mapping is NOT trivial since we * merge with greyscale target, but if pct is 100, the grey * value is not used, so it becomes trivial. pjw 2.0.12. */ if (dst == src && pct == 100) { nc = c; } else { dc = gdImageGetPixel (dst, tox, toy); g = 0.29900 * gdImageRed(dst, dc) + 0.58700 * gdImageGreen(dst, dc) + 0.11400 * gdImageBlue(dst, dc); ncR = gdImageRed (src, c) * (pct / 100.0) + g * ((100 - pct) / 100.0); ncG = gdImageGreen (src, c) * (pct / 100.0) + g * ((100 - pct) / 100.0); ncB = gdImageBlue (src, c) * (pct / 100.0) + g * ((100 - pct) / 100.0); /* First look for an exact match */ nc = gdImageColorExact (dst, ncR, ncG, ncB); if (nc == (-1)) { /* No, so try to allocate it */ nc = gdImageColorAllocate (dst, ncR, ncG, ncB); /* If we're out of colors, go for the closest color */ if (nc == (-1)) { nc = gdImageColorClosest (dst, ncR, ncG, ncB); } } } gdImageSetPixel (dst, tox, toy, nc); tox++; } toy++; } } /** * Function: gdImageCopyResized * * Copy a resized area from an image to another image * * If the source and destination area differ in size, the area will be resized * using nearest-neighbor interpolation. * * Parameters: * dst - The destination image. * src - The source image. * dstX - The x-coordinate of the upper left corner to copy to. * dstY - The y-coordinate of the upper left corner to copy to. * srcX - The x-coordinate of the upper left corner to copy from. * srcY - The y-coordinate of the upper left corner to copy from. * dstW - The width of the area to copy to. * dstH - The height of the area to copy to. * srcW - The width of the area to copy from. * srcH - The height of the area to copy from. * * See also: * - <gdImageCopyResampled> * - <gdImageScale> */ BGD_DECLARE(void) gdImageCopyResized (gdImagePtr dst, gdImagePtr src, int dstX, int dstY, int srcX, int srcY, int dstW, int dstH, int srcW, int srcH) { int c; int x, y; int tox, toy; int ydest; int i; int colorMap[gdMaxColors]; /* Stretch vectors */ int *stx; int *sty; /* We only need to use floating point to determine the correct stretch vector for one line's worth. */ if (overflow2(sizeof (int), srcW)) { return; } if (overflow2(sizeof (int), srcH)) { return; } stx = (int *) gdMalloc (sizeof (int) * srcW); if (!stx) { return; } sty = (int *) gdMalloc (sizeof (int) * srcH); if (!sty) { gdFree(stx); return; } /* Fixed by Mao Morimoto 2.0.16 */ for (i = 0; (i < srcW); i++) { stx[i] = dstW * (i + 1) / srcW - dstW * i / srcW; } for (i = 0; (i < srcH); i++) { sty[i] = dstH * (i + 1) / srcH - dstH * i / srcH; } for (i = 0; (i < gdMaxColors); i++) { colorMap[i] = (-1); } toy = dstY; for (y = srcY; (y < (srcY + srcH)); y++) { for (ydest = 0; (ydest < sty[y - srcY]); ydest++) { tox = dstX; for (x = srcX; (x < (srcX + srcW)); x++) { int nc = 0; int mapTo; if (!stx[x - srcX]) { continue; } if (dst->trueColor) { /* 2.0.9: Thorben Kundinger: Maybe the source image is not a truecolor image */ if (!src->trueColor) { int tmp = gdImageGetPixel (src, x, y); mapTo = gdImageGetTrueColorPixel (src, x, y); if (gdImageGetTransparent (src) == tmp) { /* 2.0.21, TK: not tox++ */ tox += stx[x - srcX]; continue; } } else { /* TK: old code follows */ mapTo = gdImageGetTrueColorPixel (src, x, y); /* Added 7/24/95: support transparent copies */ if (gdImageGetTransparent (src) == mapTo) { /* 2.0.21, TK: not tox++ */ tox += stx[x - srcX]; continue; } } } else { c = gdImageGetPixel (src, x, y); /* Added 7/24/95: support transparent copies */ if (gdImageGetTransparent (src) == c) { tox += stx[x - srcX]; continue; } if (src->trueColor) { /* Remap to the palette available in the destination image. This is slow and works badly. */ mapTo = gdImageColorResolveAlpha (dst, gdTrueColorGetRed (c), gdTrueColorGetGreen (c), gdTrueColorGetBlue (c), gdTrueColorGetAlpha (c)); } else { /* Have we established a mapping for this color? */ if (colorMap[c] == (-1)) { /* If it's the same image, mapping is trivial */ if (dst == src) { nc = c; } else { /* Find or create the best match */ /* 2.0.5: can't use gdTrueColorGetRed, etc with palette */ nc = gdImageColorResolveAlpha (dst, gdImageRed (src, c), gdImageGreen (src, c), gdImageBlue (src, c), gdImageAlpha (src, c)); } colorMap[c] = nc; } mapTo = colorMap[c]; } } for (i = 0; (i < stx[x - srcX]); i++) { gdImageSetPixel (dst, tox, toy, mapTo); tox++; } } toy++; } } gdFree (stx); gdFree (sty); } /** * Function: gdImageCopyRotated * * Copy a rotated area from an image to another image * * The area is counter-clockwise rotated using nearest-neighbor interpolation. * * Parameters: * dst - The destination image. * src - The source image. * dstX - The x-coordinate of the center of the area to copy to. * dstY - The y-coordinate of the center of the area to copy to. * srcX - The x-coordinate of the upper left corner to copy from. * srcY - The y-coordinate of the upper left corner to copy from. * srcW - The width of the area to copy from. * srcH - The height of the area to copy from. * angle - The angle in degrees. * * See also: * - <gdImageRotateInterpolated> */ BGD_DECLARE(void) gdImageCopyRotated (gdImagePtr dst, gdImagePtr src, double dstX, double dstY, int srcX, int srcY, int srcWidth, int srcHeight, int angle) { double dx, dy; double radius = sqrt (srcWidth * srcWidth + srcHeight * srcHeight); double aCos = cos (angle * .0174532925); double aSin = sin (angle * .0174532925); double scX = srcX + ((double) srcWidth) / 2; double scY = srcY + ((double) srcHeight) / 2; int cmap[gdMaxColors]; int i; /* 2.0.34: transparency preservation. The transparentness of the transparent color is more important than its hue. */ if (src->transparent != -1) { if (dst->transparent == -1) { dst->transparent = src->transparent; } } for (i = 0; (i < gdMaxColors); i++) { cmap[i] = (-1); } for (dy = dstY - radius; (dy <= dstY + radius); dy++) { for (dx = dstX - radius; (dx <= dstX + radius); dx++) { double sxd = (dx - dstX) * aCos - (dy - dstY) * aSin; double syd = (dy - dstY) * aCos + (dx - dstX) * aSin; int sx = sxd + scX; int sy = syd + scY; if ((sx >= srcX) && (sx < srcX + srcWidth) && (sy >= srcY) && (sy < srcY + srcHeight)) { int c = gdImageGetPixel (src, sx, sy); /* 2.0.34: transparency wins */ if (c == src->transparent) { gdImageSetPixel (dst, dx, dy, dst->transparent); } else if (!src->trueColor) { /* Use a table to avoid an expensive lookup on every single pixel */ if (cmap[c] == -1) { cmap[c] = gdImageColorResolveAlpha (dst, gdImageRed (src, c), gdImageGreen (src, c), gdImageBlue (src, c), gdImageAlpha (src, c)); } gdImageSetPixel (dst, dx, dy, cmap[c]); } else { gdImageSetPixel (dst, dx, dy, gdImageColorResolveAlpha (dst, gdImageRed (src, c), gdImageGreen (src, c), gdImageBlue (src, c), gdImageAlpha (src, c))); } } } } } /* When gd 1.x was first created, floating point was to be avoided. These days it is often faster than table lookups or integer arithmetic. The routine below is shamelessly, gloriously floating point. TBB */ /* 2.0.10: cast instead of floor() yields 35% performance improvement. Thanks to John Buckman. */ #define floor2(exp) ((long) exp) /*#define floor2(exp) floor(exp)*/ /** * Function: gdImageCopyResampled * * Copy a resampled area from an image to another image * * If the source and destination area differ in size, the area will be resized * using bilinear interpolation for truecolor images, and nearest-neighbor * interpolation for palette images. * * Parameters: * dst - The destination image. * src - The source image. * dstX - The x-coordinate of the upper left corner to copy to. * dstY - The y-coordinate of the upper left corner to copy to. * srcX - The x-coordinate of the upper left corner to copy from. * srcY - The y-coordinate of the upper left corner to copy from. * dstW - The width of the area to copy to. * dstH - The height of the area to copy to. * srcW - The width of the area to copy from. * srcH - The height of the area to copy from. * * See also: * - <gdImageCopyResized> * - <gdImageScale> */ BGD_DECLARE(void) gdImageCopyResampled (gdImagePtr dst, gdImagePtr src, int dstX, int dstY, int srcX, int srcY, int dstW, int dstH, int srcW, int srcH) { int x, y; if (!dst->trueColor) { gdImageCopyResized (dst, src, dstX, dstY, srcX, srcY, dstW, dstH, srcW, srcH); return; } for (y = dstY; (y < dstY + dstH); y++) { for (x = dstX; (x < dstX + dstW); x++) { float sy1, sy2, sx1, sx2; float sx, sy; float spixels = 0.0; float red = 0.0, green = 0.0, blue = 0.0, alpha = 0.0; float alpha_factor, alpha_sum = 0.0, contrib_sum = 0.0; sy1 = ((float)(y - dstY)) * (float)srcH / (float)dstH; sy2 = ((float)(y + 1 - dstY)) * (float) srcH / (float) dstH; sy = sy1; do { float yportion; if (floorf(sy) == floorf(sy1)) { yportion = 1.0 - (sy - floorf(sy)); if (yportion > sy2 - sy1) { yportion = sy2 - sy1; } sy = floorf(sy); } else if (sy == floorf(sy2)) { yportion = sy2 - floorf(sy2); } else { yportion = 1.0; } sx1 = ((float)(x - dstX)) * (float) srcW / dstW; sx2 = ((float)(x + 1 - dstX)) * (float) srcW / dstW; sx = sx1; do { float xportion; float pcontribution; int p; if (floorf(sx) == floorf(sx1)) { xportion = 1.0 - (sx - floorf(sx)); if (xportion > sx2 - sx1) { xportion = sx2 - sx1; } sx = floorf(sx); } else if (sx == floorf(sx2)) { xportion = sx2 - floorf(sx2); } else { xportion = 1.0; } pcontribution = xportion * yportion; p = gdImageGetTrueColorPixel(src, (int) sx + srcX, (int) sy + srcY); alpha_factor = ((gdAlphaMax - gdTrueColorGetAlpha(p))) * pcontribution; red += gdTrueColorGetRed (p) * alpha_factor; green += gdTrueColorGetGreen (p) * alpha_factor; blue += gdTrueColorGetBlue (p) * alpha_factor; alpha += gdTrueColorGetAlpha (p) * pcontribution; alpha_sum += alpha_factor; contrib_sum += pcontribution; spixels += xportion * yportion; sx += 1.0; } while (sx < sx2); sy += 1.0f; } while (sy < sy2); if (spixels != 0.0) { red /= spixels; green /= spixels; blue /= spixels; alpha /= spixels; } if ( alpha_sum != 0.0) { if( contrib_sum != 0.0) { alpha_sum /= contrib_sum; } red /= alpha_sum; green /= alpha_sum; blue /= alpha_sum; } /* Clamping to allow for rounding errors above */ if (red > 255.0) { red = 255.0; } if (green > 255.0) { green = 255.0; } if (blue > 255.0f) { blue = 255.0; } if (alpha > gdAlphaMax) { alpha = gdAlphaMax; } gdImageSetPixel(dst, x, y, gdTrueColorAlpha ((int) red, (int) green, (int) blue, (int) alpha)); } } } /** * Group: Polygons */ /** * Function: gdImagePolygon * * Draws a closed polygon * * Parameters: * im - The image. * p - The vertices as array of <gdPoint>s. * n - The number of vertices. * c - The color. * * See also: * - <gdImageOpenPolygon> * - <gdImageFilledPolygon> */ BGD_DECLARE(void) gdImagePolygon (gdImagePtr im, gdPointPtr p, int n, int c) { if (n <= 0) { return; } gdImageLine (im, p->x, p->y, p[n - 1].x, p[n - 1].y, c); gdImageOpenPolygon (im, p, n, c); } /** * Function: gdImageOpenPolygon * * Draws an open polygon * * Parameters: * im - The image. * p - The vertices as array of <gdPoint>s. * n - The number of vertices. * c - The color * * See also: * - <gdImagePolygon> */ BGD_DECLARE(void) gdImageOpenPolygon (gdImagePtr im, gdPointPtr p, int n, int c) { int i; int lx, ly; if (n <= 0) { return; } lx = p->x; ly = p->y; for (i = 1; (i < n); i++) { p++; gdImageLine (im, lx, ly, p->x, p->y, c); lx = p->x; ly = p->y; } } /* THANKS to Kirsten Schulz for the polygon fixes! */ /* The intersection finding technique of this code could be improved */ /* by remembering the previous intertersection, and by using the slope. */ /* That could help to adjust intersections to produce a nice */ /* interior_extrema. */ /** * Function: gdImageFilledPolygon * * Draws a filled polygon * * The polygon is filled using the even-odd fillrule what can leave unfilled * regions inside of self-intersecting polygons. This behavior might change in * a future version. * * Parameters: * im - The image. * p - The vertices as array of <gdPoint>s. * n - The number of vertices. * c - The color * * See also: * - <gdImagePolygon> */ BGD_DECLARE(void) gdImageFilledPolygon (gdImagePtr im, gdPointPtr p, int n, int c) { int i; int j; int index; int y; int miny, maxy, pmaxy; int x1, y1; int x2, y2; int ind1, ind2; int ints; int fill_color; if (n <= 0) { return; } if (c == gdAntiAliased) { fill_color = im->AA_color; } else { fill_color = c; } if (!im->polyAllocated) { if (overflow2(sizeof (int), n)) { return; } im->polyInts = (int *) gdMalloc (sizeof (int) * n); if (!im->polyInts) { return; } im->polyAllocated = n; } if (im->polyAllocated < n) { while (im->polyAllocated < n) { im->polyAllocated *= 2; } if (overflow2(sizeof (int), im->polyAllocated)) { return; } im->polyInts = (int *) gdReallocEx (im->polyInts, sizeof (int) * im->polyAllocated); if (!im->polyInts) { return; } } miny = p[0].y; maxy = p[0].y; for (i = 1; (i < n); i++) { if (p[i].y < miny) { miny = p[i].y; } if (p[i].y > maxy) { maxy = p[i].y; } } /* necessary special case: horizontal line */ if (n > 1 && miny == maxy) { x1 = x2 = p[0].x; for (i = 1; (i < n); i++) { if (p[i].x < x1) { x1 = p[i].x; } else if (p[i].x > x2) { x2 = p[i].x; } } gdImageLine(im, x1, miny, x2, miny, c); return; } pmaxy = maxy; /* 2.0.16: Optimization by Ilia Chipitsine -- don't waste time offscreen */ /* 2.0.26: clipping rectangle is even better */ if (miny < im->cy1) { miny = im->cy1; } if (maxy > im->cy2) { maxy = im->cy2; } /* Fix in 1.3: count a vertex only once */ for (y = miny; (y <= maxy); y++) { ints = 0; for (i = 0; (i < n); i++) { if (!i) { ind1 = n - 1; ind2 = 0; } else { ind1 = i - 1; ind2 = i; } y1 = p[ind1].y; y2 = p[ind2].y; if (y1 < y2) { x1 = p[ind1].x; x2 = p[ind2].x; } else if (y1 > y2) { y2 = p[ind1].y; y1 = p[ind2].y; x2 = p[ind1].x; x1 = p[ind2].x; } else { continue; } /* Do the following math as float intermediately, and round to ensure * that Polygon and FilledPolygon for the same set of points have the * same footprint. */ if ((y >= y1) && (y < y2)) { im->polyInts[ints++] = (int) ((float) ((y - y1) * (x2 - x1)) / (float) (y2 - y1) + 0.5 + x1); } else if ((y == pmaxy) && (y == y2)) { im->polyInts[ints++] = x2; } } /* 2.0.26: polygons pretty much always have less than 100 points, and most of the time they have considerably less. For such trivial cases, insertion sort is a good choice. Also a good choice for future implementations that may wish to indirect through a table. */ for (i = 1; (i < ints); i++) { index = im->polyInts[i]; j = i; while ((j > 0) && (im->polyInts[j - 1] > index)) { im->polyInts[j] = im->polyInts[j - 1]; j--; } im->polyInts[j] = index; } for (i = 0; (i < (ints-1)); i += 2) { /* 2.0.29: back to gdImageLine to prevent segfaults when performing a pattern fill */ gdImageLine (im, im->polyInts[i], y, im->polyInts[i + 1], y, fill_color); } } /* If we are drawing this AA, then redraw the border with AA lines. */ /* This doesn't work as well as I'd like, but it doesn't clash either. */ if (c == gdAntiAliased) { gdImagePolygon (im, p, n, c); } } /** * Group: other */ static void gdImageSetAAPixelColor(gdImagePtr im, int x, int y, int color, int t); /** * Function: gdImageSetStyle * * Sets the style for following drawing operations * * Parameters: * im - The image. * style - An array of color values. * noOfPixel - The number of color values. */ BGD_DECLARE(void) gdImageSetStyle (gdImagePtr im, int *style, int noOfPixels) { if (im->style) { gdFree (im->style); } if (overflow2(sizeof (int), noOfPixels)) { return; } im->style = (int *) gdMalloc (sizeof (int) * noOfPixels); if (!im->style) { return; } memcpy (im->style, style, sizeof (int) * noOfPixels); im->styleLength = noOfPixels; im->stylePos = 0; } /** * Function: gdImageSetThickness * * Sets the thickness for following drawing operations * * Parameters: * im - The image. * thickness - The thickness in pixels. */ BGD_DECLARE(void) gdImageSetThickness (gdImagePtr im, int thickness) { im->thick = thickness; } /** * Function: gdImageSetBrush * * Sets the brush for following drawing operations * * Parameters: * im - The image. * brush - The brush image. */ BGD_DECLARE(void) gdImageSetBrush (gdImagePtr im, gdImagePtr brush) { int i; im->brush = brush; if ((!im->trueColor) && (!im->brush->trueColor)) { for (i = 0; (i < gdImageColorsTotal (brush)); i++) { int index; index = gdImageColorResolveAlpha (im, gdImageRed (brush, i), gdImageGreen (brush, i), gdImageBlue (brush, i), gdImageAlpha (brush, i)); im->brushColorMap[i] = index; } } } /* Function: gdImageSetTile */ BGD_DECLARE(void) gdImageSetTile (gdImagePtr im, gdImagePtr tile) { int i; im->tile = tile; if ((!im->trueColor) && (!im->tile->trueColor)) { for (i = 0; (i < gdImageColorsTotal (tile)); i++) { int index; index = gdImageColorResolveAlpha (im, gdImageRed (tile, i), gdImageGreen (tile, i), gdImageBlue (tile, i), gdImageAlpha (tile, i)); im->tileColorMap[i] = index; } } } /** * Function: gdImageSetAntiAliased * * Set the color for subsequent anti-aliased drawing * * If <gdAntiAliased> is passed as color to drawing operations that support * anti-aliased drawing (such as <gdImageLine> and <gdImagePolygon>), the actual * color to be used can be set with this function. * * Example: draw an anti-aliased blue line: * | gdImageSetAntiAliased(im, gdTrueColorAlpha(0, 0, gdBlueMax, gdAlphaOpaque)); * | gdImageLine(im, 10,10, 20,20, gdAntiAliased); * * Parameters: * im - The image. * c - The color. * * See also: * - <gdImageSetAntiAliasedDontBlend> */ BGD_DECLARE(void) gdImageSetAntiAliased (gdImagePtr im, int c) { im->AA = 1; im->AA_color = c; im->AA_dont_blend = -1; } /** * Function: gdImageSetAntiAliasedDontBlend * * Set the color and "dont_blend" color for subsequent anti-aliased drawing * * This extended variant of <gdImageSetAntiAliased> allows to also specify a * (background) color that will not be blended in anti-aliased drawing * operations. * * Parameters: * im - The image. * c - The color. * dont_blend - Whether to blend. */ BGD_DECLARE(void) gdImageSetAntiAliasedDontBlend (gdImagePtr im, int c, int dont_blend) { im->AA = 1; im->AA_color = c; im->AA_dont_blend = dont_blend; } /** * Function: gdImageInterlace * * Sets whether an image is interlaced * * This is relevant only when saving the image in a format that supports * interlacing. * * Parameters: * im - The image. * interlaceArg - Whether the image is interlaced. * * See also: * - <gdImageGetInterlaced> */ BGD_DECLARE(void) gdImageInterlace (gdImagePtr im, int interlaceArg) { im->interlace = interlaceArg; } /** * Function: gdImageCompare * * Compare two images * * Parameters: * im1 - An image. * im2 - Another image. * * Returns: * A bitmask of <Image Comparison> flags where each set flag signals * which attributes of the images are different. */ BGD_DECLARE(int) gdImageCompare (gdImagePtr im1, gdImagePtr im2) { int x, y; int p1, p2; int cmpStatus = 0; int sx, sy; if (im1->interlace != im2->interlace) { cmpStatus |= GD_CMP_INTERLACE; } if (im1->transparent != im2->transparent) { cmpStatus |= GD_CMP_TRANSPARENT; } if (im1->trueColor != im2->trueColor) { cmpStatus |= GD_CMP_TRUECOLOR; } sx = im1->sx; if (im1->sx != im2->sx) { cmpStatus |= GD_CMP_SIZE_X + GD_CMP_IMAGE; if (im2->sx < im1->sx) { sx = im2->sx; } } sy = im1->sy; if (im1->sy != im2->sy) { cmpStatus |= GD_CMP_SIZE_Y + GD_CMP_IMAGE; if (im2->sy < im1->sy) { sy = im2->sy; } } if (im1->colorsTotal != im2->colorsTotal) { cmpStatus |= GD_CMP_NUM_COLORS; } for (y = 0; (y < sy); y++) { for (x = 0; (x < sx); x++) { p1 = im1->trueColor ? gdImageTrueColorPixel (im1, x, y) : gdImagePalettePixel (im1, x, y); p2 = im2->trueColor ? gdImageTrueColorPixel (im2, x, y) : gdImagePalettePixel (im2, x, y); if (gdImageRed (im1, p1) != gdImageRed (im2, p2)) { cmpStatus |= GD_CMP_COLOR + GD_CMP_IMAGE; break; } if (gdImageGreen (im1, p1) != gdImageGreen (im2, p2)) { cmpStatus |= GD_CMP_COLOR + GD_CMP_IMAGE; break; } if (gdImageBlue (im1, p1) != gdImageBlue (im2, p2)) { cmpStatus |= GD_CMP_COLOR + GD_CMP_IMAGE; break; } #if 0 /* Soon we'll add alpha channel to palettes */ if (gdImageAlpha (im1, p1) != gdImageAlpha (im2, p2)) { cmpStatus |= GD_CMP_COLOR + GD_CMP_IMAGE; break; } #endif } if (cmpStatus & GD_CMP_COLOR) { break; }; } return cmpStatus; } /* Thanks to Frank Warmerdam for this superior implementation of gdAlphaBlend(), which merges alpha in the destination color much better. */ /** * Function: gdAlphaBlend * * Blend two colors * * Parameters: * dst - The color to blend onto. * src - The color to blend. * * See also: * - <gdImageAlphaBlending> * - <gdLayerOverlay> * - <gdLayerMultiply> */ BGD_DECLARE(int) gdAlphaBlend (int dst, int src) { int src_alpha = gdTrueColorGetAlpha(src); int dst_alpha, alpha, red, green, blue; int src_weight, dst_weight, tot_weight; /* -------------------------------------------------------------------- */ /* Simple cases we want to handle fast. */ /* -------------------------------------------------------------------- */ if( src_alpha == gdAlphaOpaque ) return src; dst_alpha = gdTrueColorGetAlpha(dst); if( src_alpha == gdAlphaTransparent ) return dst; if( dst_alpha == gdAlphaTransparent ) return src; /* -------------------------------------------------------------------- */ /* What will the source and destination alphas be? Note that */ /* the destination weighting is substantially reduced as the */ /* overlay becomes quite opaque. */ /* -------------------------------------------------------------------- */ src_weight = gdAlphaTransparent - src_alpha; dst_weight = (gdAlphaTransparent - dst_alpha) * src_alpha / gdAlphaMax; tot_weight = src_weight + dst_weight; /* -------------------------------------------------------------------- */ /* What red, green and blue result values will we use? */ /* -------------------------------------------------------------------- */ alpha = src_alpha * dst_alpha / gdAlphaMax; red = (gdTrueColorGetRed(src) * src_weight + gdTrueColorGetRed(dst) * dst_weight) / tot_weight; green = (gdTrueColorGetGreen(src) * src_weight + gdTrueColorGetGreen(dst) * dst_weight) / tot_weight; blue = (gdTrueColorGetBlue(src) * src_weight + gdTrueColorGetBlue(dst) * dst_weight) / tot_weight; /* -------------------------------------------------------------------- */ /* Return merged result. */ /* -------------------------------------------------------------------- */ return ((alpha << 24) + (red << 16) + (green << 8) + blue); } static int gdAlphaOverlayColor (int src, int dst, int max ); /** * Function: gdLayerOverlay * * Overlay two colors * * Parameters: * dst - The color to overlay onto. * src - The color to overlay. * * See also: * - <gdImageAlphaBlending> * - <gdAlphaBlend> * - <gdLayerMultiply> */ BGD_DECLARE(int) gdLayerOverlay (int dst, int src) { int a1, a2; a1 = gdAlphaMax - gdTrueColorGetAlpha(dst); a2 = gdAlphaMax - gdTrueColorGetAlpha(src); return ( ((gdAlphaMax - a1*a2/gdAlphaMax) << 24) + (gdAlphaOverlayColor( gdTrueColorGetRed(src), gdTrueColorGetRed(dst), gdRedMax ) << 16) + (gdAlphaOverlayColor( gdTrueColorGetGreen(src), gdTrueColorGetGreen(dst), gdGreenMax ) << 8) + (gdAlphaOverlayColor( gdTrueColorGetBlue(src), gdTrueColorGetBlue(dst), gdBlueMax )) ); } /* Apply 'overlay' effect - background pixels are colourised by the foreground colour */ static int gdAlphaOverlayColor (int src, int dst, int max ) { dst = dst << 1; if( dst > max ) { /* in the "light" zone */ return dst + (src << 1) - (dst * src / max) - max; } else { /* in the "dark" zone */ return dst * src / max; } } /** * Function: gdLayerMultiply * * Overlay two colors with multiply effect * * Parameters: * dst - The color to overlay onto. * src - The color to overlay. * * See also: * - <gdImageAlphaBlending> * - <gdAlphaBlend> * - <gdLayerOverlay> */ BGD_DECLARE(int) gdLayerMultiply (int dst, int src) { int a1, a2, r1, r2, g1, g2, b1, b2; a1 = gdAlphaMax - gdTrueColorGetAlpha(src); a2 = gdAlphaMax - gdTrueColorGetAlpha(dst); r1 = gdRedMax - (a1 * (gdRedMax - gdTrueColorGetRed(src))) / gdAlphaMax; r2 = gdRedMax - (a2 * (gdRedMax - gdTrueColorGetRed(dst))) / gdAlphaMax; g1 = gdGreenMax - (a1 * (gdGreenMax - gdTrueColorGetGreen(src))) / gdAlphaMax; g2 = gdGreenMax - (a2 * (gdGreenMax - gdTrueColorGetGreen(dst))) / gdAlphaMax; b1 = gdBlueMax - (a1 * (gdBlueMax - gdTrueColorGetBlue(src))) / gdAlphaMax; b2 = gdBlueMax - (a2 * (gdBlueMax - gdTrueColorGetBlue(dst))) / gdAlphaMax ; a1 = gdAlphaMax - a1; a2 = gdAlphaMax - a2; return ( ((a1*a2/gdAlphaMax) << 24) + ((r1*r2/gdRedMax) << 16) + ((g1*g2/gdGreenMax) << 8) + ((b1*b2/gdBlueMax)) ); } /** * Function: gdImageAlphaBlending * * Set the effect for subsequent drawing operations * * Note that the effect is used for truecolor images only. * * Parameters: * im - The image. * alphaBlendingArg - The effect. * * See also: * - <Effects> */ BGD_DECLARE(void) gdImageAlphaBlending (gdImagePtr im, int alphaBlendingArg) { im->alphaBlendingFlag = alphaBlendingArg; } /** * Function: gdImageSaveAlpha * * Sets the save alpha flag * * The save alpha flag specifies whether the alpha channel of the pixels should * be saved. This is supported only for image formats that support full alpha * transparency, e.g. PNG. */ BGD_DECLARE(void) gdImageSaveAlpha (gdImagePtr im, int saveAlphaArg) { im->saveAlphaFlag = saveAlphaArg; } /** * Function: gdImageSetClip * * Sets the clipping rectangle * * The clipping rectangle restricts the drawing area for following drawing * operations. * * Parameters: * im - The image. * x1 - The x-coordinate of the upper left corner. * y1 - The y-coordinate of the upper left corner. * x2 - The x-coordinate of the lower right corner. * y2 - The y-coordinate of the lower right corner. * * See also: * - <gdImageGetClip> */ BGD_DECLARE(void) gdImageSetClip (gdImagePtr im, int x1, int y1, int x2, int y2) { if (x1 < 0) { x1 = 0; } if (x1 >= im->sx) { x1 = im->sx - 1; } if (x2 < 0) { x2 = 0; } if (x2 >= im->sx) { x2 = im->sx - 1; } if (y1 < 0) { y1 = 0; } if (y1 >= im->sy) { y1 = im->sy - 1; } if (y2 < 0) { y2 = 0; } if (y2 >= im->sy) { y2 = im->sy - 1; } im->cx1 = x1; im->cy1 = y1; im->cx2 = x2; im->cy2 = y2; } /** * Function: gdImageGetClip * * Gets the current clipping rectangle * * Parameters: * im - The image. * x1P - (out) The x-coordinate of the upper left corner. * y1P - (out) The y-coordinate of the upper left corner. * x2P - (out) The x-coordinate of the lower right corner. * y2P - (out) The y-coordinate of the lower right corner. * * See also: * - <gdImageSetClip> */ BGD_DECLARE(void) gdImageGetClip (gdImagePtr im, int *x1P, int *y1P, int *x2P, int *y2P) { *x1P = im->cx1; *y1P = im->cy1; *x2P = im->cx2; *y2P = im->cy2; } /** * Function: gdImageSetResolution * * Sets the resolution of an image. * * Parameters: * im - The image. * res_x - The horizontal resolution in DPI. * res_y - The vertical resolution in DPI. * * See also: * - <gdImageResolutionX> * - <gdImageResolutionY> */ BGD_DECLARE(void) gdImageSetResolution(gdImagePtr im, const unsigned int res_x, const unsigned int res_y) { if (res_x > 0) im->res_x = res_x; if (res_y > 0) im->res_y = res_y; } /* * Added on 2003/12 by Pierre-Alain Joye (pajoye@pearfr.org) * */ #define BLEND_COLOR(a, nc, c, cc) \ nc = (cc) + (((((c) - (cc)) * (a)) + ((((c) - (cc)) * (a)) >> 8) + 0x80) >> 8); static void gdImageSetAAPixelColor(gdImagePtr im, int x, int y, int color, int t) { int dr,dg,db,p,r,g,b; /* 2.0.34: watch out for out of range calls */ if (!gdImageBoundsSafeMacro(im, x, y)) { return; } p = gdImageGetPixel(im,x,y); /* TBB: we have to implement the dont_blend stuff to provide the full feature set of the old implementation */ if ((p == color) || ((p == im->AA_dont_blend) && (t != 0x00))) { return; } dr = gdTrueColorGetRed(color); dg = gdTrueColorGetGreen(color); db = gdTrueColorGetBlue(color); r = gdTrueColorGetRed(p); g = gdTrueColorGetGreen(p); b = gdTrueColorGetBlue(p); BLEND_COLOR(t, dr, r, dr); BLEND_COLOR(t, dg, g, dg); BLEND_COLOR(t, db, b, db); im->tpixels[y][x] = gdTrueColorAlpha(dr, dg, db, gdAlphaOpaque); } static void gdImageAALine (gdImagePtr im, int x1, int y1, int x2, int y2, int col) { /* keep them as 32bits */ long x, y, inc, frac; long dx, dy,tmp; int w, wid, wstart; int thick = im->thick; if (!im->trueColor) { /* TBB: don't crash when the image is of the wrong type */ gdImageLine(im, x1, y1, x2, y2, col); return; } /* TBB: use the clipping rectangle */ if (clip_1d (&x1, &y1, &x2, &y2, im->cx1, im->cx2) == 0) return; if (clip_1d (&y1, &x1, &y2, &x2, im->cy1, im->cy2) == 0) return; dx = x2 - x1; dy = y2 - y1; if (dx == 0 && dy == 0) { /* TBB: allow setting points */ gdImageSetPixel(im, x1, y1, col); return; } else { double ag; /* Cast the long to an int to avoid compiler warnings about truncation. * This isn't a problem as computed dy/dx values came from ints above. */ ag = fabs(abs((int)dy) < abs((int)dx) ? cos(atan2(dy, dx)) : sin(atan2(dy, dx))); if (ag != 0) { wid = thick / ag; } else { wid = 1; } if (wid == 0) { wid = 1; } } /* Axis aligned lines */ if (dx == 0) { gdImageVLine(im, x1, y1, y2, col); return; } else if (dy == 0) { gdImageHLine(im, y1, x1, x2, col); return; } if (abs((int)dx) > abs((int)dy)) { if (dx < 0) { tmp = x1; x1 = x2; x2 = tmp; tmp = y1; y1 = y2; y2 = tmp; dx = x2 - x1; dy = y2 - y1; } y = y1; inc = (dy * 65536) / dx; frac = 0; /* TBB: set the last pixel for consistency (<=) */ for (x = x1 ; x <= x2 ; x++) { wstart = y - wid / 2; for (w = wstart; w < wstart + wid; w++) { gdImageSetAAPixelColor(im, x , w , col , (frac >> 8) & 0xFF); gdImageSetAAPixelColor(im, x , w + 1 , col, (~frac >> 8) & 0xFF); } frac += inc; if (frac >= 65536) { frac -= 65536; y++; } else if (frac < 0) { frac += 65536; y--; } } } else { if (dy < 0) { tmp = x1; x1 = x2; x2 = tmp; tmp = y1; y1 = y2; y2 = tmp; dx = x2 - x1; dy = y2 - y1; } x = x1; inc = (dx * 65536) / dy; frac = 0; /* TBB: set the last pixel for consistency (<=) */ for (y = y1 ; y <= y2 ; y++) { wstart = x - wid / 2; for (w = wstart; w < wstart + wid; w++) { gdImageSetAAPixelColor(im, w , y , col, (frac >> 8) & 0xFF); gdImageSetAAPixelColor(im, w + 1, y, col, (~frac >> 8) & 0xFF); } frac += inc; if (frac >= 65536) { frac -= 65536; x++; } else if (frac < 0) { frac += 65536; x--; } } } } /** * Function: gdImagePaletteToTrueColor * * Convert a palette image to true color * * Parameters: * src - The image. * * Returns: * Non-zero if the conversion succeeded, zero otherwise. * * See also: * - <gdImageTrueColorToPalette> */ BGD_DECLARE(int) gdImagePaletteToTrueColor(gdImagePtr src) { unsigned int y; unsigned int yy; if (src == NULL) { return 0; } if (src->trueColor == 1) { return 1; } else { unsigned int x; const unsigned int sy = gdImageSY(src); const unsigned int sx = gdImageSX(src); src->tpixels = (int **) gdMalloc(sizeof(int *) * sy); if (src->tpixels == NULL) { return 0; } for (y = 0; y < sy; y++) { const unsigned char *src_row = src->pixels[y]; int * dst_row; /* no need to calloc it, we overwrite all pxl anyway */ src->tpixels[y] = (int *) gdMalloc(sx * sizeof(int)); if (src->tpixels[y] == NULL) { goto clean_on_error; } dst_row = src->tpixels[y]; for (x = 0; x < sx; x++) { const unsigned char c = *(src_row + x); if (c == src->transparent) { *(dst_row + x) = gdTrueColorAlpha(0, 0, 0, 127); } else { *(dst_row + x) = gdTrueColorAlpha(src->red[c], src->green[c], src->blue[c], src->alpha[c]); } } } } /* free old palette buffer (y is sy) */ for (yy = 0; yy < y; yy++) { gdFree(src->pixels[yy]); } gdFree(src->pixels); src->trueColor = 1; src->pixels = NULL; src->alphaBlendingFlag = 0; src->saveAlphaFlag = 1; if (src->transparent >= 0) { const unsigned char c = src->transparent; src->transparent = gdTrueColorAlpha(src->red[c], src->green[c], src->blue[c], src->alpha[c]); } return 1; clean_on_error: /* free new true color buffer (y is not allocated, have failed) */ for (yy = 0; yy < y; yy++) { gdFree(src->tpixels[yy]); } gdFree(src->tpixels); return 0; }
./CrossVul/dataset_final_sorted/CWE-20/c/good_5411_0
crossvul-cpp_data_bad_5845_22
/* * 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. * * Copyright Jonathan Naylor G4KLX (g4klx@g4klx.demon.co.uk) * Copyright Alan Cox GW4PTS (alan@lxorguk.ukuu.org.uk) * Copyright Darryl Miles G7LED (dlm@g7led.demon.co.uk) */ #include <linux/module.h> #include <linux/moduleparam.h> #include <linux/capability.h> #include <linux/errno.h> #include <linux/types.h> #include <linux/socket.h> #include <linux/in.h> #include <linux/slab.h> #include <linux/kernel.h> #include <linux/sched.h> #include <linux/timer.h> #include <linux/string.h> #include <linux/sockios.h> #include <linux/net.h> #include <linux/stat.h> #include <net/ax25.h> #include <linux/inet.h> #include <linux/netdevice.h> #include <linux/if_arp.h> #include <linux/skbuff.h> #include <net/net_namespace.h> #include <net/sock.h> #include <asm/uaccess.h> #include <linux/fcntl.h> #include <linux/termios.h> /* For TIOCINQ/OUTQ */ #include <linux/mm.h> #include <linux/interrupt.h> #include <linux/notifier.h> #include <net/netrom.h> #include <linux/proc_fs.h> #include <linux/seq_file.h> #include <net/ip.h> #include <net/tcp_states.h> #include <net/arp.h> #include <linux/init.h> static int nr_ndevs = 4; int sysctl_netrom_default_path_quality = NR_DEFAULT_QUAL; int sysctl_netrom_obsolescence_count_initialiser = NR_DEFAULT_OBS; int sysctl_netrom_network_ttl_initialiser = NR_DEFAULT_TTL; int sysctl_netrom_transport_timeout = NR_DEFAULT_T1; int sysctl_netrom_transport_maximum_tries = NR_DEFAULT_N2; int sysctl_netrom_transport_acknowledge_delay = NR_DEFAULT_T2; int sysctl_netrom_transport_busy_delay = NR_DEFAULT_T4; int sysctl_netrom_transport_requested_window_size = NR_DEFAULT_WINDOW; int sysctl_netrom_transport_no_activity_timeout = NR_DEFAULT_IDLE; int sysctl_netrom_routing_control = NR_DEFAULT_ROUTING; int sysctl_netrom_link_fails_count = NR_DEFAULT_FAILS; int sysctl_netrom_reset_circuit = NR_DEFAULT_RESET; static unsigned short circuit = 0x101; static HLIST_HEAD(nr_list); static DEFINE_SPINLOCK(nr_list_lock); static const struct proto_ops nr_proto_ops; /* * NETROM network devices are virtual network devices encapsulating NETROM * frames into AX.25 which will be sent through an AX.25 device, so form a * special "super class" of normal net devices; split their locks off into a * separate class since they always nest. */ static struct lock_class_key nr_netdev_xmit_lock_key; static struct lock_class_key nr_netdev_addr_lock_key; static void nr_set_lockdep_one(struct net_device *dev, struct netdev_queue *txq, void *_unused) { lockdep_set_class(&txq->_xmit_lock, &nr_netdev_xmit_lock_key); } static void nr_set_lockdep_key(struct net_device *dev) { lockdep_set_class(&dev->addr_list_lock, &nr_netdev_addr_lock_key); netdev_for_each_tx_queue(dev, nr_set_lockdep_one, NULL); } /* * Socket removal during an interrupt is now safe. */ static void nr_remove_socket(struct sock *sk) { spin_lock_bh(&nr_list_lock); sk_del_node_init(sk); spin_unlock_bh(&nr_list_lock); } /* * Kill all bound sockets on a dropped device. */ static void nr_kill_by_device(struct net_device *dev) { struct sock *s; spin_lock_bh(&nr_list_lock); sk_for_each(s, &nr_list) if (nr_sk(s)->device == dev) nr_disconnect(s, ENETUNREACH); spin_unlock_bh(&nr_list_lock); } /* * Handle device status changes. */ static int nr_device_event(struct notifier_block *this, unsigned long event, void *ptr) { struct net_device *dev = netdev_notifier_info_to_dev(ptr); if (!net_eq(dev_net(dev), &init_net)) return NOTIFY_DONE; if (event != NETDEV_DOWN) return NOTIFY_DONE; nr_kill_by_device(dev); nr_rt_device_down(dev); return NOTIFY_DONE; } /* * Add a socket to the bound sockets list. */ static void nr_insert_socket(struct sock *sk) { spin_lock_bh(&nr_list_lock); sk_add_node(sk, &nr_list); spin_unlock_bh(&nr_list_lock); } /* * Find a socket that wants to accept the Connect Request we just * received. */ static struct sock *nr_find_listener(ax25_address *addr) { struct sock *s; spin_lock_bh(&nr_list_lock); sk_for_each(s, &nr_list) if (!ax25cmp(&nr_sk(s)->source_addr, addr) && s->sk_state == TCP_LISTEN) { bh_lock_sock(s); goto found; } s = NULL; found: spin_unlock_bh(&nr_list_lock); return s; } /* * Find a connected NET/ROM socket given my circuit IDs. */ static struct sock *nr_find_socket(unsigned char index, unsigned char id) { struct sock *s; spin_lock_bh(&nr_list_lock); sk_for_each(s, &nr_list) { struct nr_sock *nr = nr_sk(s); if (nr->my_index == index && nr->my_id == id) { bh_lock_sock(s); goto found; } } s = NULL; found: spin_unlock_bh(&nr_list_lock); return s; } /* * Find a connected NET/ROM socket given their circuit IDs. */ static struct sock *nr_find_peer(unsigned char index, unsigned char id, ax25_address *dest) { struct sock *s; spin_lock_bh(&nr_list_lock); sk_for_each(s, &nr_list) { struct nr_sock *nr = nr_sk(s); if (nr->your_index == index && nr->your_id == id && !ax25cmp(&nr->dest_addr, dest)) { bh_lock_sock(s); goto found; } } s = NULL; found: spin_unlock_bh(&nr_list_lock); return s; } /* * Find next free circuit ID. */ static unsigned short nr_find_next_circuit(void) { unsigned short id = circuit; unsigned char i, j; struct sock *sk; for (;;) { i = id / 256; j = id % 256; if (i != 0 && j != 0) { if ((sk=nr_find_socket(i, j)) == NULL) break; bh_unlock_sock(sk); } id++; } return id; } /* * Deferred destroy. */ void nr_destroy_socket(struct sock *); /* * Handler for deferred kills. */ static void nr_destroy_timer(unsigned long data) { struct sock *sk=(struct sock *)data; bh_lock_sock(sk); sock_hold(sk); nr_destroy_socket(sk); bh_unlock_sock(sk); sock_put(sk); } /* * This is called from user mode and the timers. Thus it protects itself * against interrupt users but doesn't worry about being called during * work. Once it is removed from the queue no interrupt or bottom half * will touch it and we are (fairly 8-) ) safe. */ void nr_destroy_socket(struct sock *sk) { struct sk_buff *skb; nr_remove_socket(sk); nr_stop_heartbeat(sk); nr_stop_t1timer(sk); nr_stop_t2timer(sk); nr_stop_t4timer(sk); nr_stop_idletimer(sk); nr_clear_queues(sk); /* Flush the queues */ while ((skb = skb_dequeue(&sk->sk_receive_queue)) != NULL) { if (skb->sk != sk) { /* A pending connection */ /* Queue the unaccepted socket for death */ sock_set_flag(skb->sk, SOCK_DEAD); nr_start_heartbeat(skb->sk); nr_sk(skb->sk)->state = NR_STATE_0; } kfree_skb(skb); } if (sk_has_allocations(sk)) { /* Defer: outstanding buffers */ sk->sk_timer.function = nr_destroy_timer; sk->sk_timer.expires = jiffies + 2 * HZ; add_timer(&sk->sk_timer); } else sock_put(sk); } /* * Handling for system calls applied via the various interfaces to a * NET/ROM socket object. */ static int nr_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen) { struct sock *sk = sock->sk; struct nr_sock *nr = nr_sk(sk); unsigned long opt; if (level != SOL_NETROM) return -ENOPROTOOPT; if (optlen < sizeof(unsigned int)) return -EINVAL; if (get_user(opt, (unsigned int __user *)optval)) return -EFAULT; switch (optname) { case NETROM_T1: if (opt < 1 || opt > ULONG_MAX / HZ) return -EINVAL; nr->t1 = opt * HZ; return 0; case NETROM_T2: if (opt < 1 || opt > ULONG_MAX / HZ) return -EINVAL; nr->t2 = opt * HZ; return 0; case NETROM_N2: if (opt < 1 || opt > 31) return -EINVAL; nr->n2 = opt; return 0; case NETROM_T4: if (opt < 1 || opt > ULONG_MAX / HZ) return -EINVAL; nr->t4 = opt * HZ; return 0; case NETROM_IDLE: if (opt > ULONG_MAX / (60 * HZ)) return -EINVAL; nr->idle = opt * 60 * HZ; return 0; default: return -ENOPROTOOPT; } } static int nr_getsockopt(struct socket *sock, int level, int optname, char __user *optval, int __user *optlen) { struct sock *sk = sock->sk; struct nr_sock *nr = nr_sk(sk); int val = 0; int len; if (level != SOL_NETROM) return -ENOPROTOOPT; if (get_user(len, optlen)) return -EFAULT; if (len < 0) return -EINVAL; switch (optname) { case NETROM_T1: val = nr->t1 / HZ; break; case NETROM_T2: val = nr->t2 / HZ; break; case NETROM_N2: val = nr->n2; break; case NETROM_T4: val = nr->t4 / HZ; break; case NETROM_IDLE: val = nr->idle / (60 * HZ); break; default: return -ENOPROTOOPT; } len = min_t(unsigned int, len, sizeof(int)); if (put_user(len, optlen)) return -EFAULT; return copy_to_user(optval, &val, len) ? -EFAULT : 0; } static int nr_listen(struct socket *sock, int backlog) { struct sock *sk = sock->sk; lock_sock(sk); if (sk->sk_state != TCP_LISTEN) { memset(&nr_sk(sk)->user_addr, 0, AX25_ADDR_LEN); sk->sk_max_ack_backlog = backlog; sk->sk_state = TCP_LISTEN; release_sock(sk); return 0; } release_sock(sk); return -EOPNOTSUPP; } static struct proto nr_proto = { .name = "NETROM", .owner = THIS_MODULE, .obj_size = sizeof(struct nr_sock), }; static int nr_create(struct net *net, struct socket *sock, int protocol, int kern) { struct sock *sk; struct nr_sock *nr; if (!net_eq(net, &init_net)) return -EAFNOSUPPORT; if (sock->type != SOCK_SEQPACKET || protocol != 0) return -ESOCKTNOSUPPORT; sk = sk_alloc(net, PF_NETROM, GFP_ATOMIC, &nr_proto); if (sk == NULL) return -ENOMEM; nr = nr_sk(sk); sock_init_data(sock, sk); sock->ops = &nr_proto_ops; sk->sk_protocol = protocol; skb_queue_head_init(&nr->ack_queue); skb_queue_head_init(&nr->reseq_queue); skb_queue_head_init(&nr->frag_queue); nr_init_timers(sk); nr->t1 = msecs_to_jiffies(sysctl_netrom_transport_timeout); nr->t2 = msecs_to_jiffies(sysctl_netrom_transport_acknowledge_delay); nr->n2 = msecs_to_jiffies(sysctl_netrom_transport_maximum_tries); nr->t4 = msecs_to_jiffies(sysctl_netrom_transport_busy_delay); nr->idle = msecs_to_jiffies(sysctl_netrom_transport_no_activity_timeout); nr->window = sysctl_netrom_transport_requested_window_size; nr->bpqext = 1; nr->state = NR_STATE_0; return 0; } static struct sock *nr_make_new(struct sock *osk) { struct sock *sk; struct nr_sock *nr, *onr; if (osk->sk_type != SOCK_SEQPACKET) return NULL; sk = sk_alloc(sock_net(osk), PF_NETROM, GFP_ATOMIC, osk->sk_prot); if (sk == NULL) return NULL; nr = nr_sk(sk); sock_init_data(NULL, sk); sk->sk_type = osk->sk_type; sk->sk_priority = osk->sk_priority; sk->sk_protocol = osk->sk_protocol; sk->sk_rcvbuf = osk->sk_rcvbuf; sk->sk_sndbuf = osk->sk_sndbuf; sk->sk_state = TCP_ESTABLISHED; sock_copy_flags(sk, osk); skb_queue_head_init(&nr->ack_queue); skb_queue_head_init(&nr->reseq_queue); skb_queue_head_init(&nr->frag_queue); nr_init_timers(sk); onr = nr_sk(osk); nr->t1 = onr->t1; nr->t2 = onr->t2; nr->n2 = onr->n2; nr->t4 = onr->t4; nr->idle = onr->idle; nr->window = onr->window; nr->device = onr->device; nr->bpqext = onr->bpqext; return sk; } static int nr_release(struct socket *sock) { struct sock *sk = sock->sk; struct nr_sock *nr; if (sk == NULL) return 0; sock_hold(sk); sock_orphan(sk); lock_sock(sk); nr = nr_sk(sk); switch (nr->state) { case NR_STATE_0: case NR_STATE_1: case NR_STATE_2: nr_disconnect(sk, 0); nr_destroy_socket(sk); break; case NR_STATE_3: nr_clear_queues(sk); nr->n2count = 0; nr_write_internal(sk, NR_DISCREQ); nr_start_t1timer(sk); nr_stop_t2timer(sk); nr_stop_t4timer(sk); nr_stop_idletimer(sk); nr->state = NR_STATE_2; sk->sk_state = TCP_CLOSE; sk->sk_shutdown |= SEND_SHUTDOWN; sk->sk_state_change(sk); sock_set_flag(sk, SOCK_DESTROY); break; default: break; } sock->sk = NULL; release_sock(sk); sock_put(sk); return 0; } static int nr_bind(struct socket *sock, struct sockaddr *uaddr, int addr_len) { struct sock *sk = sock->sk; struct nr_sock *nr = nr_sk(sk); struct full_sockaddr_ax25 *addr = (struct full_sockaddr_ax25 *)uaddr; struct net_device *dev; ax25_uid_assoc *user; ax25_address *source; lock_sock(sk); if (!sock_flag(sk, SOCK_ZAPPED)) { release_sock(sk); return -EINVAL; } if (addr_len < sizeof(struct sockaddr_ax25) || addr_len > sizeof(struct full_sockaddr_ax25)) { release_sock(sk); return -EINVAL; } if (addr_len < (addr->fsa_ax25.sax25_ndigis * sizeof(ax25_address) + sizeof(struct sockaddr_ax25))) { release_sock(sk); return -EINVAL; } if (addr->fsa_ax25.sax25_family != AF_NETROM) { release_sock(sk); return -EINVAL; } if ((dev = nr_dev_get(&addr->fsa_ax25.sax25_call)) == NULL) { release_sock(sk); return -EADDRNOTAVAIL; } /* * Only the super user can set an arbitrary user callsign. */ if (addr->fsa_ax25.sax25_ndigis == 1) { if (!capable(CAP_NET_BIND_SERVICE)) { dev_put(dev); release_sock(sk); return -EPERM; } nr->user_addr = addr->fsa_digipeater[0]; nr->source_addr = addr->fsa_ax25.sax25_call; } else { source = &addr->fsa_ax25.sax25_call; user = ax25_findbyuid(current_euid()); if (user) { nr->user_addr = user->call; ax25_uid_put(user); } else { if (ax25_uid_policy && !capable(CAP_NET_BIND_SERVICE)) { release_sock(sk); dev_put(dev); return -EPERM; } nr->user_addr = *source; } nr->source_addr = *source; } nr->device = dev; nr_insert_socket(sk); sock_reset_flag(sk, SOCK_ZAPPED); dev_put(dev); release_sock(sk); return 0; } static int nr_connect(struct socket *sock, struct sockaddr *uaddr, int addr_len, int flags) { struct sock *sk = sock->sk; struct nr_sock *nr = nr_sk(sk); struct sockaddr_ax25 *addr = (struct sockaddr_ax25 *)uaddr; ax25_address *source = NULL; ax25_uid_assoc *user; struct net_device *dev; int err = 0; lock_sock(sk); if (sk->sk_state == TCP_ESTABLISHED && sock->state == SS_CONNECTING) { sock->state = SS_CONNECTED; goto out_release; /* Connect completed during a ERESTARTSYS event */ } if (sk->sk_state == TCP_CLOSE && sock->state == SS_CONNECTING) { sock->state = SS_UNCONNECTED; err = -ECONNREFUSED; goto out_release; } if (sk->sk_state == TCP_ESTABLISHED) { err = -EISCONN; /* No reconnect on a seqpacket socket */ goto out_release; } sk->sk_state = TCP_CLOSE; sock->state = SS_UNCONNECTED; if (addr_len != sizeof(struct sockaddr_ax25) && addr_len != sizeof(struct full_sockaddr_ax25)) { err = -EINVAL; goto out_release; } if (addr->sax25_family != AF_NETROM) { err = -EINVAL; goto out_release; } if (sock_flag(sk, SOCK_ZAPPED)) { /* Must bind first - autobinding in this may or may not work */ sock_reset_flag(sk, SOCK_ZAPPED); if ((dev = nr_dev_first()) == NULL) { err = -ENETUNREACH; goto out_release; } source = (ax25_address *)dev->dev_addr; user = ax25_findbyuid(current_euid()); if (user) { nr->user_addr = user->call; ax25_uid_put(user); } else { if (ax25_uid_policy && !capable(CAP_NET_ADMIN)) { dev_put(dev); err = -EPERM; goto out_release; } nr->user_addr = *source; } nr->source_addr = *source; nr->device = dev; dev_put(dev); nr_insert_socket(sk); /* Finish the bind */ } nr->dest_addr = addr->sax25_call; release_sock(sk); circuit = nr_find_next_circuit(); lock_sock(sk); nr->my_index = circuit / 256; nr->my_id = circuit % 256; circuit++; /* Move to connecting socket, start sending Connect Requests */ sock->state = SS_CONNECTING; sk->sk_state = TCP_SYN_SENT; nr_establish_data_link(sk); nr->state = NR_STATE_1; nr_start_heartbeat(sk); /* Now the loop */ if (sk->sk_state != TCP_ESTABLISHED && (flags & O_NONBLOCK)) { err = -EINPROGRESS; goto out_release; } /* * A Connect Ack with Choke or timeout or failed routing will go to * closed. */ if (sk->sk_state == TCP_SYN_SENT) { DEFINE_WAIT(wait); for (;;) { prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE); if (sk->sk_state != TCP_SYN_SENT) break; if (!signal_pending(current)) { release_sock(sk); schedule(); lock_sock(sk); continue; } err = -ERESTARTSYS; break; } finish_wait(sk_sleep(sk), &wait); if (err) goto out_release; } if (sk->sk_state != TCP_ESTABLISHED) { sock->state = SS_UNCONNECTED; err = sock_error(sk); /* Always set at this point */ goto out_release; } sock->state = SS_CONNECTED; out_release: release_sock(sk); return err; } static int nr_accept(struct socket *sock, struct socket *newsock, int flags) { struct sk_buff *skb; struct sock *newsk; DEFINE_WAIT(wait); struct sock *sk; int err = 0; if ((sk = sock->sk) == NULL) return -EINVAL; lock_sock(sk); if (sk->sk_type != SOCK_SEQPACKET) { err = -EOPNOTSUPP; goto out_release; } if (sk->sk_state != TCP_LISTEN) { err = -EINVAL; goto out_release; } /* * The write queue this time is holding sockets ready to use * hooked into the SABM we saved */ for (;;) { prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE); skb = skb_dequeue(&sk->sk_receive_queue); if (skb) break; if (flags & O_NONBLOCK) { err = -EWOULDBLOCK; break; } if (!signal_pending(current)) { release_sock(sk); schedule(); lock_sock(sk); continue; } err = -ERESTARTSYS; break; } finish_wait(sk_sleep(sk), &wait); if (err) goto out_release; newsk = skb->sk; sock_graft(newsk, newsock); /* Now attach up the new socket */ kfree_skb(skb); sk_acceptq_removed(sk); out_release: release_sock(sk); return err; } static int nr_getname(struct socket *sock, struct sockaddr *uaddr, int *uaddr_len, int peer) { struct full_sockaddr_ax25 *sax = (struct full_sockaddr_ax25 *)uaddr; struct sock *sk = sock->sk; struct nr_sock *nr = nr_sk(sk); memset(&sax->fsa_ax25, 0, sizeof(struct sockaddr_ax25)); lock_sock(sk); if (peer != 0) { if (sk->sk_state != TCP_ESTABLISHED) { release_sock(sk); return -ENOTCONN; } sax->fsa_ax25.sax25_family = AF_NETROM; sax->fsa_ax25.sax25_ndigis = 1; sax->fsa_ax25.sax25_call = nr->user_addr; memset(sax->fsa_digipeater, 0, sizeof(sax->fsa_digipeater)); sax->fsa_digipeater[0] = nr->dest_addr; *uaddr_len = sizeof(struct full_sockaddr_ax25); } else { sax->fsa_ax25.sax25_family = AF_NETROM; sax->fsa_ax25.sax25_ndigis = 0; sax->fsa_ax25.sax25_call = nr->source_addr; *uaddr_len = sizeof(struct sockaddr_ax25); } release_sock(sk); return 0; } int nr_rx_frame(struct sk_buff *skb, struct net_device *dev) { struct sock *sk; struct sock *make; struct nr_sock *nr_make; ax25_address *src, *dest, *user; unsigned short circuit_index, circuit_id; unsigned short peer_circuit_index, peer_circuit_id; unsigned short frametype, flags, window, timeout; int ret; skb->sk = NULL; /* Initially we don't know who it's for */ /* * skb->data points to the netrom frame start */ src = (ax25_address *)(skb->data + 0); dest = (ax25_address *)(skb->data + 7); circuit_index = skb->data[15]; circuit_id = skb->data[16]; peer_circuit_index = skb->data[17]; peer_circuit_id = skb->data[18]; frametype = skb->data[19] & 0x0F; flags = skb->data[19] & 0xF0; /* * Check for an incoming IP over NET/ROM frame. */ if (frametype == NR_PROTOEXT && circuit_index == NR_PROTO_IP && circuit_id == NR_PROTO_IP) { skb_pull(skb, NR_NETWORK_LEN + NR_TRANSPORT_LEN); skb_reset_transport_header(skb); return nr_rx_ip(skb, dev); } /* * Find an existing socket connection, based on circuit ID, if it's * a Connect Request base it on their circuit ID. * * Circuit ID 0/0 is not valid but it could still be a "reset" for a * circuit that no longer exists at the other end ... */ sk = NULL; if (circuit_index == 0 && circuit_id == 0) { if (frametype == NR_CONNACK && flags == NR_CHOKE_FLAG) sk = nr_find_peer(peer_circuit_index, peer_circuit_id, src); } else { if (frametype == NR_CONNREQ) sk = nr_find_peer(circuit_index, circuit_id, src); else sk = nr_find_socket(circuit_index, circuit_id); } if (sk != NULL) { skb_reset_transport_header(skb); if (frametype == NR_CONNACK && skb->len == 22) nr_sk(sk)->bpqext = 1; else nr_sk(sk)->bpqext = 0; ret = nr_process_rx_frame(sk, skb); bh_unlock_sock(sk); return ret; } /* * Now it should be a CONNREQ. */ if (frametype != NR_CONNREQ) { /* * Here it would be nice to be able to send a reset but * NET/ROM doesn't have one. We've tried to extend the protocol * by sending NR_CONNACK | NR_CHOKE_FLAGS replies but that * apparently kills BPQ boxes... :-( * So now we try to follow the established behaviour of * G8PZT's Xrouter which is sending packets with command type 7 * as an extension of the protocol. */ if (sysctl_netrom_reset_circuit && (frametype != NR_RESET || flags != 0)) nr_transmit_reset(skb, 1); return 0; } sk = nr_find_listener(dest); user = (ax25_address *)(skb->data + 21); if (sk == NULL || sk_acceptq_is_full(sk) || (make = nr_make_new(sk)) == NULL) { nr_transmit_refusal(skb, 0); if (sk) bh_unlock_sock(sk); return 0; } window = skb->data[20]; skb->sk = make; make->sk_state = TCP_ESTABLISHED; /* Fill in his circuit details */ nr_make = nr_sk(make); nr_make->source_addr = *dest; nr_make->dest_addr = *src; nr_make->user_addr = *user; nr_make->your_index = circuit_index; nr_make->your_id = circuit_id; bh_unlock_sock(sk); circuit = nr_find_next_circuit(); bh_lock_sock(sk); nr_make->my_index = circuit / 256; nr_make->my_id = circuit % 256; circuit++; /* Window negotiation */ if (window < nr_make->window) nr_make->window = window; /* L4 timeout negotiation */ if (skb->len == 37) { timeout = skb->data[36] * 256 + skb->data[35]; if (timeout * HZ < nr_make->t1) nr_make->t1 = timeout * HZ; nr_make->bpqext = 1; } else { nr_make->bpqext = 0; } nr_write_internal(make, NR_CONNACK); nr_make->condition = 0x00; nr_make->vs = 0; nr_make->va = 0; nr_make->vr = 0; nr_make->vl = 0; nr_make->state = NR_STATE_3; sk_acceptq_added(sk); skb_queue_head(&sk->sk_receive_queue, skb); if (!sock_flag(sk, SOCK_DEAD)) sk->sk_data_ready(sk, skb->len); bh_unlock_sock(sk); nr_insert_socket(make); nr_start_heartbeat(make); nr_start_idletimer(make); return 1; } static int nr_sendmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t len) { struct sock *sk = sock->sk; struct nr_sock *nr = nr_sk(sk); struct sockaddr_ax25 *usax = (struct sockaddr_ax25 *)msg->msg_name; int err; struct sockaddr_ax25 sax; struct sk_buff *skb; unsigned char *asmptr; int size; if (msg->msg_flags & ~(MSG_DONTWAIT|MSG_EOR|MSG_CMSG_COMPAT)) return -EINVAL; lock_sock(sk); if (sock_flag(sk, SOCK_ZAPPED)) { err = -EADDRNOTAVAIL; goto out; } if (sk->sk_shutdown & SEND_SHUTDOWN) { send_sig(SIGPIPE, current, 0); err = -EPIPE; goto out; } if (nr->device == NULL) { err = -ENETUNREACH; goto out; } if (usax) { if (msg->msg_namelen < sizeof(sax)) { err = -EINVAL; goto out; } sax = *usax; if (ax25cmp(&nr->dest_addr, &sax.sax25_call) != 0) { err = -EISCONN; goto out; } if (sax.sax25_family != AF_NETROM) { err = -EINVAL; goto out; } } else { if (sk->sk_state != TCP_ESTABLISHED) { err = -ENOTCONN; goto out; } sax.sax25_family = AF_NETROM; sax.sax25_call = nr->dest_addr; } /* Build a packet - the conventional user limit is 236 bytes. We can do ludicrously large NetROM frames but must not overflow */ if (len > 65536) { err = -EMSGSIZE; goto out; } size = len + NR_NETWORK_LEN + NR_TRANSPORT_LEN; if ((skb = sock_alloc_send_skb(sk, size, msg->msg_flags & MSG_DONTWAIT, &err)) == NULL) goto out; skb_reserve(skb, size - len); skb_reset_transport_header(skb); /* * Push down the NET/ROM header */ asmptr = skb_push(skb, NR_TRANSPORT_LEN); /* Build a NET/ROM Transport header */ *asmptr++ = nr->your_index; *asmptr++ = nr->your_id; *asmptr++ = 0; /* To be filled in later */ *asmptr++ = 0; /* Ditto */ *asmptr++ = NR_INFO; /* * Put the data on the end */ skb_put(skb, len); /* User data follows immediately after the NET/ROM transport header */ if (memcpy_fromiovec(skb_transport_header(skb), msg->msg_iov, len)) { kfree_skb(skb); err = -EFAULT; goto out; } if (sk->sk_state != TCP_ESTABLISHED) { kfree_skb(skb); err = -ENOTCONN; goto out; } nr_output(sk, skb); /* Shove it onto the queue */ err = len; out: release_sock(sk); return err; } static int nr_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t size, int flags) { struct sock *sk = sock->sk; struct sockaddr_ax25 *sax = (struct sockaddr_ax25 *)msg->msg_name; size_t copied; struct sk_buff *skb; int er; /* * This works for seqpacket too. The receiver has ordered the queue for * us! We do one quick check first though */ lock_sock(sk); if (sk->sk_state != TCP_ESTABLISHED) { release_sock(sk); return -ENOTCONN; } /* Now we can treat all alike */ if ((skb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT, flags & MSG_DONTWAIT, &er)) == NULL) { release_sock(sk); return er; } skb_reset_transport_header(skb); copied = skb->len; if (copied > size) { copied = size; msg->msg_flags |= MSG_TRUNC; } er = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied); if (er < 0) { skb_free_datagram(sk, skb); release_sock(sk); return er; } if (sax != NULL) { memset(sax, 0, sizeof(*sax)); sax->sax25_family = AF_NETROM; skb_copy_from_linear_data_offset(skb, 7, sax->sax25_call.ax25_call, AX25_ADDR_LEN); } msg->msg_namelen = sizeof(*sax); skb_free_datagram(sk, skb); release_sock(sk); return copied; } static int nr_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg) { struct sock *sk = sock->sk; void __user *argp = (void __user *)arg; int ret; switch (cmd) { case TIOCOUTQ: { long amount; lock_sock(sk); amount = sk->sk_sndbuf - sk_wmem_alloc_get(sk); if (amount < 0) amount = 0; release_sock(sk); return put_user(amount, (int __user *)argp); } case TIOCINQ: { struct sk_buff *skb; long amount = 0L; lock_sock(sk); /* These two are safe on a single CPU system as only user tasks fiddle here */ if ((skb = skb_peek(&sk->sk_receive_queue)) != NULL) amount = skb->len; release_sock(sk); return put_user(amount, (int __user *)argp); } case SIOCGSTAMP: lock_sock(sk); ret = sock_get_timestamp(sk, argp); release_sock(sk); return ret; case SIOCGSTAMPNS: lock_sock(sk); ret = sock_get_timestampns(sk, argp); release_sock(sk); return ret; case SIOCGIFADDR: case SIOCSIFADDR: case SIOCGIFDSTADDR: case SIOCSIFDSTADDR: case SIOCGIFBRDADDR: case SIOCSIFBRDADDR: case SIOCGIFNETMASK: case SIOCSIFNETMASK: case SIOCGIFMETRIC: case SIOCSIFMETRIC: return -EINVAL; case SIOCADDRT: case SIOCDELRT: case SIOCNRDECOBS: if (!capable(CAP_NET_ADMIN)) return -EPERM; return nr_rt_ioctl(cmd, argp); default: return -ENOIOCTLCMD; } return 0; } #ifdef CONFIG_PROC_FS static void *nr_info_start(struct seq_file *seq, loff_t *pos) { spin_lock_bh(&nr_list_lock); return seq_hlist_start_head(&nr_list, *pos); } static void *nr_info_next(struct seq_file *seq, void *v, loff_t *pos) { return seq_hlist_next(v, &nr_list, pos); } static void nr_info_stop(struct seq_file *seq, void *v) { spin_unlock_bh(&nr_list_lock); } static int nr_info_show(struct seq_file *seq, void *v) { struct sock *s = sk_entry(v); struct net_device *dev; struct nr_sock *nr; const char *devname; char buf[11]; if (v == SEQ_START_TOKEN) seq_puts(seq, "user_addr dest_node src_node dev my your st vs vr va t1 t2 t4 idle n2 wnd Snd-Q Rcv-Q inode\n"); else { bh_lock_sock(s); nr = nr_sk(s); if ((dev = nr->device) == NULL) devname = "???"; else devname = dev->name; seq_printf(seq, "%-9s ", ax2asc(buf, &nr->user_addr)); seq_printf(seq, "%-9s ", ax2asc(buf, &nr->dest_addr)); seq_printf(seq, "%-9s %-3s %02X/%02X %02X/%02X %2d %3d %3d %3d %3lu/%03lu %2lu/%02lu %3lu/%03lu %3lu/%03lu %2d/%02d %3d %5d %5d %ld\n", ax2asc(buf, &nr->source_addr), devname, nr->my_index, nr->my_id, nr->your_index, nr->your_id, nr->state, nr->vs, nr->vr, nr->va, ax25_display_timer(&nr->t1timer) / HZ, nr->t1 / HZ, ax25_display_timer(&nr->t2timer) / HZ, nr->t2 / HZ, ax25_display_timer(&nr->t4timer) / HZ, nr->t4 / HZ, ax25_display_timer(&nr->idletimer) / (60 * HZ), nr->idle / (60 * HZ), nr->n2count, nr->n2, nr->window, sk_wmem_alloc_get(s), sk_rmem_alloc_get(s), s->sk_socket ? SOCK_INODE(s->sk_socket)->i_ino : 0L); bh_unlock_sock(s); } return 0; } static const struct seq_operations nr_info_seqops = { .start = nr_info_start, .next = nr_info_next, .stop = nr_info_stop, .show = nr_info_show, }; static int nr_info_open(struct inode *inode, struct file *file) { return seq_open(file, &nr_info_seqops); } static const struct file_operations nr_info_fops = { .owner = THIS_MODULE, .open = nr_info_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release, }; #endif /* CONFIG_PROC_FS */ static const struct net_proto_family nr_family_ops = { .family = PF_NETROM, .create = nr_create, .owner = THIS_MODULE, }; static const struct proto_ops nr_proto_ops = { .family = PF_NETROM, .owner = THIS_MODULE, .release = nr_release, .bind = nr_bind, .connect = nr_connect, .socketpair = sock_no_socketpair, .accept = nr_accept, .getname = nr_getname, .poll = datagram_poll, .ioctl = nr_ioctl, .listen = nr_listen, .shutdown = sock_no_shutdown, .setsockopt = nr_setsockopt, .getsockopt = nr_getsockopt, .sendmsg = nr_sendmsg, .recvmsg = nr_recvmsg, .mmap = sock_no_mmap, .sendpage = sock_no_sendpage, }; static struct notifier_block nr_dev_notifier = { .notifier_call = nr_device_event, }; static struct net_device **dev_nr; static struct ax25_protocol nr_pid = { .pid = AX25_P_NETROM, .func = nr_route_frame }; static struct ax25_linkfail nr_linkfail_notifier = { .func = nr_link_failed, }; static int __init nr_proto_init(void) { int i; int rc = proto_register(&nr_proto, 0); if (rc != 0) goto out; if (nr_ndevs > 0x7fffffff/sizeof(struct net_device *)) { printk(KERN_ERR "NET/ROM: nr_proto_init - nr_ndevs parameter to large\n"); return -1; } dev_nr = kzalloc(nr_ndevs * sizeof(struct net_device *), GFP_KERNEL); if (dev_nr == NULL) { printk(KERN_ERR "NET/ROM: nr_proto_init - unable to allocate device array\n"); return -1; } for (i = 0; i < nr_ndevs; i++) { char name[IFNAMSIZ]; struct net_device *dev; sprintf(name, "nr%d", i); dev = alloc_netdev(0, name, nr_setup); if (!dev) { printk(KERN_ERR "NET/ROM: nr_proto_init - unable to allocate device structure\n"); goto fail; } dev->base_addr = i; if (register_netdev(dev)) { printk(KERN_ERR "NET/ROM: nr_proto_init - unable to register network device\n"); free_netdev(dev); goto fail; } nr_set_lockdep_key(dev); dev_nr[i] = dev; } if (sock_register(&nr_family_ops)) { printk(KERN_ERR "NET/ROM: nr_proto_init - unable to register socket family\n"); goto fail; } register_netdevice_notifier(&nr_dev_notifier); ax25_register_pid(&nr_pid); ax25_linkfail_register(&nr_linkfail_notifier); #ifdef CONFIG_SYSCTL nr_register_sysctl(); #endif nr_loopback_init(); proc_create("nr", S_IRUGO, init_net.proc_net, &nr_info_fops); proc_create("nr_neigh", S_IRUGO, init_net.proc_net, &nr_neigh_fops); proc_create("nr_nodes", S_IRUGO, init_net.proc_net, &nr_nodes_fops); out: return rc; fail: while (--i >= 0) { unregister_netdev(dev_nr[i]); free_netdev(dev_nr[i]); } kfree(dev_nr); proto_unregister(&nr_proto); rc = -1; goto out; } module_init(nr_proto_init); module_param(nr_ndevs, int, 0); MODULE_PARM_DESC(nr_ndevs, "number of NET/ROM devices"); MODULE_AUTHOR("Jonathan Naylor G4KLX <g4klx@g4klx.demon.co.uk>"); MODULE_DESCRIPTION("The amateur radio NET/ROM network and transport layer protocol"); MODULE_LICENSE("GPL"); MODULE_ALIAS_NETPROTO(PF_NETROM); static void __exit nr_exit(void) { int i; remove_proc_entry("nr", init_net.proc_net); remove_proc_entry("nr_neigh", init_net.proc_net); remove_proc_entry("nr_nodes", init_net.proc_net); nr_loopback_clear(); nr_rt_free(); #ifdef CONFIG_SYSCTL nr_unregister_sysctl(); #endif ax25_linkfail_release(&nr_linkfail_notifier); ax25_protocol_release(AX25_P_NETROM); unregister_netdevice_notifier(&nr_dev_notifier); sock_unregister(PF_NETROM); for (i = 0; i < nr_ndevs; i++) { struct net_device *dev = dev_nr[i]; if (dev) { unregister_netdev(dev); free_netdev(dev); } } kfree(dev_nr); proto_unregister(&nr_proto); } module_exit(nr_exit);
./CrossVul/dataset_final_sorted/CWE-20/c/bad_5845_22
crossvul-cpp_data_bad_1022_0
/* * Copyright (c) 2002 - 2003 * NetGroup, Politecnico di Torino (Italy) * 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 Politecnico di Torino nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include "ftmacros.h" #include "varattrs.h" #include <errno.h> // for the errno variable #include <stdlib.h> // for malloc(), free(), ... #include <string.h> // for strlen(), ... #ifdef _WIN32 #include <process.h> // for threads #else #include <unistd.h> #include <pthread.h> #include <signal.h> #include <sys/time.h> #include <sys/types.h> // for select() and such #include <pwd.h> // for password management #endif #ifdef HAVE_GETSPNAM #include <shadow.h> // for password management #endif #include <pcap.h> // for libpcap/WinPcap calls #include "fmtutils.h" #include "sockutils.h" // for socket calls #include "portability.h" #include "rpcap-protocol.h" #include "daemon.h" #include "log.h" // // Timeout, in seconds, when we're waiting for a client to send us an // authentication request; if they don't send us a request within that // interval, we drop the connection, so we don't stay stuck forever. // #define RPCAP_TIMEOUT_INIT 90 // // Timeout, in seconds, when we're waiting for an authenticated client // to send us a request, if a capture isn't in progress; if they don't // send us a request within that interval, we drop the connection, so // we don't stay stuck forever. // #define RPCAP_TIMEOUT_RUNTIME 180 // // Time, in seconds, that we wait after a failed authentication attempt // before processing the next request; this prevents a client from // rapidly trying different accounts or passwords. // #define RPCAP_SUSPEND_WRONGAUTH 1 // Parameters for the service loop. struct daemon_slpars { SOCKET sockctrl; //!< SOCKET ID of the control connection int isactive; //!< Not null if the daemon has to run in active mode int nullAuthAllowed; //!< '1' if we permit NULL authentication, '0' otherwise }; // // Data for a session managed by a thread. // It includes both a Boolean indicating whether we *have* a thread, // and a platform-dependent (UN*X vs. Windows) identifier for the // thread; on Windows, we could use an invalid handle to indicate // that we don't have a thread, but there *is* no portable "no thread" // value for a pthread_t on UN*X. // struct session { SOCKET sockctrl; SOCKET sockdata; uint8 protocol_version; pcap_t *fp; unsigned int TotCapt; int have_thread; #ifdef _WIN32 HANDLE thread; #else pthread_t thread; #endif }; // Locally defined functions static int daemon_msg_err(SOCKET sockctrl, uint32 plen); static int daemon_msg_auth_req(struct daemon_slpars *pars, uint32 plen); static int daemon_AuthUserPwd(char *username, char *password, char *errbuf); static int daemon_msg_findallif_req(uint8 ver, struct daemon_slpars *pars, uint32 plen); static int daemon_msg_open_req(uint8 ver, struct daemon_slpars *pars, uint32 plen, char *source, size_t sourcelen); static int daemon_msg_startcap_req(uint8 ver, struct daemon_slpars *pars, uint32 plen, char *source, struct session **sessionp, struct rpcap_sampling *samp_param); static int daemon_msg_endcap_req(uint8 ver, struct daemon_slpars *pars, struct session *session); static int daemon_msg_updatefilter_req(uint8 ver, struct daemon_slpars *pars, struct session *session, uint32 plen); static int daemon_unpackapplyfilter(SOCKET sockctrl, struct session *session, uint32 *plenp, char *errbuf); static int daemon_msg_stats_req(uint8 ver, struct daemon_slpars *pars, struct session *session, uint32 plen, struct pcap_stat *stats, unsigned int svrcapt); static int daemon_msg_setsampling_req(uint8 ver, struct daemon_slpars *pars, uint32 plen, struct rpcap_sampling *samp_param); static void daemon_seraddr(struct sockaddr_storage *sockaddrin, struct rpcap_sockaddr *sockaddrout); #ifdef _WIN32 static unsigned __stdcall daemon_thrdatamain(void *ptr); #else static void *daemon_thrdatamain(void *ptr); static void noop_handler(int sign); #endif static int rpcapd_recv_msg_header(SOCKET sock, struct rpcap_header *headerp); static int rpcapd_recv(SOCKET sock, char *buffer, size_t toread, uint32 *plen, char *errmsgbuf); static int rpcapd_discard(SOCKET sock, uint32 len); static void session_close(struct session *); static int is_url(const char *source); int daemon_serviceloop(SOCKET sockctrl, int isactive, char *passiveClients, int nullAuthAllowed) { struct daemon_slpars pars; // service loop parameters char errbuf[PCAP_ERRBUF_SIZE + 1]; // keeps the error string, prior to be printed char errmsgbuf[PCAP_ERRBUF_SIZE + 1]; // buffer for errors to send to the client int host_port_check_status; int nrecv; struct rpcap_header header; // RPCAP message general header uint32 plen; // payload length from header int authenticated = 0; // 1 if the client has successfully authenticated char source[PCAP_BUF_SIZE+1]; // keeps the string that contains the interface to open int got_source = 0; // 1 if we've gotten the source from an open request #ifndef _WIN32 struct sigaction action; #endif struct session *session = NULL; // struct session main variable const char *msg_type_string; // string for message type int client_told_us_to_close = 0; // 1 if the client told us to close the capture // needed to save the values of the statistics struct pcap_stat stats; unsigned int svrcapt; struct rpcap_sampling samp_param; // in case sampling has been requested // Structures needed for the select() call fd_set rfds; // set of socket descriptors we have to check struct timeval tv; // maximum time the select() can block waiting for data int retval; // select() return value *errbuf = 0; // Initialize errbuf // Set parameters structure pars.sockctrl = sockctrl; pars.isactive = isactive; // active mode pars.nullAuthAllowed = nullAuthAllowed; // // We have a connection. // // If it's a passive mode connection, check whether the connecting // host is among the ones allowed. // // In either case, we were handed a copy of the host list; free it // as soon as we're done with it. // if (pars.isactive) { // Nothing to do. free(passiveClients); passiveClients = NULL; } else { struct sockaddr_storage from; socklen_t fromlen; // // Get the address of the other end of the connection. // fromlen = sizeof(struct sockaddr_storage); if (getpeername(pars.sockctrl, (struct sockaddr *)&from, &fromlen) == -1) { sock_geterror("getpeername()", errmsgbuf, PCAP_ERRBUF_SIZE); if (rpcap_senderror(pars.sockctrl, 0, PCAP_ERR_NETW, errmsgbuf, errbuf) == -1) rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf); goto end; } // // Are they in the list of host/port combinations we allow? // host_port_check_status = sock_check_hostlist(passiveClients, RPCAP_HOSTLIST_SEP, &from, errmsgbuf, PCAP_ERRBUF_SIZE); free(passiveClients); passiveClients = NULL; if (host_port_check_status < 0) { if (host_port_check_status == -2) { // // We got an error; log it. // rpcapd_log(LOGPRIO_ERROR, "%s", errmsgbuf); } // // Sorry, we can't let you in. // if (rpcap_senderror(pars.sockctrl, 0, PCAP_ERR_HOSTNOAUTH, errmsgbuf, errbuf) == -1) rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf); goto end; } } #ifndef _WIN32 // // Catch SIGUSR1, but do nothing. We use it to interrupt the // capture thread to break it out of a loop in which it's // blocked waiting for packets to arrive. // // We don't want interrupted system calls to restart, so that // the read routine for the pcap_t gets EINTR rather than // restarting if it's blocked in a system call. // memset(&action, 0, sizeof (action)); action.sa_handler = noop_handler; action.sa_flags = 0; sigemptyset(&action.sa_mask); sigaction(SIGUSR1, &action, NULL); #endif // // The client must first authenticate; loop until they send us a // message with a version we support and credentials we accept, // they send us a close message indicating that they're giving up, // or we get a network error or other fatal error. // while (!authenticated) { // // If we're not in active mode, we use select(), with a // timeout, to wait for an authentication request; if // the timeout expires, we drop the connection, so that // a client can't just connect to us and leave us // waiting forever. // if (!pars.isactive) { FD_ZERO(&rfds); // We do not have to block here tv.tv_sec = RPCAP_TIMEOUT_INIT; tv.tv_usec = 0; FD_SET(pars.sockctrl, &rfds); retval = select(pars.sockctrl + 1, &rfds, NULL, NULL, &tv); if (retval == -1) { sock_geterror("select() failed", errmsgbuf, PCAP_ERRBUF_SIZE); if (rpcap_senderror(pars.sockctrl, 0, PCAP_ERR_NETW, errmsgbuf, errbuf) == -1) rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf); goto end; } // The timeout has expired // So, this was a fake connection. Drop it down if (retval == 0) { if (rpcap_senderror(pars.sockctrl, 0, PCAP_ERR_INITTIMEOUT, "The RPCAP initial timeout has expired", errbuf) == -1) rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf); goto end; } } // // Read the message header from the client. // nrecv = rpcapd_recv_msg_header(pars.sockctrl, &header); if (nrecv == -1) { // Fatal error. goto end; } if (nrecv == -2) { // Client closed the connection. goto end; } plen = header.plen; // // While we're in the authentication pharse, all requests // must use version 0. // if (header.ver != 0) { // // Send it back to them with their version. // if (rpcap_senderror(pars.sockctrl, header.ver, PCAP_ERR_WRONGVER, "RPCAP version in requests in the authentication phase must be 0", errbuf) == -1) { // That failed; log a message and give up. rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf); goto end; } // Discard the rest of the message and drop the // connection. (void)rpcapd_discard(pars.sockctrl, plen); goto end; } switch (header.type) { case RPCAP_MSG_AUTH_REQ: retval = daemon_msg_auth_req(&pars, plen); if (retval == -1) { // Fatal error; a message has // been logged, so just give up. goto end; } if (retval == -2) { // Non-fatal error; we sent back // an error message, so let them // try again. continue; } // OK, we're authenticated; we sent back // a reply, so start serving requests. authenticated = 1; break; case RPCAP_MSG_CLOSE: // // The client is giving up. // Discard the rest of the message, if // there is anything more. // (void)rpcapd_discard(pars.sockctrl, plen); // We're done with this client. goto end; case RPCAP_MSG_ERROR: // Log this and close the connection? // XXX - is this what happens in active // mode, where *we* initiate the // connection, and the client gives us // an error message rather than a "let // me log in" message, indicating that // we're not allowed to connect to them? (void)daemon_msg_err(pars.sockctrl, plen); goto end; case RPCAP_MSG_FINDALLIF_REQ: case RPCAP_MSG_OPEN_REQ: case RPCAP_MSG_STARTCAP_REQ: case RPCAP_MSG_UPDATEFILTER_REQ: case RPCAP_MSG_STATS_REQ: case RPCAP_MSG_ENDCAP_REQ: case RPCAP_MSG_SETSAMPLING_REQ: // // These requests can't be sent until // the client is authenticated. // msg_type_string = rpcap_msg_type_string(header.type); if (msg_type_string != NULL) { pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "%s request sent before authentication was completed", msg_type_string); } else { pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Message of type %u sent before authentication was completed", header.type); } if (rpcap_senderror(pars.sockctrl, header.ver, PCAP_ERR_WRONGMSG, errmsgbuf, errbuf) == -1) { rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf); goto end; } // Discard the rest of the message. if (rpcapd_discard(pars.sockctrl, plen) == -1) { // Network error. goto end; } break; case RPCAP_MSG_PACKET: case RPCAP_MSG_FINDALLIF_REPLY: case RPCAP_MSG_OPEN_REPLY: case RPCAP_MSG_STARTCAP_REPLY: case RPCAP_MSG_UPDATEFILTER_REPLY: case RPCAP_MSG_AUTH_REPLY: case RPCAP_MSG_STATS_REPLY: case RPCAP_MSG_ENDCAP_REPLY: case RPCAP_MSG_SETSAMPLING_REPLY: // // These are server-to-client messages. // msg_type_string = rpcap_msg_type_string(header.type); if (msg_type_string != NULL) { pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Server-to-client message %s received from client", msg_type_string); } else { pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Server-to-client message of type %u received from client", header.type); } if (rpcap_senderror(pars.sockctrl, header.ver, PCAP_ERR_WRONGMSG, errmsgbuf, errbuf) == -1) { rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf); goto end; } // Discard the rest of the message. if (rpcapd_discard(pars.sockctrl, plen) == -1) { // Fatal error. goto end; } break; default: // // Unknown message type. // pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Unknown message type %u", header.type); if (rpcap_senderror(pars.sockctrl, header.ver, PCAP_ERR_WRONGMSG, errmsgbuf, errbuf) == -1) { rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf); goto end; } // Discard the rest of the message. if (rpcapd_discard(pars.sockctrl, plen) == -1) { // Fatal error. goto end; } break; } } // // OK, the client has authenticated itself, and we can start // processing regular requests from it. // // // We don't have any statistics yet. // stats.ps_ifdrop = 0; stats.ps_recv = 0; stats.ps_drop = 0; svrcapt = 0; // // Service requests. // for (;;) { errbuf[0] = 0; // clear errbuf // Avoid zombies connections; check if the connection is opens but no commands are performed // from more than RPCAP_TIMEOUT_RUNTIME // Conditions: // - I have to be in normal mode (no active mode) // - if the device is open, I don't have to be in the middle of a capture (session->sockdata) // - if the device is closed, I have always to check if a new command arrives // // Be carefully: the capture can have been started, but an error occurred (so session != NULL, but // sockdata is 0 if ((!pars.isactive) && ((session == NULL) || ((session != NULL) && (session->sockdata == 0)))) { // Check for the initial timeout FD_ZERO(&rfds); // We do not have to block here tv.tv_sec = RPCAP_TIMEOUT_RUNTIME; tv.tv_usec = 0; FD_SET(pars.sockctrl, &rfds); retval = select(pars.sockctrl + 1, &rfds, NULL, NULL, &tv); if (retval == -1) { sock_geterror("select() failed", errmsgbuf, PCAP_ERRBUF_SIZE); if (rpcap_senderror(pars.sockctrl, 0, PCAP_ERR_NETW, errmsgbuf, errbuf) == -1) rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf); goto end; } // The timeout has expired // So, this was a fake connection. Drop it down if (retval == 0) { if (rpcap_senderror(pars.sockctrl, 0, PCAP_ERR_INITTIMEOUT, "The RPCAP initial timeout has expired", errbuf) == -1) rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf); goto end; } } // // Read the message header from the client. // nrecv = rpcapd_recv_msg_header(pars.sockctrl, &header); if (nrecv == -1) { // Fatal error. goto end; } if (nrecv == -2) { // Client closed the connection. goto end; } plen = header.plen; // // Did the client specify a protocol version that we // support? // if (!RPCAP_VERSION_IS_SUPPORTED(header.ver)) { // // Tell them it's not a supported version. // Send the error message with their version, // so they don't reject it as having the wrong // version. // if (rpcap_senderror(pars.sockctrl, header.ver, PCAP_ERR_WRONGVER, "RPCAP version in message isn't supported by the server", errbuf) == -1) { // That failed; log a message and give up. rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf); goto end; } // Discard the rest of the message. (void)rpcapd_discard(pars.sockctrl, plen); // Give up on them. goto end; } switch (header.type) { case RPCAP_MSG_ERROR: // The other endpoint reported an error { (void)daemon_msg_err(pars.sockctrl, plen); // Do nothing; just exit; the error code is already into the errbuf // XXX - actually exit.... break; } case RPCAP_MSG_FINDALLIF_REQ: { if (daemon_msg_findallif_req(header.ver, &pars, plen) == -1) { // Fatal error; a message has // been logged, so just give up. goto end; } break; } case RPCAP_MSG_OPEN_REQ: { // // Process the open request, and keep // the source from it, for use later // when the capture is started. // // XXX - we don't care if the client sends // us multiple open requests, the last // one wins. // retval = daemon_msg_open_req(header.ver, &pars, plen, source, sizeof(source)); if (retval == -1) { // Fatal error; a message has // been logged, so just give up. goto end; } got_source = 1; break; } case RPCAP_MSG_STARTCAP_REQ: { if (!got_source) { // They never told us what device // to capture on! if (rpcap_senderror(pars.sockctrl, header.ver, PCAP_ERR_STARTCAPTURE, "No capture device was specified", errbuf) == -1) { // Fatal error; log an // error and give up. rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf); goto end; } if (rpcapd_discard(pars.sockctrl, plen) == -1) { goto end; } break; } if (daemon_msg_startcap_req(header.ver, &pars, plen, source, &session, &samp_param) == -1) { // Fatal error; a message has // been logged, so just give up. goto end; } break; } case RPCAP_MSG_UPDATEFILTER_REQ: { if (session) { if (daemon_msg_updatefilter_req(header.ver, &pars, session, plen) == -1) { // Fatal error; a message has // been logged, so just give up. goto end; } } else { if (rpcap_senderror(pars.sockctrl, header.ver, PCAP_ERR_UPDATEFILTER, "Device not opened. Cannot update filter", errbuf) == -1) { // That failed; log a message and give up. rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf); goto end; } } break; } case RPCAP_MSG_CLOSE: // The other endpoint close the pcap session { // // Indicate to our caller that the client // closed the control connection. // This is used only in case of active mode. // client_told_us_to_close = 1; rpcapd_log(LOGPRIO_DEBUG, "The other end system asked to close the connection."); goto end; } case RPCAP_MSG_STATS_REQ: { if (daemon_msg_stats_req(header.ver, &pars, session, plen, &stats, svrcapt) == -1) { // Fatal error; a message has // been logged, so just give up. goto end; } break; } case RPCAP_MSG_ENDCAP_REQ: // The other endpoint close the current capture session { if (session) { // Save statistics (we can need them in the future) if (pcap_stats(session->fp, &stats)) { svrcapt = session->TotCapt; } else { stats.ps_ifdrop = 0; stats.ps_recv = 0; stats.ps_drop = 0; svrcapt = 0; } if (daemon_msg_endcap_req(header.ver, &pars, session) == -1) { free(session); session = NULL; // Fatal error; a message has // been logged, so just give up. goto end; } free(session); session = NULL; } else { rpcap_senderror(pars.sockctrl, header.ver, PCAP_ERR_ENDCAPTURE, "Device not opened. Cannot close the capture", errbuf); } break; } case RPCAP_MSG_SETSAMPLING_REQ: { if (daemon_msg_setsampling_req(header.ver, &pars, plen, &samp_param) == -1) { // Fatal error; a message has // been logged, so just give up. goto end; } break; } case RPCAP_MSG_AUTH_REQ: { // // We're already authenticated; you don't // get to reauthenticate. // rpcapd_log(LOGPRIO_INFO, "The client sent an RPCAP_MSG_AUTH_REQ message after authentication was completed"); if (rpcap_senderror(pars.sockctrl, header.ver, PCAP_ERR_WRONGMSG, "RPCAP_MSG_AUTH_REQ request sent after authentication was completed", errbuf) == -1) { rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf); goto end; } // Discard the rest of the message. if (rpcapd_discard(pars.sockctrl, plen) == -1) { // Fatal error. goto end; } goto end; case RPCAP_MSG_PACKET: case RPCAP_MSG_FINDALLIF_REPLY: case RPCAP_MSG_OPEN_REPLY: case RPCAP_MSG_STARTCAP_REPLY: case RPCAP_MSG_UPDATEFILTER_REPLY: case RPCAP_MSG_AUTH_REPLY: case RPCAP_MSG_STATS_REPLY: case RPCAP_MSG_ENDCAP_REPLY: case RPCAP_MSG_SETSAMPLING_REPLY: // // These are server-to-client messages. // msg_type_string = rpcap_msg_type_string(header.type); if (msg_type_string != NULL) { rpcapd_log(LOGPRIO_INFO, "The client sent a %s server-to-client message", msg_type_string); pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Server-to-client message %s received from client", msg_type_string); } else { rpcapd_log(LOGPRIO_INFO, "The client sent a server-to-client message of type %u", header.type); pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Server-to-client message of type %u received from client", header.type); } if (rpcap_senderror(pars.sockctrl, header.ver, PCAP_ERR_WRONGMSG, errmsgbuf, errbuf) == -1) { rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf); goto end; } // Discard the rest of the message. if (rpcapd_discard(pars.sockctrl, plen) == -1) { // Fatal error. goto end; } goto end; default: // // Unknown message type. // rpcapd_log(LOGPRIO_INFO, "The client sent a message of type %u", header.type); pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Unknown message type %u", header.type); if (rpcap_senderror(pars.sockctrl, header.ver, PCAP_ERR_WRONGMSG, errbuf, errmsgbuf) == -1) { rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf); goto end; } // Discard the rest of the message. if (rpcapd_discard(pars.sockctrl, plen) == -1) { // Fatal error. goto end; } goto end; } } } end: // The service loop is finishing up. // If we have a capture session running, close it. if (session) { session_close(session); free(session); session = NULL; } sock_close(sockctrl, NULL, 0); // Print message and return rpcapd_log(LOGPRIO_DEBUG, "I'm exiting from the child loop"); return client_told_us_to_close; } /* * This handles the RPCAP_MSG_ERR message. */ static int daemon_msg_err(SOCKET sockctrl, uint32 plen) { char errbuf[PCAP_ERRBUF_SIZE]; char remote_errbuf[PCAP_ERRBUF_SIZE]; if (plen >= PCAP_ERRBUF_SIZE) { /* * Message is too long; just read as much of it as we * can into the buffer provided, and discard the rest. */ if (sock_recv(sockctrl, remote_errbuf, PCAP_ERRBUF_SIZE - 1, SOCK_RECEIVEALL_YES|SOCK_EOF_IS_ERROR, errbuf, PCAP_ERRBUF_SIZE) == -1) { // Network error. rpcapd_log(LOGPRIO_ERROR, "Read from client failed: %s", errbuf); return -1; } if (rpcapd_discard(sockctrl, plen - (PCAP_ERRBUF_SIZE - 1)) == -1) { // Network error. return -1; } /* * Null-terminate it. */ remote_errbuf[PCAP_ERRBUF_SIZE - 1] = '\0'; } else if (plen == 0) { /* Empty error string. */ remote_errbuf[0] = '\0'; } else { if (sock_recv(sockctrl, remote_errbuf, plen, SOCK_RECEIVEALL_YES|SOCK_EOF_IS_ERROR, errbuf, PCAP_ERRBUF_SIZE) == -1) { // Network error. rpcapd_log(LOGPRIO_ERROR, "Read from client failed: %s", errbuf); return -1; } /* * Null-terminate it. */ remote_errbuf[plen] = '\0'; } // Log the message rpcapd_log(LOGPRIO_ERROR, "Error from client: %s", remote_errbuf); return 0; } /* * This handles the RPCAP_MSG_AUTH_REQ message. * It checks if the authentication credentials supplied by the user are valid. * * This function is called if the daemon receives a RPCAP_MSG_AUTH_REQ * message in its authentication loop. It reads the body of the * authentication message from the network and checks whether the * credentials are valid. * * \param sockctrl: the socket for the control connection. * * \param nullAuthAllowed: '1' if the NULL authentication is allowed. * * \param errbuf: a user-allocated buffer in which the error message * (if one) has to be written. It must be at least PCAP_ERRBUF_SIZE * bytes long. * * \return '0' if everything is fine, '-1' if an unrecoverable error occurred, * or '-2' if the authentication failed. For errors, an error message is * returned in the 'errbuf' variable; this gives a message for the * unrecoverable error or for the authentication failure. */ static int daemon_msg_auth_req(struct daemon_slpars *pars, uint32 plen) { char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors char errmsgbuf[PCAP_ERRBUF_SIZE]; // buffer for errors to send to the client int status; struct rpcap_auth auth; // RPCAP authentication header char sendbuf[RPCAP_NETBUF_SIZE]; // temporary buffer in which data to be sent is buffered int sendbufidx = 0; // index which keeps the number of bytes currently buffered struct rpcap_authreply *authreply; // authentication reply message status = rpcapd_recv(pars->sockctrl, (char *) &auth, sizeof(struct rpcap_auth), &plen, errmsgbuf); if (status == -1) { return -1; } if (status == -2) { goto error; } switch (ntohs(auth.type)) { case RPCAP_RMTAUTH_NULL: { if (!pars->nullAuthAllowed) { // Send the client an error reply. pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Authentication failed; NULL authentication not permitted."); if (rpcap_senderror(pars->sockctrl, 0, PCAP_ERR_AUTH_FAILED, errmsgbuf, errbuf) == -1) { // That failed; log a message and give up. rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf); return -1; } goto error_noreply; } break; } case RPCAP_RMTAUTH_PWD: { char *username, *passwd; uint32 usernamelen, passwdlen; usernamelen = ntohs(auth.slen1); username = (char *) malloc (usernamelen + 1); if (username == NULL) { pcap_fmt_errmsg_for_errno(errmsgbuf, PCAP_ERRBUF_SIZE, errno, "malloc() failed"); goto error; } status = rpcapd_recv(pars->sockctrl, username, usernamelen, &plen, errmsgbuf); if (status == -1) { free(username); return -1; } if (status == -2) { free(username); goto error; } username[usernamelen] = '\0'; passwdlen = ntohs(auth.slen2); passwd = (char *) malloc (passwdlen + 1); if (passwd == NULL) { pcap_fmt_errmsg_for_errno(errmsgbuf, PCAP_ERRBUF_SIZE, errno, "malloc() failed"); free(username); goto error; } status = rpcapd_recv(pars->sockctrl, passwd, passwdlen, &plen, errmsgbuf); if (status == -1) { free(username); free(passwd); return -1; } if (status == -2) { free(username); free(passwd); goto error; } passwd[passwdlen] = '\0'; if (daemon_AuthUserPwd(username, passwd, errmsgbuf)) { // // Authentication failed. Let the client // know. // free(username); free(passwd); if (rpcap_senderror(pars->sockctrl, 0, PCAP_ERR_AUTH_FAILED, errmsgbuf, errbuf) == -1) { // That failed; log a message and give up. rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf); return -1; } // // Suspend for 1 second, so that they can't // hammer us with repeated tries with an // attack such as a dictionary attack. // // WARNING: this delay is inserted only // at this point; if the client closes the // connection and reconnects, the suspension // time does not have any effect. // sleep_secs(RPCAP_SUSPEND_WRONGAUTH); goto error_noreply; } free(username); free(passwd); break; } default: pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Authentication type not recognized."); if (rpcap_senderror(pars->sockctrl, 0, PCAP_ERR_AUTH_TYPE_NOTSUP, errmsgbuf, errbuf) == -1) { // That failed; log a message and give up. rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf); return -1; } goto error_noreply; } // The authentication succeeded; let the client know. if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL, &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1) goto error; rpcap_createhdr((struct rpcap_header *) sendbuf, 0, RPCAP_MSG_AUTH_REPLY, 0, sizeof(struct rpcap_authreply)); authreply = (struct rpcap_authreply *) &sendbuf[sendbufidx]; if (sock_bufferize(NULL, sizeof(struct rpcap_authreply), NULL, &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1) goto error; // // Indicate to our peer what versions we support. // memset(authreply, 0, sizeof(struct rpcap_authreply)); authreply->minvers = RPCAP_MIN_VERSION; authreply->maxvers = RPCAP_MAX_VERSION; // Send the reply. if (sock_send(pars->sockctrl, sendbuf, sendbufidx, errbuf, PCAP_ERRBUF_SIZE) == -1) { // That failed; log a messsage and give up. rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf); return -1; } // Check if all the data has been read; if not, discard the data in excess if (rpcapd_discard(pars->sockctrl, plen) == -1) { return -1; } return 0; error: if (rpcap_senderror(pars->sockctrl, 0, PCAP_ERR_AUTH, errmsgbuf, errbuf) == -1) { // That failed; log a message and give up. rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf); return -1; } error_noreply: // Check if all the data has been read; if not, discard the data in excess if (rpcapd_discard(pars->sockctrl, plen) == -1) { return -1; } return -2; } static int daemon_AuthUserPwd(char *username, char *password, char *errbuf) { #ifdef _WIN32 /* * Warning: the user which launches the process must have the * SE_TCB_NAME right. * This corresponds to have the "Act as part of the Operating System" * turned on (administrative tools, local security settings, local * policies, user right assignment) * However, it seems to me that if you run it as a service, this * right should be provided by default. * * XXX - hopefully, this returns errors such as ERROR_LOGON_FAILURE, * which merely indicates that the user name or password is * incorrect, not whether it's the user name or the password * that's incorrect, so a client that's trying to brute-force * accounts doesn't know whether it's the user name or the * password that's incorrect, so it doesn't know whether to * stop trying to log in with a given user name and move on * to another user name. */ DWORD error; HANDLE Token; char errmsgbuf[PCAP_ERRBUF_SIZE]; // buffer for errors to log if (LogonUser(username, ".", password, LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT, &Token) == 0) { pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication failed"); error = GetLastError(); if (error != ERROR_LOGON_FAILURE) { // Some error other than an authentication error; // log it. pcap_fmt_errmsg_for_win32_err(errmsgbuf, PCAP_ERRBUF_SIZE, error, "LogonUser() failed"); rpcapd_log(LOGPRIO_ERROR, "%s", errmsgbuf); } return -1; } // This call should change the current thread to the selected user. // I didn't test it. if (ImpersonateLoggedOnUser(Token) == 0) { pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication failed"); pcap_fmt_errmsg_for_win32_err(errmsgbuf, PCAP_ERRBUF_SIZE, GetLastError(), "ImpersonateLoggedOnUser() failed"); rpcapd_log(LOGPRIO_ERROR, "%s", errmsgbuf); CloseHandle(Token); return -1; } CloseHandle(Token); return 0; #else /* * See * * http://www.unixpapa.com/incnote/passwd.html * * We use the Solaris/Linux shadow password authentication if * we have getspnam(), otherwise we just do traditional * authentication, which, on some platforms, might work, even * with shadow passwords, if we're running as root. Traditional * authenticaion won't work if we're not running as root, as * I think these days all UN*Xes either won't return the password * at all with getpwnam() or will only do so if you're root. * * XXX - perhaps what we *should* be using is PAM, if we have * it. That might hide all the details of username/password * authentication, whether it's done with a visible-to-root- * only password database or some other authentication mechanism, * behind its API. */ int error; struct passwd *user; char *user_password; #ifdef HAVE_GETSPNAM struct spwd *usersp; #endif char *crypt_password; // This call is needed to get the uid if ((user = getpwnam(username)) == NULL) { pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication failed"); return -1; } #ifdef HAVE_GETSPNAM // This call is needed to get the password; otherwise 'x' is returned if ((usersp = getspnam(username)) == NULL) { pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication failed"); return -1; } user_password = usersp->sp_pwdp; #else /* * XXX - what about other platforms? * The unixpapa.com page claims this Just Works on *BSD if you're * running as root - it's from 2000, so it doesn't indicate whether * macOS (which didn't come out until 2001, under the name Mac OS * X) behaves like the *BSDs or not, and might also work on AIX. * HP-UX does something else. * * Again, hopefully PAM hides all that. */ user_password = user->pw_passwd; #endif // // The Single UNIX Specification says that if crypt() fails it // sets errno, but some implementatons that haven't been run // through the SUS test suite might not do so. // errno = 0; crypt_password = crypt(password, user_password); if (crypt_password == NULL) { error = errno; pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication failed"); if (error == 0) { // It didn't set errno. rpcapd_log(LOGPRIO_ERROR, "crypt() failed"); } else { rpcapd_log(LOGPRIO_ERROR, "crypt() failed: %s", strerror(error)); } return -1; } if (strcmp(user_password, crypt_password) != 0) { pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication failed"); return -1; } if (setuid(user->pw_uid)) { error = errno; pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE, error, "setuid"); rpcapd_log(LOGPRIO_ERROR, "setuid() failed: %s", strerror(error)); return -1; } /* if (setgid(user->pw_gid)) { error = errno; pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE, errno, "setgid"); rpcapd_log(LOGPRIO_ERROR, "setgid() failed: %s", strerror(error)); return -1; } */ return 0; #endif } static int daemon_msg_findallif_req(uint8 ver, struct daemon_slpars *pars, uint32 plen) { char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors char errmsgbuf[PCAP_ERRBUF_SIZE]; // buffer for errors to send to the client char sendbuf[RPCAP_NETBUF_SIZE]; // temporary buffer in which data to be sent is buffered int sendbufidx = 0; // index which keeps the number of bytes currently buffered pcap_if_t *alldevs = NULL; // pointer to the header of the interface chain pcap_if_t *d; // temp pointer needed to scan the interface chain struct pcap_addr *address; // pcap structure that keeps a network address of an interface struct rpcap_findalldevs_if *findalldevs_if;// rpcap structure that packet all the data of an interface together uint16 nif = 0; // counts the number of interface listed // Discard the rest of the message; there shouldn't be any payload. if (rpcapd_discard(pars->sockctrl, plen) == -1) { // Network error. return -1; } // Retrieve the device list if (pcap_findalldevs(&alldevs, errmsgbuf) == -1) goto error; if (alldevs == NULL) { if (rpcap_senderror(pars->sockctrl, ver, PCAP_ERR_NOREMOTEIF, "No interfaces found! Make sure libpcap/WinPcap is properly installed" " and you have the right to access to the remote device.", errbuf) == -1) { rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf); return -1; } return 0; } // checks the number of interfaces and it computes the total length of the payload for (d = alldevs; d != NULL; d = d->next) { nif++; if (d->description) plen+= strlen(d->description); if (d->name) plen+= strlen(d->name); plen+= sizeof(struct rpcap_findalldevs_if); for (address = d->addresses; address != NULL; address = address->next) { /* * Send only IPv4 and IPv6 addresses over the wire. */ switch (address->addr->sa_family) { case AF_INET: #ifdef AF_INET6 case AF_INET6: #endif plen+= (sizeof(struct rpcap_sockaddr) * 4); break; default: break; } } } // RPCAP findalldevs command if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL, &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1) goto error; rpcap_createhdr((struct rpcap_header *) sendbuf, ver, RPCAP_MSG_FINDALLIF_REPLY, nif, plen); // send the interface list for (d = alldevs; d != NULL; d = d->next) { uint16 lname, ldescr; findalldevs_if = (struct rpcap_findalldevs_if *) &sendbuf[sendbufidx]; if (sock_bufferize(NULL, sizeof(struct rpcap_findalldevs_if), NULL, &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1) goto error; memset(findalldevs_if, 0, sizeof(struct rpcap_findalldevs_if)); if (d->description) ldescr = (short) strlen(d->description); else ldescr = 0; if (d->name) lname = (short) strlen(d->name); else lname = 0; findalldevs_if->desclen = htons(ldescr); findalldevs_if->namelen = htons(lname); findalldevs_if->flags = htonl(d->flags); for (address = d->addresses; address != NULL; address = address->next) { /* * Send only IPv4 and IPv6 addresses over the wire. */ switch (address->addr->sa_family) { case AF_INET: #ifdef AF_INET6 case AF_INET6: #endif findalldevs_if->naddr++; break; default: break; } } findalldevs_if->naddr = htons(findalldevs_if->naddr); if (sock_bufferize(d->name, lname, sendbuf, &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_BUFFERIZE, errmsgbuf, PCAP_ERRBUF_SIZE) == -1) goto error; if (sock_bufferize(d->description, ldescr, sendbuf, &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_BUFFERIZE, errmsgbuf, PCAP_ERRBUF_SIZE) == -1) goto error; // send all addresses for (address = d->addresses; address != NULL; address = address->next) { struct rpcap_sockaddr *sockaddr; /* * Send only IPv4 and IPv6 addresses over the wire. */ switch (address->addr->sa_family) { case AF_INET: #ifdef AF_INET6 case AF_INET6: #endif sockaddr = (struct rpcap_sockaddr *) &sendbuf[sendbufidx]; if (sock_bufferize(NULL, sizeof(struct rpcap_sockaddr), NULL, &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1) goto error; daemon_seraddr((struct sockaddr_storage *) address->addr, sockaddr); sockaddr = (struct rpcap_sockaddr *) &sendbuf[sendbufidx]; if (sock_bufferize(NULL, sizeof(struct rpcap_sockaddr), NULL, &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1) goto error; daemon_seraddr((struct sockaddr_storage *) address->netmask, sockaddr); sockaddr = (struct rpcap_sockaddr *) &sendbuf[sendbufidx]; if (sock_bufferize(NULL, sizeof(struct rpcap_sockaddr), NULL, &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1) goto error; daemon_seraddr((struct sockaddr_storage *) address->broadaddr, sockaddr); sockaddr = (struct rpcap_sockaddr *) &sendbuf[sendbufidx]; if (sock_bufferize(NULL, sizeof(struct rpcap_sockaddr), NULL, &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1) goto error; daemon_seraddr((struct sockaddr_storage *) address->dstaddr, sockaddr); break; default: break; } } } // We no longer need the device list. Free it. pcap_freealldevs(alldevs); // Send a final command that says "now send it!" if (sock_send(pars->sockctrl, sendbuf, sendbufidx, errbuf, PCAP_ERRBUF_SIZE) == -1) { rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf); return -1; } return 0; error: if (alldevs) pcap_freealldevs(alldevs); if (rpcap_senderror(pars->sockctrl, ver, PCAP_ERR_FINDALLIF, errmsgbuf, errbuf) == -1) { rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf); return -1; } return 0; } /* \param plen: the length of the current message (needed in order to be able to discard excess data in the message, if present) */ static int daemon_msg_open_req(uint8 ver, struct daemon_slpars *pars, uint32 plen, char *source, size_t sourcelen) { char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors char errmsgbuf[PCAP_ERRBUF_SIZE]; // buffer for errors to send to the client pcap_t *fp; // pcap_t main variable int nread; char sendbuf[RPCAP_NETBUF_SIZE]; // temporary buffer in which data to be sent is buffered int sendbufidx = 0; // index which keeps the number of bytes currently buffered struct rpcap_openreply *openreply; // open reply message if (plen > sourcelen - 1) { pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Source string too long"); goto error; } nread = sock_recv(pars->sockctrl, source, plen, SOCK_RECEIVEALL_YES|SOCK_EOF_IS_ERROR, errbuf, PCAP_ERRBUF_SIZE); if (nread == -1) { rpcapd_log(LOGPRIO_ERROR, "Read from client failed: %s", errbuf); return -1; } source[nread] = '\0'; plen -= nread; // Is this a URL rather than a device? // If so, reject it. if (is_url(source)) { pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Source string refers to a remote device"); goto error; } // Open the selected device // This is a fake open, since we do that only to get the needed parameters, then we close the device again if ((fp = pcap_open_live(source, 1500 /* fake snaplen */, 0 /* no promis */, 1000 /* fake timeout */, errmsgbuf)) == NULL) goto error; // Now, I can send a RPCAP open reply message if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL, &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1) goto error; rpcap_createhdr((struct rpcap_header *) sendbuf, ver, RPCAP_MSG_OPEN_REPLY, 0, sizeof(struct rpcap_openreply)); openreply = (struct rpcap_openreply *) &sendbuf[sendbufidx]; if (sock_bufferize(NULL, sizeof(struct rpcap_openreply), NULL, &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1) goto error; memset(openreply, 0, sizeof(struct rpcap_openreply)); openreply->linktype = htonl(pcap_datalink(fp)); openreply->tzoff = 0; /* This is always 0 for live captures */ // We're done with the pcap_t. pcap_close(fp); // Send the reply. if (sock_send(pars->sockctrl, sendbuf, sendbufidx, errbuf, PCAP_ERRBUF_SIZE) == -1) { rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf); return -1; } return 0; error: if (rpcap_senderror(pars->sockctrl, ver, PCAP_ERR_OPEN, errmsgbuf, errbuf) == -1) { // That failed; log a message and give up. rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf); return -1; } // Check if all the data has been read; if not, discard the data in excess if (rpcapd_discard(pars->sockctrl, plen) == -1) { return -1; } return 0; } /* \param plen: the length of the current message (needed in order to be able to discard excess data in the message, if present) */ static int daemon_msg_startcap_req(uint8 ver, struct daemon_slpars *pars, uint32 plen, char *source, struct session **sessionp, struct rpcap_sampling *samp_param _U_) { char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors char errmsgbuf[PCAP_ERRBUF_SIZE]; // buffer for errors to send to the client char portdata[PCAP_BUF_SIZE]; // temp variable needed to derive the data port char peerhost[PCAP_BUF_SIZE]; // temp variable needed to derive the host name of our peer struct session *session = NULL; // saves state of session int status; char sendbuf[RPCAP_NETBUF_SIZE]; // temporary buffer in which data to be sent is buffered int sendbufidx = 0; // index which keeps the number of bytes currently buffered // socket-related variables struct addrinfo hints; // temp, needed to open a socket connection struct addrinfo *addrinfo; // temp, needed to open a socket connection struct sockaddr_storage saddr; // temp, needed to retrieve the network data port chosen on the local machine socklen_t saddrlen; // temp, needed to retrieve the network data port chosen on the local machine int ret; // return value from functions // RPCAP-related variables struct rpcap_startcapreq startcapreq; // start capture request message struct rpcap_startcapreply *startcapreply; // start capture reply message int serveropen_dp; // keeps who is going to open the data connection addrinfo = NULL; status = rpcapd_recv(pars->sockctrl, (char *) &startcapreq, sizeof(struct rpcap_startcapreq), &plen, errmsgbuf); if (status == -1) { goto fatal_error; } if (status == -2) { goto error; } startcapreq.flags = ntohs(startcapreq.flags); // Create a session structure session = malloc(sizeof(struct session)); if (session == NULL) { pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Can't allocate session structure"); goto error; } session->sockdata = INVALID_SOCKET; // We don't have a thread yet. session->have_thread = 0; // // We *shouldn't* have to initialize the thread indicator // itself, because the compiler *should* realize that we // only use this if have_thread isn't 0, but we *do* have // to do it, because not all compilers *do* realize that. // // There is no "invalid thread handle" value for a UN*X // pthread_t, so we just zero it out. // #ifdef _WIN32 session->thread = INVALID_HANDLE_VALUE; #else memset(&session->thread, 0, sizeof(session->thread)); #endif // Open the selected device if ((session->fp = pcap_open_live(source, ntohl(startcapreq.snaplen), (startcapreq.flags & RPCAP_STARTCAPREQ_FLAG_PROMISC) ? 1 : 0 /* local device, other flags not needed */, ntohl(startcapreq.read_timeout), errmsgbuf)) == NULL) goto error; #if 0 // Apply sampling parameters fp->rmt_samp.method = samp_param->method; fp->rmt_samp.value = samp_param->value; #endif /* We're in active mode if: - we're using TCP, and the user wants us to be in active mode - we're using UDP */ serveropen_dp = (startcapreq.flags & RPCAP_STARTCAPREQ_FLAG_SERVEROPEN) || (startcapreq.flags & RPCAP_STARTCAPREQ_FLAG_DGRAM) || pars->isactive; /* Gets the sockaddr structure referred to the other peer in the ctrl connection We need that because: - if we're in passive mode, we need to know the address family we want to use (the same used for the ctrl socket) - if we're in active mode, we need to know the network address of the other host we want to connect to */ saddrlen = sizeof(struct sockaddr_storage); if (getpeername(pars->sockctrl, (struct sockaddr *) &saddr, &saddrlen) == -1) { sock_geterror("getpeername()", errmsgbuf, PCAP_ERRBUF_SIZE); goto error; } memset(&hints, 0, sizeof(struct addrinfo)); hints.ai_socktype = (startcapreq.flags & RPCAP_STARTCAPREQ_FLAG_DGRAM) ? SOCK_DGRAM : SOCK_STREAM; hints.ai_family = saddr.ss_family; // Now we have to create a new socket to send packets if (serveropen_dp) // Data connection is opened by the server toward the client { pcap_snprintf(portdata, sizeof portdata, "%d", ntohs(startcapreq.portdata)); // Get the name of the other peer (needed to connect to that specific network address) if (getnameinfo((struct sockaddr *) &saddr, saddrlen, peerhost, sizeof(peerhost), NULL, 0, NI_NUMERICHOST)) { sock_geterror("getnameinfo()", errmsgbuf, PCAP_ERRBUF_SIZE); goto error; } if (sock_initaddress(peerhost, portdata, &hints, &addrinfo, errmsgbuf, PCAP_ERRBUF_SIZE) == -1) goto error; if ((session->sockdata = sock_open(addrinfo, SOCKOPEN_CLIENT, 0, errmsgbuf, PCAP_ERRBUF_SIZE)) == INVALID_SOCKET) goto error; } else // Data connection is opened by the client toward the server { hints.ai_flags = AI_PASSIVE; // Let's the server socket pick up a free network port for us if (sock_initaddress(NULL, "0", &hints, &addrinfo, errmsgbuf, PCAP_ERRBUF_SIZE) == -1) goto error; if ((session->sockdata = sock_open(addrinfo, SOCKOPEN_SERVER, 1 /* max 1 connection in queue */, errmsgbuf, PCAP_ERRBUF_SIZE)) == INVALID_SOCKET) goto error; // get the complete sockaddr structure used in the data connection saddrlen = sizeof(struct sockaddr_storage); if (getsockname(session->sockdata, (struct sockaddr *) &saddr, &saddrlen) == -1) { sock_geterror("getsockname()", errmsgbuf, PCAP_ERRBUF_SIZE); goto error; } // Get the local port the system picked up if (getnameinfo((struct sockaddr *) &saddr, saddrlen, NULL, 0, portdata, sizeof(portdata), NI_NUMERICSERV)) { sock_geterror("getnameinfo()", errmsgbuf, PCAP_ERRBUF_SIZE); goto error; } } // addrinfo is no longer used freeaddrinfo(addrinfo); addrinfo = NULL; // Needed to send an error on the ctrl connection session->sockctrl = pars->sockctrl; session->protocol_version = ver; // Now I can set the filter ret = daemon_unpackapplyfilter(pars->sockctrl, session, &plen, errmsgbuf); if (ret == -1) { // Fatal error. A message has been logged; just give up. goto fatal_error; } if (ret == -2) { // Non-fatal error. Send an error message to the client. goto error; } // Now, I can send a RPCAP start capture reply message if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL, &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1) goto error; rpcap_createhdr((struct rpcap_header *) sendbuf, ver, RPCAP_MSG_STARTCAP_REPLY, 0, sizeof(struct rpcap_startcapreply)); startcapreply = (struct rpcap_startcapreply *) &sendbuf[sendbufidx]; if (sock_bufferize(NULL, sizeof(struct rpcap_startcapreply), NULL, &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1) goto error; memset(startcapreply, 0, sizeof(struct rpcap_startcapreply)); startcapreply->bufsize = htonl(pcap_bufsize(session->fp)); if (!serveropen_dp) { unsigned short port = (unsigned short)strtoul(portdata,NULL,10); startcapreply->portdata = htons(port); } if (sock_send(pars->sockctrl, sendbuf, sendbufidx, errbuf, PCAP_ERRBUF_SIZE) == -1) { // That failed; log a message and give up. rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf); goto fatal_error; } if (!serveropen_dp) { SOCKET socktemp; // We need another socket, since we're going to accept() a connection // Connection creation saddrlen = sizeof(struct sockaddr_storage); socktemp = accept(session->sockdata, (struct sockaddr *) &saddr, &saddrlen); if (socktemp == INVALID_SOCKET) { sock_geterror("accept()", errbuf, PCAP_ERRBUF_SIZE); rpcapd_log(LOGPRIO_ERROR, "Accept of data connection failed: %s", errbuf); goto error; } // Now that I accepted the connection, the server socket is no longer needed sock_close(session->sockdata, NULL, 0); session->sockdata = socktemp; } // Now we have to create a new thread to receive packets #ifdef _WIN32 session->thread = (HANDLE)_beginthreadex(NULL, 0, daemon_thrdatamain, (void *) session, 0, NULL); if (session->thread == 0) { pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Error creating the data thread"); goto error; } #else ret = pthread_create(&session->thread, NULL, daemon_thrdatamain, (void *) session); if (ret != 0) { pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE, ret, "Error creating the data thread"); goto error; } #endif session->have_thread = 1; // Check if all the data has been read; if not, discard the data in excess if (rpcapd_discard(pars->sockctrl, plen) == -1) goto fatal_error; *sessionp = session; return 0; error: // // Not a fatal error, so send the client an error message and // keep serving client requests. // *sessionp = NULL; if (addrinfo) freeaddrinfo(addrinfo); if (session) { session_close(session); free(session); } if (rpcap_senderror(pars->sockctrl, ver, PCAP_ERR_STARTCAPTURE, errmsgbuf, errbuf) == -1) { // That failed; log a message and give up. rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf); return -1; } // Check if all the data has been read; if not, discard the data in excess if (rpcapd_discard(pars->sockctrl, plen) == -1) { // Network error. return -1; } return 0; fatal_error: // // Fatal network error, so don't try to communicate with // the client, just give up. // *sessionp = NULL; if (session) { session_close(session); free(session); } return -1; } static int daemon_msg_endcap_req(uint8 ver, struct daemon_slpars *pars, struct session *session) { char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors struct rpcap_header header; session_close(session); rpcap_createhdr(&header, ver, RPCAP_MSG_ENDCAP_REPLY, 0, 0); if (sock_send(pars->sockctrl, (char *) &header, sizeof(struct rpcap_header), errbuf, PCAP_ERRBUF_SIZE) == -1) { // That failed; log a message and give up. rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf); return -1; } return 0; } static int daemon_unpackapplyfilter(SOCKET sockctrl, struct session *session, uint32 *plenp, char *errmsgbuf) { int status; struct rpcap_filter filter; struct rpcap_filterbpf_insn insn; struct bpf_insn *bf_insn; struct bpf_program bf_prog; unsigned int i; status = rpcapd_recv(sockctrl, (char *) &filter, sizeof(struct rpcap_filter), plenp, errmsgbuf); if (status == -1) { return -1; } if (status == -2) { return -2; } bf_prog.bf_len = ntohl(filter.nitems); if (ntohs(filter.filtertype) != RPCAP_UPDATEFILTER_BPF) { pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Only BPF/NPF filters are currently supported"); return -2; } bf_insn = (struct bpf_insn *) malloc (sizeof(struct bpf_insn) * bf_prog.bf_len); if (bf_insn == NULL) { pcap_fmt_errmsg_for_errno(errmsgbuf, PCAP_ERRBUF_SIZE, errno, "malloc() failed"); return -2; } bf_prog.bf_insns = bf_insn; for (i = 0; i < bf_prog.bf_len; i++) { status = rpcapd_recv(sockctrl, (char *) &insn, sizeof(struct rpcap_filterbpf_insn), plenp, errmsgbuf); if (status == -1) { return -1; } if (status == -2) { return -2; } bf_insn->code = ntohs(insn.code); bf_insn->jf = insn.jf; bf_insn->jt = insn.jt; bf_insn->k = ntohl(insn.k); bf_insn++; } if (bpf_validate(bf_prog.bf_insns, bf_prog.bf_len) == 0) { pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "The filter contains bogus instructions"); return -2; } if (pcap_setfilter(session->fp, &bf_prog)) { pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "RPCAP error: %s", pcap_geterr(session->fp)); return -2; } return 0; } static int daemon_msg_updatefilter_req(uint8 ver, struct daemon_slpars *pars, struct session *session, uint32 plen) { char errbuf[PCAP_ERRBUF_SIZE]; char errmsgbuf[PCAP_ERRBUF_SIZE]; // buffer for errors to send to the client int ret; // status of daemon_unpackapplyfilter() struct rpcap_header header; // keeps the answer to the updatefilter command ret = daemon_unpackapplyfilter(pars->sockctrl, session, &plen, errmsgbuf); if (ret == -1) { // Fatal error. A message has been logged; just give up. return -1; } if (ret == -2) { // Non-fatal error. Send an error reply to the client. goto error; } // Check if all the data has been read; if not, discard the data in excess if (rpcapd_discard(pars->sockctrl, plen) == -1) { // Network error. return -1; } // A response is needed, otherwise the other host does not know that everything went well rpcap_createhdr(&header, ver, RPCAP_MSG_UPDATEFILTER_REPLY, 0, 0); if (sock_send(pars->sockctrl, (char *) &header, sizeof (struct rpcap_header), pcap_geterr(session->fp), PCAP_ERRBUF_SIZE)) { // That failed; log a messsage and give up. rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf); return -1; } return 0; error: if (rpcapd_discard(pars->sockctrl, plen) == -1) { return -1; } rpcap_senderror(pars->sockctrl, ver, PCAP_ERR_UPDATEFILTER, errmsgbuf, NULL); return 0; } /*! \brief Received the sampling parameters from remote host and it stores in the pcap_t structure. */ static int daemon_msg_setsampling_req(uint8 ver, struct daemon_slpars *pars, uint32 plen, struct rpcap_sampling *samp_param) { char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors char errmsgbuf[PCAP_ERRBUF_SIZE]; struct rpcap_header header; struct rpcap_sampling rpcap_samp; int status; status = rpcapd_recv(pars->sockctrl, (char *) &rpcap_samp, sizeof(struct rpcap_sampling), &plen, errmsgbuf); if (status == -1) { return -1; } if (status == -2) { goto error; } // Save these settings in the pcap_t samp_param->method = rpcap_samp.method; samp_param->value = ntohl(rpcap_samp.value); // A response is needed, otherwise the other host does not know that everything went well rpcap_createhdr(&header, ver, RPCAP_MSG_SETSAMPLING_REPLY, 0, 0); if (sock_send(pars->sockctrl, (char *) &header, sizeof (struct rpcap_header), errbuf, PCAP_ERRBUF_SIZE) == -1) { // That failed; log a messsage and give up. rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf); return -1; } if (rpcapd_discard(pars->sockctrl, plen) == -1) { return -1; } return 0; error: if (rpcap_senderror(pars->sockctrl, ver, PCAP_ERR_SETSAMPLING, errmsgbuf, errbuf) == -1) { // That failed; log a message and give up. rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf); return -1; } // Check if all the data has been read; if not, discard the data in excess if (rpcapd_discard(pars->sockctrl, plen) == -1) { return -1; } return 0; } static int daemon_msg_stats_req(uint8 ver, struct daemon_slpars *pars, struct session *session, uint32 plen, struct pcap_stat *stats, unsigned int svrcapt) { char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors char errmsgbuf[PCAP_ERRBUF_SIZE]; // buffer for errors to send to the client char sendbuf[RPCAP_NETBUF_SIZE]; // temporary buffer in which data to be sent is buffered int sendbufidx = 0; // index which keeps the number of bytes currently buffered struct rpcap_stats *netstats; // statistics sent on the network // Checks that the header does not contain other data; if so, discard it if (rpcapd_discard(pars->sockctrl, plen) == -1) { // Network error. return -1; } if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL, &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1) goto error; rpcap_createhdr((struct rpcap_header *) sendbuf, ver, RPCAP_MSG_STATS_REPLY, 0, (uint16) sizeof(struct rpcap_stats)); netstats = (struct rpcap_stats *) &sendbuf[sendbufidx]; if (sock_bufferize(NULL, sizeof(struct rpcap_stats), NULL, &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1) goto error; if (session && session->fp) { if (pcap_stats(session->fp, stats) == -1) { pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "%s", pcap_geterr(session->fp)); goto error; } netstats->ifdrop = htonl(stats->ps_ifdrop); netstats->ifrecv = htonl(stats->ps_recv); netstats->krnldrop = htonl(stats->ps_drop); netstats->svrcapt = htonl(session->TotCapt); } else { // We have to keep compatibility with old applications, // which ask for statistics also when the capture has // already stopped. netstats->ifdrop = htonl(stats->ps_ifdrop); netstats->ifrecv = htonl(stats->ps_recv); netstats->krnldrop = htonl(stats->ps_drop); netstats->svrcapt = htonl(svrcapt); } // Send the packet if (sock_send(pars->sockctrl, sendbuf, sendbufidx, errbuf, PCAP_ERRBUF_SIZE) == -1) { rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf); return -1; } return 0; error: rpcap_senderror(pars->sockctrl, ver, PCAP_ERR_GETSTATS, errmsgbuf, NULL); return 0; } #ifdef _WIN32 static unsigned __stdcall #else static void * #endif daemon_thrdatamain(void *ptr) { char errbuf[PCAP_ERRBUF_SIZE + 1]; // error buffer struct session *session; // pointer to the struct session for this session int retval; // general variable used to keep the return value of other functions struct rpcap_pkthdr *net_pkt_header;// header of the packet struct pcap_pkthdr *pkt_header; // pointer to the buffer that contains the header of the current packet u_char *pkt_data; // pointer to the buffer that contains the current packet size_t sendbufsize; // size for the send buffer char *sendbuf; // temporary buffer in which data to be sent is buffered int sendbufidx; // index which keeps the number of bytes currently buffered int status; #ifndef _WIN32 sigset_t sigusr1; // signal set with just SIGUSR1 #endif session = (struct session *) ptr; session->TotCapt = 0; // counter which is incremented each time a packet is received // Initialize errbuf memset(errbuf, 0, sizeof(errbuf)); // // We need a buffer large enough to hold a buffer large enough // for a maximum-size packet for this pcap_t. // if (pcap_snapshot(session->fp) < 0) { // // The snapshot length is negative. // This "should not happen". // rpcapd_log(LOGPRIO_ERROR, "Unable to allocate the buffer for this child thread: snapshot length of %d is negative", pcap_snapshot(session->fp)); sendbuf = NULL; // we can't allocate a buffer, so nothing to free goto error; } // // size_t is unsigned, and the result of pcap_snapshot() is signed; // on no platform that we support is int larger than size_t. // This means that, unless the extra information we prepend to // a maximum-sized packet is impossibly large, the sum of the // snapshot length and the size of that extra information will // fit in a size_t. // // So we don't need to make sure that sendbufsize will overflow. // sendbufsize = sizeof(struct rpcap_header) + sizeof(struct rpcap_pkthdr) + pcap_snapshot(session->fp); sendbuf = (char *) malloc (sendbufsize); if (sendbuf == NULL) { rpcapd_log(LOGPRIO_ERROR, "Unable to allocate the buffer for this child thread"); goto error; } #ifndef _WIN32 // // Set the signal set to include just SIGUSR1, and block that // signal; we only want it unblocked when we're reading // packets - we dn't want any other system calls, such as // ones being used to send to the client or to log messages, // to be interrupted. // sigemptyset(&sigusr1); sigaddset(&sigusr1, SIGUSR1); pthread_sigmask(SIG_BLOCK, &sigusr1, NULL); #endif // Retrieve the packets for (;;) { #ifndef _WIN32 // // Unblock SIGUSR1 while we might be waiting for packets. // pthread_sigmask(SIG_UNBLOCK, &sigusr1, NULL); #endif retval = pcap_next_ex(session->fp, &pkt_header, (const u_char **) &pkt_data); // cast to avoid a compiler warning #ifndef _WIN32 // // Now block it again. // pthread_sigmask(SIG_BLOCK, &sigusr1, NULL); #endif if (retval < 0) break; // error if (retval == 0) // Read timeout elapsed continue; sendbufidx = 0; // Bufferize the general header if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL, &sendbufidx, sendbufsize, SOCKBUF_CHECKONLY, errbuf, PCAP_ERRBUF_SIZE) == -1) { rpcapd_log(LOGPRIO_ERROR, "sock_bufferize() error sending packet message: %s", errbuf); goto error; } rpcap_createhdr((struct rpcap_header *) sendbuf, session->protocol_version, RPCAP_MSG_PACKET, 0, (uint16) (sizeof(struct rpcap_pkthdr) + pkt_header->caplen)); net_pkt_header = (struct rpcap_pkthdr *) &sendbuf[sendbufidx]; // Bufferize the pkt header if (sock_bufferize(NULL, sizeof(struct rpcap_pkthdr), NULL, &sendbufidx, sendbufsize, SOCKBUF_CHECKONLY, errbuf, PCAP_ERRBUF_SIZE) == -1) { rpcapd_log(LOGPRIO_ERROR, "sock_bufferize() error sending packet message: %s", errbuf); goto error; } net_pkt_header->caplen = htonl(pkt_header->caplen); net_pkt_header->len = htonl(pkt_header->len); net_pkt_header->npkt = htonl(++(session->TotCapt)); net_pkt_header->timestamp_sec = htonl(pkt_header->ts.tv_sec); net_pkt_header->timestamp_usec = htonl(pkt_header->ts.tv_usec); // Bufferize the pkt data if (sock_bufferize((char *) pkt_data, pkt_header->caplen, sendbuf, &sendbufidx, sendbufsize, SOCKBUF_BUFFERIZE, errbuf, PCAP_ERRBUF_SIZE) == -1) { rpcapd_log(LOGPRIO_ERROR, "sock_bufferize() error sending packet message: %s", errbuf); goto error; } // Send the packet // If the client dropped the connection, don't report an // error, just quit. status = sock_send(session->sockdata, sendbuf, sendbufidx, errbuf, PCAP_ERRBUF_SIZE); if (status < 0) { if (status == -1) { // // Error other than "client closed the // connection out from under us"; report // it. // rpcapd_log(LOGPRIO_ERROR, "Send of packet to client failed: %s", errbuf); } // // Give up in either case. // goto error; } } if (retval < 0 && retval != PCAP_ERROR_BREAK) { // // Failed with an error other than "we were told to break // out of the loop". // // The latter just means that the client told us to stop // capturing, so there's no error to report. // pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Error reading the packets: %s", pcap_geterr(session->fp)); rpcap_senderror(session->sockctrl, session->protocol_version, PCAP_ERR_READEX, errbuf, NULL); } error: // // The main thread will clean up the session structure. // free(sendbuf); return 0; } #ifndef _WIN32 // // Do-nothing handler for SIGUSR1; the sole purpose of SIGUSR1 is to // interrupt the data thread if it's blocked in a system call waiting // for packets to arrive. // static void noop_handler(int sign _U_) { } #endif /*! \brief It serializes a network address. It accepts a 'sockaddr_storage' structure as input, and it converts it appropriately into a format that can be used to be sent on the network. Basically, it applies all the hton() conversion required to the input variable. \param sockaddrin a 'sockaddr_storage' pointer to the variable that has to be serialized. This variable can be both a 'sockaddr_in' and 'sockaddr_in6'. \param sockaddrout an 'rpcap_sockaddr' pointer to the variable that will contain the serialized data. This variable has to be allocated by the user. \warning This function supports only AF_INET and AF_INET6 address families. */ static void daemon_seraddr(struct sockaddr_storage *sockaddrin, struct rpcap_sockaddr *sockaddrout) { memset(sockaddrout, 0, sizeof(struct sockaddr_storage)); // There can be the case in which the sockaddrin is not available if (sockaddrin == NULL) return; // Warning: we support only AF_INET and AF_INET6 switch (sockaddrin->ss_family) { case AF_INET: { struct sockaddr_in *sockaddrin_ipv4; struct rpcap_sockaddr_in *sockaddrout_ipv4; sockaddrin_ipv4 = (struct sockaddr_in *) sockaddrin; sockaddrout_ipv4 = (struct rpcap_sockaddr_in *) sockaddrout; sockaddrout_ipv4->family = htons(RPCAP_AF_INET); sockaddrout_ipv4->port = htons(sockaddrin_ipv4->sin_port); memcpy(&sockaddrout_ipv4->addr, &sockaddrin_ipv4->sin_addr, sizeof(sockaddrout_ipv4->addr)); memset(sockaddrout_ipv4->zero, 0, sizeof(sockaddrout_ipv4->zero)); break; } #ifdef AF_INET6 case AF_INET6: { struct sockaddr_in6 *sockaddrin_ipv6; struct rpcap_sockaddr_in6 *sockaddrout_ipv6; sockaddrin_ipv6 = (struct sockaddr_in6 *) sockaddrin; sockaddrout_ipv6 = (struct rpcap_sockaddr_in6 *) sockaddrout; sockaddrout_ipv6->family = htons(RPCAP_AF_INET6); sockaddrout_ipv6->port = htons(sockaddrin_ipv6->sin6_port); sockaddrout_ipv6->flowinfo = htonl(sockaddrin_ipv6->sin6_flowinfo); memcpy(&sockaddrout_ipv6->addr, &sockaddrin_ipv6->sin6_addr, sizeof(sockaddrout_ipv6->addr)); sockaddrout_ipv6->scope_id = htonl(sockaddrin_ipv6->sin6_scope_id); break; } #endif } } /*! \brief Suspends a thread for secs seconds. */ void sleep_secs(int secs) { #ifdef _WIN32 Sleep(secs*1000); #else unsigned secs_remaining; if (secs <= 0) return; secs_remaining = secs; while (secs_remaining != 0) secs_remaining = sleep(secs_remaining); #endif } /* * Read the header of a message. */ static int rpcapd_recv_msg_header(SOCKET sock, struct rpcap_header *headerp) { int nread; char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors nread = sock_recv(sock, (char *) headerp, sizeof(struct rpcap_header), SOCK_RECEIVEALL_YES|SOCK_EOF_ISNT_ERROR, errbuf, PCAP_ERRBUF_SIZE); if (nread == -1) { // Network error. rpcapd_log(LOGPRIO_ERROR, "Read from client failed: %s", errbuf); return -1; } if (nread == 0) { // Immediate EOF; that's treated like a close message. return -2; } headerp->plen = ntohl(headerp->plen); return 0; } /* * Read data from a message. * If we're trying to read more data that remains, puts an error * message into errmsgbuf and returns -2. Otherwise, tries to read * the data and, if that succeeds, subtracts the amount read from * the number of bytes of data that remains. * Returns 0 on success, logs a message and returns -1 on a network * error. */ static int rpcapd_recv(SOCKET sock, char *buffer, size_t toread, uint32 *plen, char *errmsgbuf) { int nread; char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors if (toread > *plen) { // Tell the client and continue. pcap_snprintf(errmsgbuf, PCAP_ERRBUF_SIZE, "Message payload is too short"); return -2; } nread = sock_recv(sock, buffer, toread, SOCK_RECEIVEALL_YES|SOCK_EOF_IS_ERROR, errbuf, PCAP_ERRBUF_SIZE); if (nread == -1) { rpcapd_log(LOGPRIO_ERROR, "Read from client failed: %s", errbuf); return -1; } *plen -= nread; return 0; } /* * Discard data from a connection. * Mostly used to discard wrong-sized messages. * Returns 0 on success, logs a message and returns -1 on a network * error. */ static int rpcapd_discard(SOCKET sock, uint32 len) { char errbuf[PCAP_ERRBUF_SIZE + 1]; // keeps the error string, prior to be printed if (len != 0) { if (sock_discard(sock, len, errbuf, PCAP_ERRBUF_SIZE) == -1) { // Network error. rpcapd_log(LOGPRIO_ERROR, "Read from client failed: %s", errbuf); return -1; } } return 0; } // // Shut down any packet-capture thread associated with the session, // close the SSL handle for the data socket if we have one, close // the data socket if we have one, and close the underlying packet // capture handle if we have one. // // We do not, of course, touch the controlling socket that's also // copied into the session, as the service loop might still use it. // static void session_close(struct session *session) { if (session->have_thread) { // // Tell the data connection thread main capture loop to // break out of that loop. // // This may be sufficient to wake up a blocked thread, // but it's not guaranteed to be sufficient. // pcap_breakloop(session->fp); #ifdef _WIN32 // // Set the event on which a read would block, so that, // if it's currently blocked waiting for packets to // arrive, it'll wake up, so it can see the "break // out of the loop" indication. (pcap_breakloop() // might do this, but older versions don't. Setting // it twice should, at worst, cause an extra wakeup, // which shouldn't be a problem.) // // XXX - what about modules other than NPF? // SetEvent(pcap_getevent(session->fp)); // // Wait for the thread to exit, so we don't close // sockets out from under it. // // XXX - have a timeout, so we don't wait forever? // WaitForSingleObject(session->thread, INFINITE); // // Release the thread handle, as we're done with // it. // CloseHandle(session->thread); session->have_thread = 0; session->thread = INVALID_HANDLE_VALUE; #else // // Send a SIGUSR1 signal to the thread, so that, if // it's currently blocked waiting for packets to arrive, // it'll wake up (we've turned off SA_RESTART for // SIGUSR1, so that the system call in which it's blocked // should return EINTR rather than restarting). // pthread_kill(session->thread, SIGUSR1); // // Wait for the thread to exit, so we don't close // sockets out from under it. // // XXX - have a timeout, so we don't wait forever? // pthread_join(session->thread, NULL); session->have_thread = 0; memset(&session->thread, 0, sizeof(session->thread)); #endif } if (session->sockdata != INVALID_SOCKET) { sock_close(session->sockdata, NULL, 0); session->sockdata = INVALID_SOCKET; } if (session->fp) { pcap_close(session->fp); session->fp = NULL; } } // Check whether a capture source string is a URL or not. // This includes URLs that refer to a local device; a scheme, followed // by ://, followed by *another* scheme and ://, is just silly, and // anybody who supplies that will get an error. // static int is_url(const char *source) { char *colonp; /* * RFC 3986 says: * * URI = scheme ":" hier-part [ "?" query ] [ "#" fragment ] * * hier-part = "//" authority path-abempty * / path-absolute * / path-rootless * / path-empty * * authority = [ userinfo "@" ] host [ ":" port ] * * userinfo = *( unreserved / pct-encoded / sub-delims / ":" ) * * Step 1: look for the ":" at the end of the scheme. * A colon in the source is *NOT* sufficient to indicate that * this is a URL, as interface names on some platforms might * include colons (e.g., I think some Solaris interfaces * might). */ colonp = strchr(source, ':'); if (colonp == NULL) { /* * The source is the device to open. It's not a URL. */ return (0); } /* * All schemes must have "//" after them, i.e. we only support * hier-part = "//" authority path-abempty, not * hier-part = path-absolute * hier-part = path-rootless * hier-part = path-empty * * We need that in order to distinguish between a local device * name that happens to contain a colon and a URI. */ if (strncmp(colonp + 1, "//", 2) != 0) { /* * The source is the device to open. It's not a URL. */ return (0); } /* * It's a URL. */ return (1); }
./CrossVul/dataset_final_sorted/CWE-20/c/bad_1022_0
crossvul-cpp_data_good_4965_0
/* * ALSA timer back-end using hrtimer * Copyright (C) 2008 Takashi Iwai * * 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 <linux/init.h> #include <linux/slab.h> #include <linux/module.h> #include <linux/moduleparam.h> #include <linux/hrtimer.h> #include <sound/core.h> #include <sound/timer.h> MODULE_AUTHOR("Takashi Iwai <tiwai@suse.de>"); MODULE_DESCRIPTION("ALSA hrtimer backend"); MODULE_LICENSE("GPL"); MODULE_ALIAS("snd-timer-" __stringify(SNDRV_TIMER_GLOBAL_HRTIMER)); #define NANO_SEC 1000000000UL /* 10^9 in sec */ static unsigned int resolution; struct snd_hrtimer { struct snd_timer *timer; struct hrtimer hrt; atomic_t running; }; static enum hrtimer_restart snd_hrtimer_callback(struct hrtimer *hrt) { struct snd_hrtimer *stime = container_of(hrt, struct snd_hrtimer, hrt); struct snd_timer *t = stime->timer; unsigned long oruns; if (!atomic_read(&stime->running)) return HRTIMER_NORESTART; oruns = hrtimer_forward_now(hrt, ns_to_ktime(t->sticks * resolution)); snd_timer_interrupt(stime->timer, t->sticks * oruns); if (!atomic_read(&stime->running)) return HRTIMER_NORESTART; return HRTIMER_RESTART; } static int snd_hrtimer_open(struct snd_timer *t) { struct snd_hrtimer *stime; stime = kmalloc(sizeof(*stime), GFP_KERNEL); if (!stime) return -ENOMEM; hrtimer_init(&stime->hrt, CLOCK_MONOTONIC, HRTIMER_MODE_REL); stime->timer = t; stime->hrt.function = snd_hrtimer_callback; atomic_set(&stime->running, 0); t->private_data = stime; return 0; } static int snd_hrtimer_close(struct snd_timer *t) { struct snd_hrtimer *stime = t->private_data; if (stime) { hrtimer_cancel(&stime->hrt); kfree(stime); t->private_data = NULL; } return 0; } static int snd_hrtimer_start(struct snd_timer *t) { struct snd_hrtimer *stime = t->private_data; atomic_set(&stime->running, 0); hrtimer_try_to_cancel(&stime->hrt); hrtimer_start(&stime->hrt, ns_to_ktime(t->sticks * resolution), HRTIMER_MODE_REL); atomic_set(&stime->running, 1); return 0; } static int snd_hrtimer_stop(struct snd_timer *t) { struct snd_hrtimer *stime = t->private_data; atomic_set(&stime->running, 0); hrtimer_try_to_cancel(&stime->hrt); return 0; } static struct snd_timer_hardware hrtimer_hw = { .flags = SNDRV_TIMER_HW_AUTO | SNDRV_TIMER_HW_TASKLET, .open = snd_hrtimer_open, .close = snd_hrtimer_close, .start = snd_hrtimer_start, .stop = snd_hrtimer_stop, }; /* * entry functions */ static struct snd_timer *mytimer; static int __init snd_hrtimer_init(void) { struct snd_timer *timer; int err; resolution = hrtimer_resolution; /* Create a new timer and set up the fields */ err = snd_timer_global_new("hrtimer", SNDRV_TIMER_GLOBAL_HRTIMER, &timer); if (err < 0) return err; timer->module = THIS_MODULE; strcpy(timer->name, "HR timer"); timer->hw = hrtimer_hw; timer->hw.resolution = resolution; timer->hw.ticks = NANO_SEC / resolution; err = snd_timer_global_register(timer); if (err < 0) { snd_timer_global_free(timer); return err; } mytimer = timer; /* remember this */ return 0; } static void __exit snd_hrtimer_exit(void) { if (mytimer) { snd_timer_global_free(mytimer); mytimer = NULL; } } module_init(snd_hrtimer_init); module_exit(snd_hrtimer_exit);
./CrossVul/dataset_final_sorted/CWE-20/c/good_4965_0
crossvul-cpp_data_bad_364_2
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % PPPP IIIII CCCC TTTTT % % P P I C T % % PPPP I C T % % P I C T % % P IIIII CCCC T % % % % % % Read/Write Apple Macintosh QuickDraw/PICT Format % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2018 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://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/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/cache.h" #include "MagickCore/color-private.h" #include "MagickCore/colormap.h" #include "MagickCore/colormap-private.h" #include "MagickCore/colorspace.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/composite.h" #include "MagickCore/constitute.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/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/profile.h" #include "MagickCore/resource_.h" #include "MagickCore/quantum-private.h" #include "MagickCore/static.h" #include "MagickCore/string_.h" #include "MagickCore/module.h" #include "MagickCore/transform.h" #include "MagickCore/utility.h" /* ImageMagick Macintosh PICT Methods. */ typedef struct _PICTCode { const char *name; ssize_t length; const char *description; } PICTCode; typedef struct _PICTPixmap { short version, pack_type; size_t pack_size, horizontal_resolution, vertical_resolution; short pixel_type, bits_per_pixel, component_count, component_size; size_t plane_bytes, table, reserved; } PICTPixmap; typedef struct _PICTRectangle { short top, left, bottom, right; } PICTRectangle; static const PICTCode codes[] = { /* 0x00 */ { "NOP", 0, "nop" }, /* 0x01 */ { "Clip", 0, "clip" }, /* 0x02 */ { "BkPat", 8, "background pattern" }, /* 0x03 */ { "TxFont", 2, "text font (word)" }, /* 0x04 */ { "TxFace", 1, "text face (byte)" }, /* 0x05 */ { "TxMode", 2, "text mode (word)" }, /* 0x06 */ { "SpExtra", 4, "space extra (fixed point)" }, /* 0x07 */ { "PnSize", 4, "pen size (point)" }, /* 0x08 */ { "PnMode", 2, "pen mode (word)" }, /* 0x09 */ { "PnPat", 8, "pen pattern" }, /* 0x0a */ { "FillPat", 8, "fill pattern" }, /* 0x0b */ { "OvSize", 4, "oval size (point)" }, /* 0x0c */ { "Origin", 4, "dh, dv (word)" }, /* 0x0d */ { "TxSize", 2, "text size (word)" }, /* 0x0e */ { "FgColor", 4, "foreground color (ssize_tword)" }, /* 0x0f */ { "BkColor", 4, "background color (ssize_tword)" }, /* 0x10 */ { "TxRatio", 8, "numerator (point), denominator (point)" }, /* 0x11 */ { "Version", 1, "version (byte)" }, /* 0x12 */ { "BkPixPat", 0, "color background pattern" }, /* 0x13 */ { "PnPixPat", 0, "color pen pattern" }, /* 0x14 */ { "FillPixPat", 0, "color fill pattern" }, /* 0x15 */ { "PnLocHFrac", 2, "fractional pen position" }, /* 0x16 */ { "ChExtra", 2, "extra for each character" }, /* 0x17 */ { "reserved", 0, "reserved for Apple use" }, /* 0x18 */ { "reserved", 0, "reserved for Apple use" }, /* 0x19 */ { "reserved", 0, "reserved for Apple use" }, /* 0x1a */ { "RGBFgCol", 6, "RGB foreColor" }, /* 0x1b */ { "RGBBkCol", 6, "RGB backColor" }, /* 0x1c */ { "HiliteMode", 0, "hilite mode flag" }, /* 0x1d */ { "HiliteColor", 6, "RGB hilite color" }, /* 0x1e */ { "DefHilite", 0, "Use default hilite color" }, /* 0x1f */ { "OpColor", 6, "RGB OpColor for arithmetic modes" }, /* 0x20 */ { "Line", 8, "pnLoc (point), newPt (point)" }, /* 0x21 */ { "LineFrom", 4, "newPt (point)" }, /* 0x22 */ { "ShortLine", 6, "pnLoc (point, dh, dv (-128 .. 127))" }, /* 0x23 */ { "ShortLineFrom", 2, "dh, dv (-128 .. 127)" }, /* 0x24 */ { "reserved", -1, "reserved for Apple use" }, /* 0x25 */ { "reserved", -1, "reserved for Apple use" }, /* 0x26 */ { "reserved", -1, "reserved for Apple use" }, /* 0x27 */ { "reserved", -1, "reserved for Apple use" }, /* 0x28 */ { "LongText", 0, "txLoc (point), count (0..255), text" }, /* 0x29 */ { "DHText", 0, "dh (0..255), count (0..255), text" }, /* 0x2a */ { "DVText", 0, "dv (0..255), count (0..255), text" }, /* 0x2b */ { "DHDVText", 0, "dh, dv (0..255), count (0..255), text" }, /* 0x2c */ { "reserved", -1, "reserved for Apple use" }, /* 0x2d */ { "reserved", -1, "reserved for Apple use" }, /* 0x2e */ { "reserved", -1, "reserved for Apple use" }, /* 0x2f */ { "reserved", -1, "reserved for Apple use" }, /* 0x30 */ { "frameRect", 8, "rect" }, /* 0x31 */ { "paintRect", 8, "rect" }, /* 0x32 */ { "eraseRect", 8, "rect" }, /* 0x33 */ { "invertRect", 8, "rect" }, /* 0x34 */ { "fillRect", 8, "rect" }, /* 0x35 */ { "reserved", 8, "reserved for Apple use" }, /* 0x36 */ { "reserved", 8, "reserved for Apple use" }, /* 0x37 */ { "reserved", 8, "reserved for Apple use" }, /* 0x38 */ { "frameSameRect", 0, "rect" }, /* 0x39 */ { "paintSameRect", 0, "rect" }, /* 0x3a */ { "eraseSameRect", 0, "rect" }, /* 0x3b */ { "invertSameRect", 0, "rect" }, /* 0x3c */ { "fillSameRect", 0, "rect" }, /* 0x3d */ { "reserved", 0, "reserved for Apple use" }, /* 0x3e */ { "reserved", 0, "reserved for Apple use" }, /* 0x3f */ { "reserved", 0, "reserved for Apple use" }, /* 0x40 */ { "frameRRect", 8, "rect" }, /* 0x41 */ { "paintRRect", 8, "rect" }, /* 0x42 */ { "eraseRRect", 8, "rect" }, /* 0x43 */ { "invertRRect", 8, "rect" }, /* 0x44 */ { "fillRRrect", 8, "rect" }, /* 0x45 */ { "reserved", 8, "reserved for Apple use" }, /* 0x46 */ { "reserved", 8, "reserved for Apple use" }, /* 0x47 */ { "reserved", 8, "reserved for Apple use" }, /* 0x48 */ { "frameSameRRect", 0, "rect" }, /* 0x49 */ { "paintSameRRect", 0, "rect" }, /* 0x4a */ { "eraseSameRRect", 0, "rect" }, /* 0x4b */ { "invertSameRRect", 0, "rect" }, /* 0x4c */ { "fillSameRRect", 0, "rect" }, /* 0x4d */ { "reserved", 0, "reserved for Apple use" }, /* 0x4e */ { "reserved", 0, "reserved for Apple use" }, /* 0x4f */ { "reserved", 0, "reserved for Apple use" }, /* 0x50 */ { "frameOval", 8, "rect" }, /* 0x51 */ { "paintOval", 8, "rect" }, /* 0x52 */ { "eraseOval", 8, "rect" }, /* 0x53 */ { "invertOval", 8, "rect" }, /* 0x54 */ { "fillOval", 8, "rect" }, /* 0x55 */ { "reserved", 8, "reserved for Apple use" }, /* 0x56 */ { "reserved", 8, "reserved for Apple use" }, /* 0x57 */ { "reserved", 8, "reserved for Apple use" }, /* 0x58 */ { "frameSameOval", 0, "rect" }, /* 0x59 */ { "paintSameOval", 0, "rect" }, /* 0x5a */ { "eraseSameOval", 0, "rect" }, /* 0x5b */ { "invertSameOval", 0, "rect" }, /* 0x5c */ { "fillSameOval", 0, "rect" }, /* 0x5d */ { "reserved", 0, "reserved for Apple use" }, /* 0x5e */ { "reserved", 0, "reserved for Apple use" }, /* 0x5f */ { "reserved", 0, "reserved for Apple use" }, /* 0x60 */ { "frameArc", 12, "rect, startAngle, arcAngle" }, /* 0x61 */ { "paintArc", 12, "rect, startAngle, arcAngle" }, /* 0x62 */ { "eraseArc", 12, "rect, startAngle, arcAngle" }, /* 0x63 */ { "invertArc", 12, "rect, startAngle, arcAngle" }, /* 0x64 */ { "fillArc", 12, "rect, startAngle, arcAngle" }, /* 0x65 */ { "reserved", 12, "reserved for Apple use" }, /* 0x66 */ { "reserved", 12, "reserved for Apple use" }, /* 0x67 */ { "reserved", 12, "reserved for Apple use" }, /* 0x68 */ { "frameSameArc", 4, "rect, startAngle, arcAngle" }, /* 0x69 */ { "paintSameArc", 4, "rect, startAngle, arcAngle" }, /* 0x6a */ { "eraseSameArc", 4, "rect, startAngle, arcAngle" }, /* 0x6b */ { "invertSameArc", 4, "rect, startAngle, arcAngle" }, /* 0x6c */ { "fillSameArc", 4, "rect, startAngle, arcAngle" }, /* 0x6d */ { "reserved", 4, "reserved for Apple use" }, /* 0x6e */ { "reserved", 4, "reserved for Apple use" }, /* 0x6f */ { "reserved", 4, "reserved for Apple use" }, /* 0x70 */ { "framePoly", 0, "poly" }, /* 0x71 */ { "paintPoly", 0, "poly" }, /* 0x72 */ { "erasePoly", 0, "poly" }, /* 0x73 */ { "invertPoly", 0, "poly" }, /* 0x74 */ { "fillPoly", 0, "poly" }, /* 0x75 */ { "reserved", 0, "reserved for Apple use" }, /* 0x76 */ { "reserved", 0, "reserved for Apple use" }, /* 0x77 */ { "reserved", 0, "reserved for Apple use" }, /* 0x78 */ { "frameSamePoly", 0, "poly (NYI)" }, /* 0x79 */ { "paintSamePoly", 0, "poly (NYI)" }, /* 0x7a */ { "eraseSamePoly", 0, "poly (NYI)" }, /* 0x7b */ { "invertSamePoly", 0, "poly (NYI)" }, /* 0x7c */ { "fillSamePoly", 0, "poly (NYI)" }, /* 0x7d */ { "reserved", 0, "reserved for Apple use" }, /* 0x7e */ { "reserved", 0, "reserved for Apple use" }, /* 0x7f */ { "reserved", 0, "reserved for Apple use" }, /* 0x80 */ { "frameRgn", 0, "region" }, /* 0x81 */ { "paintRgn", 0, "region" }, /* 0x82 */ { "eraseRgn", 0, "region" }, /* 0x83 */ { "invertRgn", 0, "region" }, /* 0x84 */ { "fillRgn", 0, "region" }, /* 0x85 */ { "reserved", 0, "reserved for Apple use" }, /* 0x86 */ { "reserved", 0, "reserved for Apple use" }, /* 0x87 */ { "reserved", 0, "reserved for Apple use" }, /* 0x88 */ { "frameSameRgn", 0, "region (NYI)" }, /* 0x89 */ { "paintSameRgn", 0, "region (NYI)" }, /* 0x8a */ { "eraseSameRgn", 0, "region (NYI)" }, /* 0x8b */ { "invertSameRgn", 0, "region (NYI)" }, /* 0x8c */ { "fillSameRgn", 0, "region (NYI)" }, /* 0x8d */ { "reserved", 0, "reserved for Apple use" }, /* 0x8e */ { "reserved", 0, "reserved for Apple use" }, /* 0x8f */ { "reserved", 0, "reserved for Apple use" }, /* 0x90 */ { "BitsRect", 0, "copybits, rect clipped" }, /* 0x91 */ { "BitsRgn", 0, "copybits, rgn clipped" }, /* 0x92 */ { "reserved", -1, "reserved for Apple use" }, /* 0x93 */ { "reserved", -1, "reserved for Apple use" }, /* 0x94 */ { "reserved", -1, "reserved for Apple use" }, /* 0x95 */ { "reserved", -1, "reserved for Apple use" }, /* 0x96 */ { "reserved", -1, "reserved for Apple use" }, /* 0x97 */ { "reserved", -1, "reserved for Apple use" }, /* 0x98 */ { "PackBitsRect", 0, "packed copybits, rect clipped" }, /* 0x99 */ { "PackBitsRgn", 0, "packed copybits, rgn clipped" }, /* 0x9a */ { "DirectBitsRect", 0, "PixMap, srcRect, dstRect, mode, PixData" }, /* 0x9b */ { "DirectBitsRgn", 0, "PixMap, srcRect, dstRect, mode, maskRgn, PixData" }, /* 0x9c */ { "reserved", -1, "reserved for Apple use" }, /* 0x9d */ { "reserved", -1, "reserved for Apple use" }, /* 0x9e */ { "reserved", -1, "reserved for Apple use" }, /* 0x9f */ { "reserved", -1, "reserved for Apple use" }, /* 0xa0 */ { "ShortComment", 2, "kind (word)" }, /* 0xa1 */ { "LongComment", 0, "kind (word), size (word), data" } }; /* Forward declarations. */ static MagickBooleanType WritePICTImage(const ImageInfo *,Image *,ExceptionInfo *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e c o d e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DecodeImage decompresses an image via Macintosh pack bits decoding for % Macintosh PICT images. % % The format of the DecodeImage method is: % % unsigned char *DecodeImage(Image *blob,Image *image, % size_t bytes_per_line,const int bits_per_pixel, % unsigned size_t extent) % % A description of each parameter follows: % % o image_info: the image info. % % o blob,image: the address of a structure of type Image. % % o bytes_per_line: This integer identifies the number of bytes in a % scanline. % % o bits_per_pixel: the number of bits in a pixel. % % o extent: the number of pixels allocated. % */ static unsigned char *ExpandBuffer(unsigned char *pixels, MagickSizeType *bytes_per_line,const unsigned int bits_per_pixel) { register ssize_t i; register unsigned char *p, *q; static unsigned char scanline[8*256]; p=pixels; q=scanline; switch (bits_per_pixel) { case 8: case 16: case 32: return(pixels); case 4: { for (i=0; i < (ssize_t) *bytes_per_line; i++) { *q++=(*p >> 4) & 0xff; *q++=(*p & 15); p++; } *bytes_per_line*=2; break; } case 2: { for (i=0; i < (ssize_t) *bytes_per_line; i++) { *q++=(*p >> 6) & 0x03; *q++=(*p >> 4) & 0x03; *q++=(*p >> 2) & 0x03; *q++=(*p & 3); p++; } *bytes_per_line*=4; break; } case 1: { for (i=0; i < (ssize_t) *bytes_per_line; i++) { *q++=(*p >> 7) & 0x01; *q++=(*p >> 6) & 0x01; *q++=(*p >> 5) & 0x01; *q++=(*p >> 4) & 0x01; *q++=(*p >> 3) & 0x01; *q++=(*p >> 2) & 0x01; *q++=(*p >> 1) & 0x01; *q++=(*p & 0x01); p++; } *bytes_per_line*=8; break; } default: break; } return(scanline); } static unsigned char *DecodeImage(Image *blob,Image *image, size_t bytes_per_line,const unsigned int bits_per_pixel,size_t *extent) { MagickBooleanType status; MagickSizeType number_pixels; register ssize_t i; register unsigned char *p, *q; size_t bytes_per_pixel, length, row_bytes, scanline_length, width; ssize_t count, j, y; unsigned char *pixels, *scanline; /* Determine pixel buffer size. */ if (bits_per_pixel <= 8) bytes_per_line&=0x7fff; width=image->columns; bytes_per_pixel=1; if (bits_per_pixel == 16) { bytes_per_pixel=2; width*=2; } else if (bits_per_pixel == 32) width*=image->alpha_trait ? 4 : 3; if (bytes_per_line == 0) bytes_per_line=width; row_bytes=(size_t) (image->columns | 0x8000); if (image->storage_class == DirectClass) row_bytes=(size_t) ((4*image->columns) | 0x8000); /* Allocate pixel and scanline buffer. */ pixels=(unsigned char *) AcquireQuantumMemory(image->rows,row_bytes* sizeof(*pixels)); if (pixels == (unsigned char *) NULL) return((unsigned char *) NULL); *extent=row_bytes*image->rows*sizeof(*pixels); (void) memset(pixels,0,*extent); scanline=(unsigned char *) AcquireQuantumMemory(row_bytes,2* sizeof(*scanline)); if (scanline == (unsigned char *) NULL) { pixels=(unsigned char *) RelinquishMagickMemory(pixels); return((unsigned char *) NULL); } (void) memset(scanline,0,2*row_bytes*sizeof(*scanline)); status=MagickTrue; if (bytes_per_line < 8) { /* Pixels are already uncompressed. */ for (y=0; y < (ssize_t) image->rows; y++) { q=pixels+y*width*GetPixelChannels(image); number_pixels=bytes_per_line; count=ReadBlob(blob,(size_t) number_pixels,scanline); if (count != (ssize_t) number_pixels) { status=MagickFalse; break; } p=ExpandBuffer(scanline,&number_pixels,bits_per_pixel); if ((q+number_pixels) > (pixels+(*extent))) { status=MagickFalse; break; } (void) memcpy(q,p,(size_t) number_pixels); } scanline=(unsigned char *) RelinquishMagickMemory(scanline); if (status == MagickFalse) pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(pixels); } /* Uncompress RLE pixels into uncompressed pixel buffer. */ for (y=0; y < (ssize_t) image->rows; y++) { q=pixels+y*width; if (bytes_per_line > 200) scanline_length=ReadBlobMSBShort(blob); else scanline_length=(size_t) ReadBlobByte(blob); if ((scanline_length >= row_bytes) || (scanline_length == 0)) { status=MagickFalse; break; } count=ReadBlob(blob,scanline_length,scanline); if (count != (ssize_t) scanline_length) { status=MagickFalse; break; } for (j=0; j < (ssize_t) scanline_length; ) if ((scanline[j] & 0x80) == 0) { length=(size_t) ((scanline[j] & 0xff)+1); number_pixels=length*bytes_per_pixel; p=ExpandBuffer(scanline+j+1,&number_pixels,bits_per_pixel); if ((q-pixels+number_pixels) <= *extent) (void) memcpy(q,p,(size_t) number_pixels); q+=number_pixels; j+=(ssize_t) (length*bytes_per_pixel+1); } else { length=(size_t) (((scanline[j] ^ 0xff) & 0xff)+2); number_pixels=bytes_per_pixel; p=ExpandBuffer(scanline+j+1,&number_pixels,bits_per_pixel); for (i=0; i < (ssize_t) length; i++) { if ((q-pixels+number_pixels) <= *extent) (void) memcpy(q,p,(size_t) number_pixels); q+=number_pixels; } j+=(ssize_t) bytes_per_pixel+1; } } scanline=(unsigned char *) RelinquishMagickMemory(scanline); if (status == MagickFalse) pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % E n c o d e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % EncodeImage compresses an image via Macintosh pack bits encoding % for Macintosh PICT images. % % The format of the EncodeImage method is: % % size_t EncodeImage(Image *image,const unsigned char *scanline, % const size_t bytes_per_line,unsigned char *pixels) % % A description of each parameter follows: % % o image: the address of a structure of type Image. % % o scanline: A pointer to an array of characters to pack. % % o bytes_per_line: the number of bytes in a scanline. % % o pixels: A pointer to an array of characters where the packed % characters are stored. % */ static size_t EncodeImage(Image *image,const unsigned char *scanline, const size_t bytes_per_line,unsigned char *pixels) { #define MaxCount 128 #define MaxPackbitsRunlength 128 register const unsigned char *p; register ssize_t i; register unsigned char *q; size_t length; ssize_t count, repeat_count, runlength; unsigned char index; /* Pack scanline. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(scanline != (unsigned char *) NULL); assert(pixels != (unsigned char *) NULL); count=0; runlength=0; p=scanline+(bytes_per_line-1); q=pixels; index=(*p); for (i=(ssize_t) bytes_per_line-1; i >= 0; i--) { if (index == *p) runlength++; else { if (runlength < 3) while (runlength > 0) { *q++=(unsigned char) index; runlength--; count++; if (count == MaxCount) { *q++=(unsigned char) (MaxCount-1); count-=MaxCount; } } else { if (count > 0) *q++=(unsigned char) (count-1); count=0; while (runlength > 0) { repeat_count=runlength; if (repeat_count > MaxPackbitsRunlength) repeat_count=MaxPackbitsRunlength; *q++=(unsigned char) index; *q++=(unsigned char) (257-repeat_count); runlength-=repeat_count; } } runlength=1; } index=(*p); p--; } if (runlength < 3) while (runlength > 0) { *q++=(unsigned char) index; runlength--; count++; if (count == MaxCount) { *q++=(unsigned char) (MaxCount-1); count-=MaxCount; } } else { if (count > 0) *q++=(unsigned char) (count-1); count=0; while (runlength > 0) { repeat_count=runlength; if (repeat_count > MaxPackbitsRunlength) repeat_count=MaxPackbitsRunlength; *q++=(unsigned char) index; *q++=(unsigned char) (257-repeat_count); runlength-=repeat_count; } } if (count > 0) *q++=(unsigned char) (count-1); /* Write the number of and the packed length. */ length=(size_t) (q-pixels); if (bytes_per_line > 200) { (void) WriteBlobMSBShort(image,(unsigned short) length); length+=2; } else { (void) WriteBlobByte(image,(unsigned char) length); length++; } while (q != pixels) { q--; (void) WriteBlobByte(image,*q); } return(length); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s P I C T % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsPICT()() returns MagickTrue if the image format type, identified by the % magick string, is PICT. % % The format of the ReadPICTImage method is: % % MagickBooleanType IsPICT(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 IsPICT(const unsigned char *magick,const size_t length) { if (length < 12) return(MagickFalse); /* Embedded OLE2 macintosh have "PICT" instead of 512 platform header. */ if (memcmp(magick,"PICT",4) == 0) return(MagickTrue); if (length < 528) return(MagickFalse); if (memcmp(magick+522,"\000\021\002\377\014\000",6) == 0) return(MagickTrue); return(MagickFalse); } #if !defined(macintosh) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d P I C T I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadPICTImage() reads an Apple Macintosh QuickDraw/PICT 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 ReadPICTImage method is: % % Image *ReadPICTImage(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 MagickBooleanType ReadPixmap(Image *image,PICTPixmap *pixmap) { pixmap->version=(short) ReadBlobMSBShort(image); pixmap->pack_type=(short) ReadBlobMSBShort(image); pixmap->pack_size=ReadBlobMSBLong(image); pixmap->horizontal_resolution=1UL*ReadBlobMSBShort(image); (void) ReadBlobMSBShort(image); pixmap->vertical_resolution=1UL*ReadBlobMSBShort(image); (void) ReadBlobMSBShort(image); pixmap->pixel_type=(short) ReadBlobMSBShort(image); pixmap->bits_per_pixel=(short) ReadBlobMSBShort(image); pixmap->component_count=(short) ReadBlobMSBShort(image); pixmap->component_size=(short) ReadBlobMSBShort(image); pixmap->plane_bytes=ReadBlobMSBLong(image); pixmap->table=ReadBlobMSBLong(image); pixmap->reserved=ReadBlobMSBLong(image); if ((EOFBlob(image) != MagickFalse) || (pixmap->bits_per_pixel <= 0) || (pixmap->bits_per_pixel > 32) || (pixmap->component_count <= 0) || (pixmap->component_count > 4) || (pixmap->component_size <= 0)) return(MagickFalse); return(MagickTrue); } static MagickBooleanType ReadRectangle(Image *image,PICTRectangle *rectangle) { rectangle->top=(short) ReadBlobMSBShort(image); rectangle->left=(short) ReadBlobMSBShort(image); rectangle->bottom=(short) ReadBlobMSBShort(image); rectangle->right=(short) ReadBlobMSBShort(image); if ((EOFBlob(image) != MagickFalse) || ((rectangle->bottom-rectangle->top) <= 0) || ((rectangle->right-rectangle->left) <= 0)) return(MagickFalse); return(MagickTrue); } static Image *ReadPICTImage(const ImageInfo *image_info, ExceptionInfo *exception) { #define ThrowPICTException(exception,message) \ { \ if (tile_image != (Image *) NULL) \ tile_image=DestroyImage(tile_image); \ if (read_info != (ImageInfo *) NULL) \ read_info=DestroyImageInfo(read_info); \ ThrowReaderException((exception),(message)); \ } char geometry[MagickPathExtent], header_ole[4]; Image *image, *tile_image; ImageInfo *read_info; int c, code; MagickBooleanType jpeg, status; PICTRectangle frame; PICTPixmap pixmap; Quantum index; register Quantum *q; register ssize_t i, x; size_t extent, length; ssize_t count, flags, j, version, y; StringInfo *profile; /* 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 PICT header. */ read_info=(ImageInfo *) NULL; tile_image=(Image *) NULL; pixmap.bits_per_pixel=0; pixmap.component_count=0; /* Skip header : 512 for standard PICT and 4, ie "PICT" for OLE2. */ header_ole[0]=ReadBlobByte(image); header_ole[1]=ReadBlobByte(image); header_ole[2]=ReadBlobByte(image); header_ole[3]=ReadBlobByte(image); if (!((header_ole[0] == 0x50) && (header_ole[1] == 0x49) && (header_ole[2] == 0x43) && (header_ole[3] == 0x54 ))) for (i=0; i < 508; i++) if (ReadBlobByte(image) == EOF) break; (void) ReadBlobMSBShort(image); /* skip picture size */ if (ReadRectangle(image,&frame) == MagickFalse) ThrowPICTException(CorruptImageError,"ImproperImageHeader"); while ((c=ReadBlobByte(image)) == 0) ; if (c != 0x11) ThrowPICTException(CorruptImageError,"ImproperImageHeader"); version=(ssize_t) ReadBlobByte(image); if (version == 2) { c=ReadBlobByte(image); if (c != 0xff) ThrowPICTException(CorruptImageError,"ImproperImageHeader"); } else if (version != 1) ThrowPICTException(CorruptImageError,"ImproperImageHeader"); if ((frame.left < 0) || (frame.right < 0) || (frame.top < 0) || (frame.bottom < 0) || (frame.left >= frame.right) || (frame.top >= frame.bottom)) ThrowPICTException(CorruptImageError,"ImproperImageHeader"); /* Create black canvas. */ flags=0; image->depth=8; image->columns=(size_t) (frame.right-frame.left); image->rows=(size_t) (frame.bottom-frame.top); image->resolution.x=DefaultResolution; image->resolution.y=DefaultResolution; image->units=UndefinedResolution; if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } status=SetImageExtent(image,image->columns,image->rows,exception); if (status != MagickFalse) status=ResetImagePixels(image,exception); if (status == MagickFalse) return(DestroyImageList(image)); /* Interpret PICT opcodes. */ jpeg=MagickFalse; for (code=0; EOFBlob(image) == MagickFalse; ) { if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; if ((version == 1) || ((TellBlob(image) % 2) != 0)) code=ReadBlobByte(image); if (version == 2) code=ReadBlobMSBSignedShort(image); if (code < 0) break; if (code == 0) continue; if (code > 0xa1) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"%04X:",code); } else { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " %04X %s: %s",code,codes[code].name,codes[code].description); switch (code) { case 0x01: { /* Clipping rectangle. */ length=ReadBlobMSBShort(image); if (length != 0x000a) { for (i=0; i < (ssize_t) (length-2); i++) if (ReadBlobByte(image) == EOF) break; break; } if (ReadRectangle(image,&frame) == MagickFalse) ThrowPICTException(CorruptImageError,"ImproperImageHeader"); if (((frame.left & 0x8000) != 0) || ((frame.top & 0x8000) != 0)) break; image->columns=(size_t) (frame.right-frame.left); image->rows=(size_t) (frame.bottom-frame.top); status=SetImageExtent(image,image->columns,image->rows,exception); if (status != MagickFalse) status=ResetImagePixels(image,exception); if (status == MagickFalse) return(DestroyImageList(image)); break; } case 0x12: case 0x13: case 0x14: { ssize_t pattern; size_t height, width; /* Skip pattern definition. */ pattern=(ssize_t) ReadBlobMSBShort(image); for (i=0; i < 8; i++) if (ReadBlobByte(image) == EOF) break; if (pattern == 2) { for (i=0; i < 5; i++) if (ReadBlobByte(image) == EOF) break; break; } if (pattern != 1) ThrowPICTException(CorruptImageError,"UnknownPatternType"); length=ReadBlobMSBShort(image); if (ReadRectangle(image,&frame) == MagickFalse) ThrowPICTException(CorruptImageError,"ImproperImageHeader"); if (ReadPixmap(image,&pixmap) == MagickFalse) ThrowPICTException(CorruptImageError,"ImproperImageHeader"); image->depth=(size_t) pixmap.component_size; image->resolution.x=1.0*pixmap.horizontal_resolution; image->resolution.y=1.0*pixmap.vertical_resolution; image->units=PixelsPerInchResolution; (void) ReadBlobMSBLong(image); flags=(ssize_t) ReadBlobMSBShort(image); length=ReadBlobMSBShort(image); for (i=0; i <= (ssize_t) length; i++) (void) ReadBlobMSBLong(image); width=(size_t) (frame.bottom-frame.top); height=(size_t) (frame.right-frame.left); if (pixmap.bits_per_pixel <= 8) length&=0x7fff; if (pixmap.bits_per_pixel == 16) width<<=1; if (length == 0) length=width; if (length < 8) { for (i=0; i < (ssize_t) (length*height); i++) if (ReadBlobByte(image) == EOF) break; } else for (i=0; i < (ssize_t) height; i++) { if (EOFBlob(image) != MagickFalse) break; if (length > 200) { for (j=0; j < (ssize_t) ReadBlobMSBShort(image); j++) if (ReadBlobByte(image) == EOF) break; } else for (j=0; j < (ssize_t) ReadBlobByte(image); j++) if (ReadBlobByte(image) == EOF) break; } break; } case 0x1b: { /* Initialize image background color. */ image->background_color.red=(Quantum) ScaleShortToQuantum(ReadBlobMSBShort(image)); image->background_color.green=(Quantum) ScaleShortToQuantum(ReadBlobMSBShort(image)); image->background_color.blue=(Quantum) ScaleShortToQuantum(ReadBlobMSBShort(image)); break; } case 0x70: case 0x71: case 0x72: case 0x73: case 0x74: case 0x75: case 0x76: case 0x77: { /* Skip polygon or region. */ length=ReadBlobMSBShort(image); for (i=0; i < (ssize_t) (length-2); i++) if (ReadBlobByte(image) == EOF) break; break; } case 0x90: case 0x91: case 0x98: case 0x99: case 0x9a: case 0x9b: { PICTRectangle source, destination; register unsigned char *p; size_t j; ssize_t bytes_per_line; unsigned char *pixels; /* Pixmap clipped by a rectangle. */ bytes_per_line=0; if ((code != 0x9a) && (code != 0x9b)) bytes_per_line=(ssize_t) ReadBlobMSBShort(image); else { (void) ReadBlobMSBShort(image); (void) ReadBlobMSBShort(image); (void) ReadBlobMSBShort(image); } if (ReadRectangle(image,&frame) == MagickFalse) ThrowPICTException(CorruptImageError,"ImproperImageHeader"); /* Initialize tile image. */ tile_image=CloneImage(image,(size_t) (frame.right-frame.left), (size_t) (frame.bottom-frame.top),MagickTrue,exception); if (tile_image == (Image *) NULL) ThrowPICTException(CorruptImageError,"ImproperImageHeader"); if ((code == 0x9a) || (code == 0x9b) || ((bytes_per_line & 0x8000) != 0)) { if (ReadPixmap(image,&pixmap) == MagickFalse) ThrowPICTException(CorruptImageError,"ImproperImageHeader"); tile_image->depth=(size_t) pixmap.component_size; tile_image->alpha_trait=pixmap.component_count == 4 ? BlendPixelTrait : UndefinedPixelTrait; tile_image->resolution.x=(double) pixmap.horizontal_resolution; tile_image->resolution.y=(double) pixmap.vertical_resolution; tile_image->units=PixelsPerInchResolution; if (tile_image->alpha_trait != UndefinedPixelTrait) (void) SetImageAlpha(tile_image,OpaqueAlpha,exception); } if ((code != 0x9a) && (code != 0x9b)) { /* Initialize colormap. */ tile_image->colors=2; if ((bytes_per_line & 0x8000) != 0) { (void) ReadBlobMSBLong(image); flags=(ssize_t) ReadBlobMSBShort(image); tile_image->colors=1UL*ReadBlobMSBShort(image)+1; } status=AcquireImageColormap(tile_image,tile_image->colors, exception); if (status == MagickFalse) ThrowPICTException(ResourceLimitError, "MemoryAllocationFailed"); if ((bytes_per_line & 0x8000) != 0) { for (i=0; i < (ssize_t) tile_image->colors; i++) { j=ReadBlobMSBShort(image) % tile_image->colors; if ((flags & 0x8000) != 0) j=(size_t) i; tile_image->colormap[j].red=(Quantum) ScaleShortToQuantum(ReadBlobMSBShort(image)); tile_image->colormap[j].green=(Quantum) ScaleShortToQuantum(ReadBlobMSBShort(image)); tile_image->colormap[j].blue=(Quantum) ScaleShortToQuantum(ReadBlobMSBShort(image)); } } else { for (i=0; i < (ssize_t) tile_image->colors; i++) { tile_image->colormap[i].red=(Quantum) (QuantumRange- tile_image->colormap[i].red); tile_image->colormap[i].green=(Quantum) (QuantumRange- tile_image->colormap[i].green); tile_image->colormap[i].blue=(Quantum) (QuantumRange- tile_image->colormap[i].blue); } } } if (EOFBlob(image) != MagickFalse) ThrowPICTException(CorruptImageError, "InsufficientImageDataInFile"); if (ReadRectangle(image,&source) == MagickFalse) ThrowPICTException(CorruptImageError,"ImproperImageHeader"); if (ReadRectangle(image,&destination) == MagickFalse) ThrowPICTException(CorruptImageError,"ImproperImageHeader"); (void) ReadBlobMSBShort(image); if ((code == 0x91) || (code == 0x99) || (code == 0x9b)) { /* Skip region. */ length=ReadBlobMSBShort(image); for (i=0; i < (ssize_t) (length-2); i++) if (ReadBlobByte(image) == EOF) break; } if ((code != 0x9a) && (code != 0x9b) && (bytes_per_line & 0x8000) == 0) pixels=DecodeImage(image,tile_image,(size_t) bytes_per_line,1, &extent); else pixels=DecodeImage(image,tile_image,(size_t) bytes_per_line, (unsigned int) pixmap.bits_per_pixel,&extent); if (pixels == (unsigned char *) NULL) ThrowPICTException(CorruptImageError,"UnableToUncompressImage"); /* Convert PICT tile image to pixel packets. */ p=pixels; for (y=0; y < (ssize_t) tile_image->rows; y++) { if (p > (pixels+extent+image->columns)) { pixels=(unsigned char *) RelinquishMagickMemory(pixels); ThrowPICTException(CorruptImageError,"NotEnoughPixelData"); } q=QueueAuthenticPixels(tile_image,0,y,tile_image->columns,1, exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) tile_image->columns; x++) { if (tile_image->storage_class == PseudoClass) { index=(Quantum) ConstrainColormapIndex(tile_image,(ssize_t) *p,exception); SetPixelIndex(tile_image,index,q); SetPixelRed(tile_image, tile_image->colormap[(ssize_t) index].red,q); SetPixelGreen(tile_image, tile_image->colormap[(ssize_t) index].green,q); SetPixelBlue(tile_image, tile_image->colormap[(ssize_t) index].blue,q); } else { if (pixmap.bits_per_pixel == 16) { i=(ssize_t) (*p++); j=(size_t) (*p); SetPixelRed(tile_image,ScaleCharToQuantum( (unsigned char) ((i & 0x7c) << 1)),q); SetPixelGreen(tile_image,ScaleCharToQuantum( (unsigned char) (((i & 0x03) << 6) | ((j & 0xe0) >> 2))),q); SetPixelBlue(tile_image,ScaleCharToQuantum( (unsigned char) ((j & 0x1f) << 3)),q); } else if (tile_image->alpha_trait == UndefinedPixelTrait) { if (p > (pixels+extent+2*image->columns)) ThrowPICTException(CorruptImageError, "NotEnoughPixelData"); SetPixelRed(tile_image,ScaleCharToQuantum(*p),q); SetPixelGreen(tile_image,ScaleCharToQuantum( *(p+tile_image->columns)),q); SetPixelBlue(tile_image,ScaleCharToQuantum( *(p+2*tile_image->columns)),q); } else { if (p > (pixels+extent+3*image->columns)) ThrowPICTException(CorruptImageError, "NotEnoughPixelData"); SetPixelAlpha(tile_image,ScaleCharToQuantum(*p),q); SetPixelRed(tile_image,ScaleCharToQuantum( *(p+tile_image->columns)),q); SetPixelGreen(tile_image,ScaleCharToQuantum( *(p+2*tile_image->columns)),q); SetPixelBlue(tile_image,ScaleCharToQuantum( *(p+3*tile_image->columns)),q); } } p++; q+=GetPixelChannels(tile_image); } if (SyncAuthenticPixels(tile_image,exception) == MagickFalse) break; if ((tile_image->storage_class == DirectClass) && (pixmap.bits_per_pixel != 16)) { p+=(pixmap.component_count-1)*tile_image->columns; if (p < pixels) break; } status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, tile_image->rows); if (status == MagickFalse) break; } pixels=(unsigned char *) RelinquishMagickMemory(pixels); if ((jpeg == MagickFalse) && (EOFBlob(image) == MagickFalse)) if ((code == 0x9a) || (code == 0x9b) || ((bytes_per_line & 0x8000) != 0)) (void) CompositeImage(image,tile_image,CopyCompositeOp, MagickTrue,(ssize_t) destination.left,(ssize_t) destination.top,exception); tile_image=DestroyImage(tile_image); break; } case 0xa1: { unsigned char *info; size_t type; /* Comment. */ type=ReadBlobMSBShort(image); length=ReadBlobMSBShort(image); if (length == 0) break; (void) ReadBlobMSBLong(image); length-=MagickMin(length,4); if (length == 0) break; info=(unsigned char *) AcquireQuantumMemory(length,sizeof(*info)); if (info == (unsigned char *) NULL) break; count=ReadBlob(image,length,info); if (count != (ssize_t) length) { info=(unsigned char *) RelinquishMagickMemory(info); ThrowPICTException(ResourceLimitError,"UnableToReadImageData"); } switch (type) { case 0xe0: { profile=BlobToStringInfo((const void *) NULL,length); SetStringInfoDatum(profile,info); status=SetImageProfile(image,"icc",profile,exception); profile=DestroyStringInfo(profile); if (status == MagickFalse) { info=(unsigned char *) RelinquishMagickMemory(info); ThrowPICTException(ResourceLimitError, "MemoryAllocationFailed"); } break; } case 0x1f2: { profile=BlobToStringInfo((const void *) NULL,length); SetStringInfoDatum(profile,info); status=SetImageProfile(image,"iptc",profile,exception); if (status == MagickFalse) { info=(unsigned char *) RelinquishMagickMemory(info); ThrowPICTException(ResourceLimitError, "MemoryAllocationFailed"); } profile=DestroyStringInfo(profile); break; } default: break; } info=(unsigned char *) RelinquishMagickMemory(info); break; } default: { /* Skip to next op code. */ if (codes[code].length == -1) (void) ReadBlobMSBShort(image); else for (i=0; i < (ssize_t) codes[code].length; i++) if (ReadBlobByte(image) == EOF) break; } } } if (code == 0xc00) { /* Skip header. */ for (i=0; i < 24; i++) if (ReadBlobByte(image) == EOF) break; continue; } if (((code >= 0xb0) && (code <= 0xcf)) || ((code >= 0x8000) && (code <= 0x80ff))) continue; if (code == 0x8200) { char filename[MaxTextExtent]; FILE *file; int unique_file; /* Embedded JPEG. */ jpeg=MagickTrue; read_info=CloneImageInfo(image_info); SetImageInfoBlob(read_info,(void *) NULL,0); file=(FILE *) NULL; unique_file=AcquireUniqueFileResource(filename); (void) FormatLocaleString(read_info->filename,MaxTextExtent,"jpeg:%s", filename); if (unique_file != -1) file=fdopen(unique_file,"wb"); if ((unique_file == -1) || (file == (FILE *) NULL)) { (void) RelinquishUniqueFileResource(read_info->filename); (void) CopyMagickString(image->filename,read_info->filename, MagickPathExtent); ThrowPICTException(FileOpenError,"UnableToCreateTemporaryFile"); } length=ReadBlobMSBLong(image); if (length > 154) { for (i=0; i < 6; i++) (void) ReadBlobMSBLong(image); if (ReadRectangle(image,&frame) == MagickFalse) { (void) fclose(file); (void) RelinquishUniqueFileResource(read_info->filename); ThrowPICTException(CorruptImageError,"ImproperImageHeader"); } for (i=0; i < 122; i++) if (ReadBlobByte(image) == EOF) break; for (i=0; i < (ssize_t) (length-154); i++) { c=ReadBlobByte(image); if (c == EOF) break; (void) fputc(c,file); } } (void) fclose(file); (void) close(unique_file); tile_image=ReadImage(read_info,exception); (void) RelinquishUniqueFileResource(filename); read_info=DestroyImageInfo(read_info); if (tile_image == (Image *) NULL) continue; (void) FormatLocaleString(geometry,MagickPathExtent,"%.20gx%.20g", (double) MagickMax(image->columns,tile_image->columns), (double) MagickMax(image->rows,tile_image->rows)); (void) SetImageExtent(image, MagickMax(image->columns,tile_image->columns), MagickMax(image->rows,tile_image->rows),exception); (void) TransformImageColorspace(image,tile_image->colorspace,exception); (void) CompositeImage(image,tile_image,CopyCompositeOp,MagickTrue, (ssize_t) frame.left,(ssize_t) frame.right,exception); image->compression=tile_image->compression; tile_image=DestroyImage(tile_image); continue; } if ((code == 0xff) || (code == 0xffff)) break; if (((code >= 0xd0) && (code <= 0xfe)) || ((code >= 0x8100) && (code <= 0xffff))) { /* Skip reserved. */ length=ReadBlobMSBShort(image); for (i=0; i < (ssize_t) length; i++) if (ReadBlobByte(image) == EOF) break; continue; } if ((code >= 0x100) && (code <= 0x7fff)) { /* Skip reserved. */ length=(size_t) ((code >> 7) & 0xff); for (i=0; i < (ssize_t) length; i++) if (ReadBlobByte(image) == EOF) break; continue; } } (void) CloseBlob(image); return(GetFirstImageInList(image)); } #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r P I C T I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterPICTImage() adds attributes for the PICT 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 RegisterPICTImage method is: % % size_t RegisterPICTImage(void) % */ ModuleExport size_t RegisterPICTImage(void) { MagickInfo *entry; entry=AcquireMagickInfo("PICT","PCT","Apple Macintosh QuickDraw/PICT"); entry->decoder=(DecodeImageHandler *) ReadPICTImage; entry->encoder=(EncodeImageHandler *) WritePICTImage; entry->flags^=CoderAdjoinFlag; entry->flags|=CoderEncoderSeekableStreamFlag; entry->magick=(IsImageFormatHandler *) IsPICT; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PICT","PICT","Apple Macintosh QuickDraw/PICT"); entry->decoder=(DecodeImageHandler *) ReadPICTImage; entry->encoder=(EncodeImageHandler *) WritePICTImage; entry->flags^=CoderAdjoinFlag; entry->flags|=CoderEncoderSeekableStreamFlag; entry->magick=(IsImageFormatHandler *) IsPICT; (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r P I C T I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterPICTImage() removes format registrations made by the % PICT module from the list of supported formats. % % The format of the UnregisterPICTImage method is: % % UnregisterPICTImage(void) % */ ModuleExport void UnregisterPICTImage(void) { (void) UnregisterMagickInfo("PCT"); (void) UnregisterMagickInfo("PICT"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e P I C T I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WritePICTImage() writes an image to a file in the Apple Macintosh % QuickDraw/PICT image format. % % The format of the WritePICTImage method is: % % MagickBooleanType WritePICTImage(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 WritePICTImage(const ImageInfo *image_info, Image *image,ExceptionInfo *exception) { #define MaxCount 128 #define PictCropRegionOp 0x01 #define PictEndOfPictureOp 0xff #define PictJPEGOp 0x8200 #define PictInfoOp 0x0C00 #define PictInfoSize 512 #define PictPixmapOp 0x9A #define PictPICTOp 0x98 #define PictVersion 0x11 const StringInfo *profile; double x_resolution, y_resolution; MagickBooleanType status; MagickOffsetType offset; PICTPixmap pixmap; PICTRectangle bounds, crop_rectangle, destination_rectangle, frame_rectangle, size_rectangle, source_rectangle; register const Quantum *p; register ssize_t i, x; size_t bytes_per_line, count, row_bytes, storage_class; ssize_t y; unsigned char *buffer, *packed_scanline, *scanline; unsigned short base_address, transfer_mode; /* Open output 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); if ((image->columns > 65535L) || (image->rows > 65535L)) ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit"); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); (void) TransformImageColorspace(image,sRGBColorspace,exception); /* Initialize image info. */ size_rectangle.top=0; size_rectangle.left=0; size_rectangle.bottom=(short) image->rows; size_rectangle.right=(short) image->columns; frame_rectangle=size_rectangle; crop_rectangle=size_rectangle; source_rectangle=size_rectangle; destination_rectangle=size_rectangle; base_address=0xff; row_bytes=image->columns; bounds.top=0; bounds.left=0; bounds.bottom=(short) image->rows; bounds.right=(short) image->columns; pixmap.version=0; pixmap.pack_type=0; pixmap.pack_size=0; pixmap.pixel_type=0; pixmap.bits_per_pixel=8; pixmap.component_count=1; pixmap.component_size=8; pixmap.plane_bytes=0; pixmap.table=0; pixmap.reserved=0; transfer_mode=0; x_resolution=image->resolution.x != 0.0 ? image->resolution.x : DefaultResolution; y_resolution=image->resolution.y != 0.0 ? image->resolution.y : DefaultResolution; storage_class=image->storage_class; if (image_info->compression == JPEGCompression) storage_class=DirectClass; if (storage_class == DirectClass) { pixmap.component_count=image->alpha_trait != UndefinedPixelTrait ? 4 : 3; pixmap.pixel_type=16; pixmap.bits_per_pixel=32; pixmap.pack_type=0x04; transfer_mode=0x40; row_bytes=4*image->columns; } /* Allocate memory. */ bytes_per_line=image->columns; if (storage_class == DirectClass) bytes_per_line*=image->alpha_trait != UndefinedPixelTrait ? 4 : 3; buffer=(unsigned char *) AcquireQuantumMemory(PictInfoSize,sizeof(*buffer)); packed_scanline=(unsigned char *) AcquireQuantumMemory((size_t) (row_bytes+MaxCount),sizeof(*packed_scanline)); scanline=(unsigned char *) AcquireQuantumMemory(row_bytes,sizeof(*scanline)); if ((buffer == (unsigned char *) NULL) || (packed_scanline == (unsigned char *) NULL) || (scanline == (unsigned char *) NULL)) { if (scanline != (unsigned char *) NULL) scanline=(unsigned char *) RelinquishMagickMemory(scanline); if (packed_scanline != (unsigned char *) NULL) packed_scanline=(unsigned char *) RelinquishMagickMemory( packed_scanline); if (buffer != (unsigned char *) NULL) buffer=(unsigned char *) RelinquishMagickMemory(buffer); ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } (void) memset(scanline,0,row_bytes); (void) memset(packed_scanline,0,(size_t) (row_bytes+MaxCount)); /* Write header, header size, size bounding box, version, and reserved. */ (void) memset(buffer,0,PictInfoSize); (void) WriteBlob(image,PictInfoSize,buffer); (void) WriteBlobMSBShort(image,0); (void) WriteBlobMSBShort(image,(unsigned short) size_rectangle.top); (void) WriteBlobMSBShort(image,(unsigned short) size_rectangle.left); (void) WriteBlobMSBShort(image,(unsigned short) size_rectangle.bottom); (void) WriteBlobMSBShort(image,(unsigned short) size_rectangle.right); (void) WriteBlobMSBShort(image,PictVersion); (void) WriteBlobMSBShort(image,0x02ff); /* version #2 */ (void) WriteBlobMSBShort(image,PictInfoOp); (void) WriteBlobMSBLong(image,0xFFFE0000U); /* Write full size of the file, resolution, frame bounding box, and reserved. */ (void) WriteBlobMSBShort(image,(unsigned short) x_resolution); (void) WriteBlobMSBShort(image,0x0000); (void) WriteBlobMSBShort(image,(unsigned short) y_resolution); (void) WriteBlobMSBShort(image,0x0000); (void) WriteBlobMSBShort(image,(unsigned short) frame_rectangle.top); (void) WriteBlobMSBShort(image,(unsigned short) frame_rectangle.left); (void) WriteBlobMSBShort(image,(unsigned short) frame_rectangle.bottom); (void) WriteBlobMSBShort(image,(unsigned short) frame_rectangle.right); (void) WriteBlobMSBLong(image,0x00000000L); profile=GetImageProfile(image,"iptc"); if (profile != (StringInfo *) NULL) { (void) WriteBlobMSBShort(image,0xa1); (void) WriteBlobMSBShort(image,0x1f2); (void) WriteBlobMSBShort(image,(unsigned short) (GetStringInfoLength(profile)+4)); (void) WriteBlobString(image,"8BIM"); (void) WriteBlob(image,GetStringInfoLength(profile), GetStringInfoDatum(profile)); } profile=GetImageProfile(image,"icc"); if (profile != (StringInfo *) NULL) { (void) WriteBlobMSBShort(image,0xa1); (void) WriteBlobMSBShort(image,0xe0); (void) WriteBlobMSBShort(image,(unsigned short) (GetStringInfoLength(profile)+4)); (void) WriteBlobMSBLong(image,0x00000000U); (void) WriteBlob(image,GetStringInfoLength(profile), GetStringInfoDatum(profile)); (void) WriteBlobMSBShort(image,0xa1); (void) WriteBlobMSBShort(image,0xe0); (void) WriteBlobMSBShort(image,4); (void) WriteBlobMSBLong(image,0x00000002U); } /* Write crop region opcode and crop bounding box. */ (void) WriteBlobMSBShort(image,PictCropRegionOp); (void) WriteBlobMSBShort(image,0xa); (void) WriteBlobMSBShort(image,(unsigned short) crop_rectangle.top); (void) WriteBlobMSBShort(image,(unsigned short) crop_rectangle.left); (void) WriteBlobMSBShort(image,(unsigned short) crop_rectangle.bottom); (void) WriteBlobMSBShort(image,(unsigned short) crop_rectangle.right); if (image_info->compression == JPEGCompression) { Image *jpeg_image; ImageInfo *jpeg_info; size_t length; unsigned char *blob; jpeg_image=CloneImage(image,0,0,MagickTrue,exception); if (jpeg_image == (Image *) NULL) { (void) CloseBlob(image); return(MagickFalse); } jpeg_info=CloneImageInfo(image_info); (void) CopyMagickString(jpeg_info->magick,"JPEG",MagickPathExtent); length=0; blob=(unsigned char *) ImageToBlob(jpeg_info,jpeg_image,&length, exception); jpeg_info=DestroyImageInfo(jpeg_info); if (blob == (unsigned char *) NULL) return(MagickFalse); jpeg_image=DestroyImage(jpeg_image); (void) WriteBlobMSBShort(image,PictJPEGOp); (void) WriteBlobMSBLong(image,(unsigned int) length+154); (void) WriteBlobMSBShort(image,0x0000); (void) WriteBlobMSBLong(image,0x00010000U); (void) WriteBlobMSBLong(image,0x00000000U); (void) WriteBlobMSBLong(image,0x00000000U); (void) WriteBlobMSBLong(image,0x00000000U); (void) WriteBlobMSBLong(image,0x00010000U); (void) WriteBlobMSBLong(image,0x00000000U); (void) WriteBlobMSBLong(image,0x00000000U); (void) WriteBlobMSBLong(image,0x00000000U); (void) WriteBlobMSBLong(image,0x40000000U); (void) WriteBlobMSBLong(image,0x00000000U); (void) WriteBlobMSBLong(image,0x00000000U); (void) WriteBlobMSBLong(image,0x00000000U); (void) WriteBlobMSBLong(image,0x00400000U); (void) WriteBlobMSBShort(image,0x0000); (void) WriteBlobMSBShort(image,(unsigned short) image->rows); (void) WriteBlobMSBShort(image,(unsigned short) image->columns); (void) WriteBlobMSBShort(image,0x0000); (void) WriteBlobMSBShort(image,768); (void) WriteBlobMSBShort(image,0x0000); (void) WriteBlobMSBLong(image,0x00000000U); (void) WriteBlobMSBLong(image,0x00566A70U); (void) WriteBlobMSBLong(image,0x65670000U); (void) WriteBlobMSBLong(image,0x00000000U); (void) WriteBlobMSBLong(image,0x00000001U); (void) WriteBlobMSBLong(image,0x00016170U); (void) WriteBlobMSBLong(image,0x706C0000U); (void) WriteBlobMSBLong(image,0x00000000U); (void) WriteBlobMSBShort(image,768); (void) WriteBlobMSBShort(image,(unsigned short) image->columns); (void) WriteBlobMSBShort(image,(unsigned short) image->rows); (void) WriteBlobMSBShort(image,(unsigned short) x_resolution); (void) WriteBlobMSBShort(image,0x0000); (void) WriteBlobMSBShort(image,(unsigned short) y_resolution); (void) WriteBlobMSBShort(image,0x0000); (void) WriteBlobMSBLong(image,length); (void) WriteBlobMSBShort(image,0x0001); (void) WriteBlobMSBLong(image,0x0B466F74U); (void) WriteBlobMSBLong(image,0x6F202D20U); (void) WriteBlobMSBLong(image,0x4A504547U); (void) WriteBlobMSBLong(image,0x00000000U); (void) WriteBlobMSBLong(image,0x00000000U); (void) WriteBlobMSBLong(image,0x00000000U); (void) WriteBlobMSBLong(image,0x00000000U); (void) WriteBlobMSBLong(image,0x00000000U); (void) WriteBlobMSBLong(image,0x0018FFFFU); (void) WriteBlob(image,length,blob); if ((length & 0x01) != 0) (void) WriteBlobByte(image,'\0'); blob=(unsigned char *) RelinquishMagickMemory(blob); } /* Write picture opcode, row bytes, and picture bounding box, and version. */ if (storage_class == PseudoClass) (void) WriteBlobMSBShort(image,PictPICTOp); else { (void) WriteBlobMSBShort(image,PictPixmapOp); (void) WriteBlobMSBLong(image,(unsigned int) base_address); } (void) WriteBlobMSBShort(image,(unsigned short) (row_bytes | 0x8000)); (void) WriteBlobMSBShort(image,(unsigned short) bounds.top); (void) WriteBlobMSBShort(image,(unsigned short) bounds.left); (void) WriteBlobMSBShort(image,(unsigned short) bounds.bottom); (void) WriteBlobMSBShort(image,(unsigned short) bounds.right); /* Write pack type, pack size, resolution, pixel type, and pixel size. */ (void) WriteBlobMSBShort(image,(unsigned short) pixmap.version); (void) WriteBlobMSBShort(image,(unsigned short) pixmap.pack_type); (void) WriteBlobMSBLong(image,(unsigned int) pixmap.pack_size); (void) WriteBlobMSBShort(image,(unsigned short) (x_resolution+0.5)); (void) WriteBlobMSBShort(image,0x0000); (void) WriteBlobMSBShort(image,(unsigned short) (y_resolution+0.5)); (void) WriteBlobMSBShort(image,0x0000); (void) WriteBlobMSBShort(image,(unsigned short) pixmap.pixel_type); (void) WriteBlobMSBShort(image,(unsigned short) pixmap.bits_per_pixel); /* Write component count, size, plane bytes, table size, and reserved. */ (void) WriteBlobMSBShort(image,(unsigned short) pixmap.component_count); (void) WriteBlobMSBShort(image,(unsigned short) pixmap.component_size); (void) WriteBlobMSBLong(image,(unsigned int) pixmap.plane_bytes); (void) WriteBlobMSBLong(image,(unsigned int) pixmap.table); (void) WriteBlobMSBLong(image,(unsigned int) pixmap.reserved); if (storage_class == PseudoClass) { /* Write image colormap. */ (void) WriteBlobMSBLong(image,0x00000000L); /* color seed */ (void) WriteBlobMSBShort(image,0L); /* color flags */ (void) WriteBlobMSBShort(image,(unsigned short) (image->colors-1)); for (i=0; i < (ssize_t) image->colors; i++) { (void) WriteBlobMSBShort(image,(unsigned short) i); (void) WriteBlobMSBShort(image,ScaleQuantumToShort( image->colormap[i].red)); (void) WriteBlobMSBShort(image,ScaleQuantumToShort( image->colormap[i].green)); (void) WriteBlobMSBShort(image,ScaleQuantumToShort( image->colormap[i].blue)); } } /* Write source and destination rectangle. */ (void) WriteBlobMSBShort(image,(unsigned short) source_rectangle.top); (void) WriteBlobMSBShort(image,(unsigned short) source_rectangle.left); (void) WriteBlobMSBShort(image,(unsigned short) source_rectangle.bottom); (void) WriteBlobMSBShort(image,(unsigned short) source_rectangle.right); (void) WriteBlobMSBShort(image,(unsigned short) destination_rectangle.top); (void) WriteBlobMSBShort(image,(unsigned short) destination_rectangle.left); (void) WriteBlobMSBShort(image,(unsigned short) destination_rectangle.bottom); (void) WriteBlobMSBShort(image,(unsigned short) destination_rectangle.right); (void) WriteBlobMSBShort(image,(unsigned short) transfer_mode); /* Write picture data. */ count=0; if (storage_class == PseudoClass) 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++) { scanline[x]=(unsigned char) GetPixelIndex(image,p); p+=GetPixelChannels(image); } count+=EncodeImage(image,scanline,(size_t) (row_bytes & 0x7FFF), packed_scanline); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } else if (image_info->compression == JPEGCompression) { (void) memset(scanline,0,row_bytes); for (y=0; y < (ssize_t) image->rows; y++) count+=EncodeImage(image,scanline,(size_t) (row_bytes & 0x7FFF), packed_scanline); } else { register unsigned char *blue, *green, *opacity, *red; red=scanline; green=scanline+image->columns; blue=scanline+2*image->columns; opacity=scanline+3*image->columns; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; red=scanline; green=scanline+image->columns; blue=scanline+2*image->columns; if (image->alpha_trait != UndefinedPixelTrait) { opacity=scanline; red=scanline+image->columns; green=scanline+2*image->columns; blue=scanline+3*image->columns; } for (x=0; x < (ssize_t) image->columns; x++) { *red++=ScaleQuantumToChar(GetPixelRed(image,p)); *green++=ScaleQuantumToChar(GetPixelGreen(image,p)); *blue++=ScaleQuantumToChar(GetPixelBlue(image,p)); if (image->alpha_trait != UndefinedPixelTrait) *opacity++=ScaleQuantumToChar((Quantum) (GetPixelAlpha(image,p))); p+=GetPixelChannels(image); } count+=EncodeImage(image,scanline,bytes_per_line,packed_scanline); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } if ((count & 0x01) != 0) (void) WriteBlobByte(image,'\0'); (void) WriteBlobMSBShort(image,PictEndOfPictureOp); offset=TellBlob(image); offset=SeekBlob(image,512,SEEK_SET); (void) WriteBlobMSBShort(image,(unsigned short) offset); scanline=(unsigned char *) RelinquishMagickMemory(scanline); packed_scanline=(unsigned char *) RelinquishMagickMemory(packed_scanline); buffer=(unsigned char *) RelinquishMagickMemory(buffer); (void) CloseBlob(image); return(MagickTrue); }
./CrossVul/dataset_final_sorted/CWE-20/c/bad_364_2
crossvul-cpp_data_bad_2162_2
/* * Kernel-based Virtual Machine driver for Linux * * This module enables machines with Intel VT-x extensions to run virtual * machines without emulation or binary translation. * * MMU support * * Copyright (C) 2006 Qumranet, Inc. * Copyright 2010 Red Hat, Inc. and/or its affiliates. * * Authors: * Yaniv Kamay <yaniv@qumranet.com> * Avi Kivity <avi@qumranet.com> * * This work is licensed under the terms of the GNU GPL, version 2. See * the COPYING file in the top-level directory. * */ #include "irq.h" #include "mmu.h" #include "x86.h" #include "kvm_cache_regs.h" #include <linux/kvm_host.h> #include <linux/types.h> #include <linux/string.h> #include <linux/mm.h> #include <linux/highmem.h> #include <linux/module.h> #include <linux/swap.h> #include <linux/hugetlb.h> #include <linux/compiler.h> #include <linux/srcu.h> #include <linux/slab.h> #include <linux/uaccess.h> #include <asm/page.h> #include <asm/cmpxchg.h> #include <asm/io.h> #include <asm/vmx.h> /* * When setting this variable to true it enables Two-Dimensional-Paging * where the hardware walks 2 page tables: * 1. the guest-virtual to guest-physical * 2. while doing 1. it walks guest-physical to host-physical * If the hardware supports that we don't need to do shadow paging. */ bool tdp_enabled = false; enum { AUDIT_PRE_PAGE_FAULT, AUDIT_POST_PAGE_FAULT, AUDIT_PRE_PTE_WRITE, AUDIT_POST_PTE_WRITE, AUDIT_PRE_SYNC, AUDIT_POST_SYNC }; #undef MMU_DEBUG #ifdef MMU_DEBUG #define pgprintk(x...) do { if (dbg) printk(x); } while (0) #define rmap_printk(x...) do { if (dbg) printk(x); } while (0) #else #define pgprintk(x...) do { } while (0) #define rmap_printk(x...) do { } while (0) #endif #ifdef MMU_DEBUG static bool dbg = 0; module_param(dbg, bool, 0644); #endif #ifndef MMU_DEBUG #define ASSERT(x) do { } while (0) #else #define ASSERT(x) \ if (!(x)) { \ printk(KERN_WARNING "assertion failed %s:%d: %s\n", \ __FILE__, __LINE__, #x); \ } #endif #define PTE_PREFETCH_NUM 8 #define PT_FIRST_AVAIL_BITS_SHIFT 10 #define PT64_SECOND_AVAIL_BITS_SHIFT 52 #define PT64_LEVEL_BITS 9 #define PT64_LEVEL_SHIFT(level) \ (PAGE_SHIFT + (level - 1) * PT64_LEVEL_BITS) #define PT64_INDEX(address, level)\ (((address) >> PT64_LEVEL_SHIFT(level)) & ((1 << PT64_LEVEL_BITS) - 1)) #define PT32_LEVEL_BITS 10 #define PT32_LEVEL_SHIFT(level) \ (PAGE_SHIFT + (level - 1) * PT32_LEVEL_BITS) #define PT32_LVL_OFFSET_MASK(level) \ (PT32_BASE_ADDR_MASK & ((1ULL << (PAGE_SHIFT + (((level) - 1) \ * PT32_LEVEL_BITS))) - 1)) #define PT32_INDEX(address, level)\ (((address) >> PT32_LEVEL_SHIFT(level)) & ((1 << PT32_LEVEL_BITS) - 1)) #define PT64_BASE_ADDR_MASK (((1ULL << 52) - 1) & ~(u64)(PAGE_SIZE-1)) #define PT64_DIR_BASE_ADDR_MASK \ (PT64_BASE_ADDR_MASK & ~((1ULL << (PAGE_SHIFT + PT64_LEVEL_BITS)) - 1)) #define PT64_LVL_ADDR_MASK(level) \ (PT64_BASE_ADDR_MASK & ~((1ULL << (PAGE_SHIFT + (((level) - 1) \ * PT64_LEVEL_BITS))) - 1)) #define PT64_LVL_OFFSET_MASK(level) \ (PT64_BASE_ADDR_MASK & ((1ULL << (PAGE_SHIFT + (((level) - 1) \ * PT64_LEVEL_BITS))) - 1)) #define PT32_BASE_ADDR_MASK PAGE_MASK #define PT32_DIR_BASE_ADDR_MASK \ (PAGE_MASK & ~((1ULL << (PAGE_SHIFT + PT32_LEVEL_BITS)) - 1)) #define PT32_LVL_ADDR_MASK(level) \ (PAGE_MASK & ~((1ULL << (PAGE_SHIFT + (((level) - 1) \ * PT32_LEVEL_BITS))) - 1)) #define PT64_PERM_MASK (PT_PRESENT_MASK | PT_WRITABLE_MASK | shadow_user_mask \ | shadow_x_mask | shadow_nx_mask) #define ACC_EXEC_MASK 1 #define ACC_WRITE_MASK PT_WRITABLE_MASK #define ACC_USER_MASK PT_USER_MASK #define ACC_ALL (ACC_EXEC_MASK | ACC_WRITE_MASK | ACC_USER_MASK) #include <trace/events/kvm.h> #define CREATE_TRACE_POINTS #include "mmutrace.h" #define SPTE_HOST_WRITEABLE (1ULL << PT_FIRST_AVAIL_BITS_SHIFT) #define SPTE_MMU_WRITEABLE (1ULL << (PT_FIRST_AVAIL_BITS_SHIFT + 1)) #define SHADOW_PT_INDEX(addr, level) PT64_INDEX(addr, level) /* make pte_list_desc fit well in cache line */ #define PTE_LIST_EXT 3 struct pte_list_desc { u64 *sptes[PTE_LIST_EXT]; struct pte_list_desc *more; }; struct kvm_shadow_walk_iterator { u64 addr; hpa_t shadow_addr; u64 *sptep; int level; unsigned index; }; #define for_each_shadow_entry(_vcpu, _addr, _walker) \ for (shadow_walk_init(&(_walker), _vcpu, _addr); \ shadow_walk_okay(&(_walker)); \ shadow_walk_next(&(_walker))) #define for_each_shadow_entry_lockless(_vcpu, _addr, _walker, spte) \ for (shadow_walk_init(&(_walker), _vcpu, _addr); \ shadow_walk_okay(&(_walker)) && \ ({ spte = mmu_spte_get_lockless(_walker.sptep); 1; }); \ __shadow_walk_next(&(_walker), spte)) static struct kmem_cache *pte_list_desc_cache; static struct kmem_cache *mmu_page_header_cache; static struct percpu_counter kvm_total_used_mmu_pages; static u64 __read_mostly shadow_nx_mask; static u64 __read_mostly shadow_x_mask; /* mutual exclusive with nx_mask */ static u64 __read_mostly shadow_user_mask; static u64 __read_mostly shadow_accessed_mask; static u64 __read_mostly shadow_dirty_mask; static u64 __read_mostly shadow_mmio_mask; static void mmu_spte_set(u64 *sptep, u64 spte); static void mmu_free_roots(struct kvm_vcpu *vcpu); void kvm_mmu_set_mmio_spte_mask(u64 mmio_mask) { shadow_mmio_mask = mmio_mask; } EXPORT_SYMBOL_GPL(kvm_mmu_set_mmio_spte_mask); /* * spte bits of bit 3 ~ bit 11 are used as low 9 bits of generation number, * the bits of bits 52 ~ bit 61 are used as high 10 bits of generation * number. */ #define MMIO_SPTE_GEN_LOW_SHIFT 3 #define MMIO_SPTE_GEN_HIGH_SHIFT 52 #define MMIO_GEN_SHIFT 19 #define MMIO_GEN_LOW_SHIFT 9 #define MMIO_GEN_LOW_MASK ((1 << MMIO_GEN_LOW_SHIFT) - 1) #define MMIO_GEN_MASK ((1 << MMIO_GEN_SHIFT) - 1) #define MMIO_MAX_GEN ((1 << MMIO_GEN_SHIFT) - 1) static u64 generation_mmio_spte_mask(unsigned int gen) { u64 mask; WARN_ON(gen > MMIO_MAX_GEN); mask = (gen & MMIO_GEN_LOW_MASK) << MMIO_SPTE_GEN_LOW_SHIFT; mask |= ((u64)gen >> MMIO_GEN_LOW_SHIFT) << MMIO_SPTE_GEN_HIGH_SHIFT; return mask; } static unsigned int get_mmio_spte_generation(u64 spte) { unsigned int gen; spte &= ~shadow_mmio_mask; gen = (spte >> MMIO_SPTE_GEN_LOW_SHIFT) & MMIO_GEN_LOW_MASK; gen |= (spte >> MMIO_SPTE_GEN_HIGH_SHIFT) << MMIO_GEN_LOW_SHIFT; return gen; } static unsigned int kvm_current_mmio_generation(struct kvm *kvm) { /* * Init kvm generation close to MMIO_MAX_GEN to easily test the * code of handling generation number wrap-around. */ return (kvm_memslots(kvm)->generation + MMIO_MAX_GEN - 150) & MMIO_GEN_MASK; } static void mark_mmio_spte(struct kvm *kvm, u64 *sptep, u64 gfn, unsigned access) { unsigned int gen = kvm_current_mmio_generation(kvm); u64 mask = generation_mmio_spte_mask(gen); access &= ACC_WRITE_MASK | ACC_USER_MASK; mask |= shadow_mmio_mask | access | gfn << PAGE_SHIFT; trace_mark_mmio_spte(sptep, gfn, access, gen); mmu_spte_set(sptep, mask); } static bool is_mmio_spte(u64 spte) { return (spte & shadow_mmio_mask) == shadow_mmio_mask; } static gfn_t get_mmio_spte_gfn(u64 spte) { u64 mask = generation_mmio_spte_mask(MMIO_MAX_GEN) | shadow_mmio_mask; return (spte & ~mask) >> PAGE_SHIFT; } static unsigned get_mmio_spte_access(u64 spte) { u64 mask = generation_mmio_spte_mask(MMIO_MAX_GEN) | shadow_mmio_mask; return (spte & ~mask) & ~PAGE_MASK; } static bool set_mmio_spte(struct kvm *kvm, u64 *sptep, gfn_t gfn, pfn_t pfn, unsigned access) { if (unlikely(is_noslot_pfn(pfn))) { mark_mmio_spte(kvm, sptep, gfn, access); return true; } return false; } static bool check_mmio_spte(struct kvm *kvm, u64 spte) { unsigned int kvm_gen, spte_gen; kvm_gen = kvm_current_mmio_generation(kvm); spte_gen = get_mmio_spte_generation(spte); trace_check_mmio_spte(spte, kvm_gen, spte_gen); return likely(kvm_gen == spte_gen); } static inline u64 rsvd_bits(int s, int e) { return ((1ULL << (e - s + 1)) - 1) << s; } void kvm_mmu_set_mask_ptes(u64 user_mask, u64 accessed_mask, u64 dirty_mask, u64 nx_mask, u64 x_mask) { shadow_user_mask = user_mask; shadow_accessed_mask = accessed_mask; shadow_dirty_mask = dirty_mask; shadow_nx_mask = nx_mask; shadow_x_mask = x_mask; } EXPORT_SYMBOL_GPL(kvm_mmu_set_mask_ptes); static int is_cpuid_PSE36(void) { return 1; } static int is_nx(struct kvm_vcpu *vcpu) { return vcpu->arch.efer & EFER_NX; } static int is_shadow_present_pte(u64 pte) { return pte & PT_PRESENT_MASK && !is_mmio_spte(pte); } static int is_large_pte(u64 pte) { return pte & PT_PAGE_SIZE_MASK; } static int is_rmap_spte(u64 pte) { return is_shadow_present_pte(pte); } static int is_last_spte(u64 pte, int level) { if (level == PT_PAGE_TABLE_LEVEL) return 1; if (is_large_pte(pte)) return 1; return 0; } static pfn_t spte_to_pfn(u64 pte) { return (pte & PT64_BASE_ADDR_MASK) >> PAGE_SHIFT; } static gfn_t pse36_gfn_delta(u32 gpte) { int shift = 32 - PT32_DIR_PSE36_SHIFT - PAGE_SHIFT; return (gpte & PT32_DIR_PSE36_MASK) << shift; } #ifdef CONFIG_X86_64 static void __set_spte(u64 *sptep, u64 spte) { *sptep = spte; } static void __update_clear_spte_fast(u64 *sptep, u64 spte) { *sptep = spte; } static u64 __update_clear_spte_slow(u64 *sptep, u64 spte) { return xchg(sptep, spte); } static u64 __get_spte_lockless(u64 *sptep) { return ACCESS_ONCE(*sptep); } static bool __check_direct_spte_mmio_pf(u64 spte) { /* It is valid if the spte is zapped. */ return spte == 0ull; } #else union split_spte { struct { u32 spte_low; u32 spte_high; }; u64 spte; }; static void count_spte_clear(u64 *sptep, u64 spte) { struct kvm_mmu_page *sp = page_header(__pa(sptep)); if (is_shadow_present_pte(spte)) return; /* Ensure the spte is completely set before we increase the count */ smp_wmb(); sp->clear_spte_count++; } static void __set_spte(u64 *sptep, u64 spte) { union split_spte *ssptep, sspte; ssptep = (union split_spte *)sptep; sspte = (union split_spte)spte; ssptep->spte_high = sspte.spte_high; /* * If we map the spte from nonpresent to present, We should store * the high bits firstly, then set present bit, so cpu can not * fetch this spte while we are setting the spte. */ smp_wmb(); ssptep->spte_low = sspte.spte_low; } static void __update_clear_spte_fast(u64 *sptep, u64 spte) { union split_spte *ssptep, sspte; ssptep = (union split_spte *)sptep; sspte = (union split_spte)spte; ssptep->spte_low = sspte.spte_low; /* * If we map the spte from present to nonpresent, we should clear * present bit firstly to avoid vcpu fetch the old high bits. */ smp_wmb(); ssptep->spte_high = sspte.spte_high; count_spte_clear(sptep, spte); } static u64 __update_clear_spte_slow(u64 *sptep, u64 spte) { union split_spte *ssptep, sspte, orig; ssptep = (union split_spte *)sptep; sspte = (union split_spte)spte; /* xchg acts as a barrier before the setting of the high bits */ orig.spte_low = xchg(&ssptep->spte_low, sspte.spte_low); orig.spte_high = ssptep->spte_high; ssptep->spte_high = sspte.spte_high; count_spte_clear(sptep, spte); return orig.spte; } /* * The idea using the light way get the spte on x86_32 guest is from * gup_get_pte(arch/x86/mm/gup.c). * * An spte tlb flush may be pending, because kvm_set_pte_rmapp * coalesces them and we are running out of the MMU lock. Therefore * we need to protect against in-progress updates of the spte. * * Reading the spte while an update is in progress may get the old value * for the high part of the spte. The race is fine for a present->non-present * change (because the high part of the spte is ignored for non-present spte), * but for a present->present change we must reread the spte. * * All such changes are done in two steps (present->non-present and * non-present->present), hence it is enough to count the number of * present->non-present updates: if it changed while reading the spte, * we might have hit the race. This is done using clear_spte_count. */ static u64 __get_spte_lockless(u64 *sptep) { struct kvm_mmu_page *sp = page_header(__pa(sptep)); union split_spte spte, *orig = (union split_spte *)sptep; int count; retry: count = sp->clear_spte_count; smp_rmb(); spte.spte_low = orig->spte_low; smp_rmb(); spte.spte_high = orig->spte_high; smp_rmb(); if (unlikely(spte.spte_low != orig->spte_low || count != sp->clear_spte_count)) goto retry; return spte.spte; } static bool __check_direct_spte_mmio_pf(u64 spte) { union split_spte sspte = (union split_spte)spte; u32 high_mmio_mask = shadow_mmio_mask >> 32; /* It is valid if the spte is zapped. */ if (spte == 0ull) return true; /* It is valid if the spte is being zapped. */ if (sspte.spte_low == 0ull && (sspte.spte_high & high_mmio_mask) == high_mmio_mask) return true; return false; } #endif static bool spte_is_locklessly_modifiable(u64 spte) { return (spte & (SPTE_HOST_WRITEABLE | SPTE_MMU_WRITEABLE)) == (SPTE_HOST_WRITEABLE | SPTE_MMU_WRITEABLE); } static bool spte_has_volatile_bits(u64 spte) { /* * Always atomicly update spte if it can be updated * out of mmu-lock, it can ensure dirty bit is not lost, * also, it can help us to get a stable is_writable_pte() * to ensure tlb flush is not missed. */ if (spte_is_locklessly_modifiable(spte)) return true; if (!shadow_accessed_mask) return false; if (!is_shadow_present_pte(spte)) return false; if ((spte & shadow_accessed_mask) && (!is_writable_pte(spte) || (spte & shadow_dirty_mask))) return false; return true; } static bool spte_is_bit_cleared(u64 old_spte, u64 new_spte, u64 bit_mask) { return (old_spte & bit_mask) && !(new_spte & bit_mask); } /* Rules for using mmu_spte_set: * Set the sptep from nonpresent to present. * Note: the sptep being assigned *must* be either not present * or in a state where the hardware will not attempt to update * the spte. */ static void mmu_spte_set(u64 *sptep, u64 new_spte) { WARN_ON(is_shadow_present_pte(*sptep)); __set_spte(sptep, new_spte); } /* Rules for using mmu_spte_update: * Update the state bits, it means the mapped pfn is not changged. * * Whenever we overwrite a writable spte with a read-only one we * should flush remote TLBs. Otherwise rmap_write_protect * will find a read-only spte, even though the writable spte * might be cached on a CPU's TLB, the return value indicates this * case. */ static bool mmu_spte_update(u64 *sptep, u64 new_spte) { u64 old_spte = *sptep; bool ret = false; WARN_ON(!is_rmap_spte(new_spte)); if (!is_shadow_present_pte(old_spte)) { mmu_spte_set(sptep, new_spte); return ret; } if (!spte_has_volatile_bits(old_spte)) __update_clear_spte_fast(sptep, new_spte); else old_spte = __update_clear_spte_slow(sptep, new_spte); /* * For the spte updated out of mmu-lock is safe, since * we always atomicly update it, see the comments in * spte_has_volatile_bits(). */ if (is_writable_pte(old_spte) && !is_writable_pte(new_spte)) ret = true; if (!shadow_accessed_mask) return ret; if (spte_is_bit_cleared(old_spte, new_spte, shadow_accessed_mask)) kvm_set_pfn_accessed(spte_to_pfn(old_spte)); if (spte_is_bit_cleared(old_spte, new_spte, shadow_dirty_mask)) kvm_set_pfn_dirty(spte_to_pfn(old_spte)); return ret; } /* * Rules for using mmu_spte_clear_track_bits: * It sets the sptep from present to nonpresent, and track the * state bits, it is used to clear the last level sptep. */ static int mmu_spte_clear_track_bits(u64 *sptep) { pfn_t pfn; u64 old_spte = *sptep; if (!spte_has_volatile_bits(old_spte)) __update_clear_spte_fast(sptep, 0ull); else old_spte = __update_clear_spte_slow(sptep, 0ull); if (!is_rmap_spte(old_spte)) return 0; pfn = spte_to_pfn(old_spte); /* * KVM does not hold the refcount of the page used by * kvm mmu, before reclaiming the page, we should * unmap it from mmu first. */ WARN_ON(!kvm_is_mmio_pfn(pfn) && !page_count(pfn_to_page(pfn))); if (!shadow_accessed_mask || old_spte & shadow_accessed_mask) kvm_set_pfn_accessed(pfn); if (!shadow_dirty_mask || (old_spte & shadow_dirty_mask)) kvm_set_pfn_dirty(pfn); return 1; } /* * Rules for using mmu_spte_clear_no_track: * Directly clear spte without caring the state bits of sptep, * it is used to set the upper level spte. */ static void mmu_spte_clear_no_track(u64 *sptep) { __update_clear_spte_fast(sptep, 0ull); } static u64 mmu_spte_get_lockless(u64 *sptep) { return __get_spte_lockless(sptep); } static void walk_shadow_page_lockless_begin(struct kvm_vcpu *vcpu) { /* * Prevent page table teardown by making any free-er wait during * kvm_flush_remote_tlbs() IPI to all active vcpus. */ local_irq_disable(); vcpu->mode = READING_SHADOW_PAGE_TABLES; /* * Make sure a following spte read is not reordered ahead of the write * to vcpu->mode. */ smp_mb(); } static void walk_shadow_page_lockless_end(struct kvm_vcpu *vcpu) { /* * Make sure the write to vcpu->mode is not reordered in front of * reads to sptes. If it does, kvm_commit_zap_page() can see us * OUTSIDE_GUEST_MODE and proceed to free the shadow page table. */ smp_mb(); vcpu->mode = OUTSIDE_GUEST_MODE; local_irq_enable(); } static int mmu_topup_memory_cache(struct kvm_mmu_memory_cache *cache, struct kmem_cache *base_cache, int min) { void *obj; if (cache->nobjs >= min) return 0; while (cache->nobjs < ARRAY_SIZE(cache->objects)) { obj = kmem_cache_zalloc(base_cache, GFP_KERNEL); if (!obj) return -ENOMEM; cache->objects[cache->nobjs++] = obj; } return 0; } static int mmu_memory_cache_free_objects(struct kvm_mmu_memory_cache *cache) { return cache->nobjs; } static void mmu_free_memory_cache(struct kvm_mmu_memory_cache *mc, struct kmem_cache *cache) { while (mc->nobjs) kmem_cache_free(cache, mc->objects[--mc->nobjs]); } static int mmu_topup_memory_cache_page(struct kvm_mmu_memory_cache *cache, int min) { void *page; if (cache->nobjs >= min) return 0; while (cache->nobjs < ARRAY_SIZE(cache->objects)) { page = (void *)__get_free_page(GFP_KERNEL); if (!page) return -ENOMEM; cache->objects[cache->nobjs++] = page; } return 0; } static void mmu_free_memory_cache_page(struct kvm_mmu_memory_cache *mc) { while (mc->nobjs) free_page((unsigned long)mc->objects[--mc->nobjs]); } static int mmu_topup_memory_caches(struct kvm_vcpu *vcpu) { int r; r = mmu_topup_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache, pte_list_desc_cache, 8 + PTE_PREFETCH_NUM); if (r) goto out; r = mmu_topup_memory_cache_page(&vcpu->arch.mmu_page_cache, 8); if (r) goto out; r = mmu_topup_memory_cache(&vcpu->arch.mmu_page_header_cache, mmu_page_header_cache, 4); out: return r; } static void mmu_free_memory_caches(struct kvm_vcpu *vcpu) { mmu_free_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache, pte_list_desc_cache); mmu_free_memory_cache_page(&vcpu->arch.mmu_page_cache); mmu_free_memory_cache(&vcpu->arch.mmu_page_header_cache, mmu_page_header_cache); } static void *mmu_memory_cache_alloc(struct kvm_mmu_memory_cache *mc) { void *p; BUG_ON(!mc->nobjs); p = mc->objects[--mc->nobjs]; return p; } static struct pte_list_desc *mmu_alloc_pte_list_desc(struct kvm_vcpu *vcpu) { return mmu_memory_cache_alloc(&vcpu->arch.mmu_pte_list_desc_cache); } static void mmu_free_pte_list_desc(struct pte_list_desc *pte_list_desc) { kmem_cache_free(pte_list_desc_cache, pte_list_desc); } static gfn_t kvm_mmu_page_get_gfn(struct kvm_mmu_page *sp, int index) { if (!sp->role.direct) return sp->gfns[index]; return sp->gfn + (index << ((sp->role.level - 1) * PT64_LEVEL_BITS)); } static void kvm_mmu_page_set_gfn(struct kvm_mmu_page *sp, int index, gfn_t gfn) { if (sp->role.direct) BUG_ON(gfn != kvm_mmu_page_get_gfn(sp, index)); else sp->gfns[index] = gfn; } /* * Return the pointer to the large page information for a given gfn, * handling slots that are not large page aligned. */ static struct kvm_lpage_info *lpage_info_slot(gfn_t gfn, struct kvm_memory_slot *slot, int level) { unsigned long idx; idx = gfn_to_index(gfn, slot->base_gfn, level); return &slot->arch.lpage_info[level - 2][idx]; } static void account_shadowed(struct kvm *kvm, gfn_t gfn) { struct kvm_memory_slot *slot; struct kvm_lpage_info *linfo; int i; slot = gfn_to_memslot(kvm, gfn); for (i = PT_DIRECTORY_LEVEL; i < PT_PAGE_TABLE_LEVEL + KVM_NR_PAGE_SIZES; ++i) { linfo = lpage_info_slot(gfn, slot, i); linfo->write_count += 1; } kvm->arch.indirect_shadow_pages++; } static void unaccount_shadowed(struct kvm *kvm, gfn_t gfn) { struct kvm_memory_slot *slot; struct kvm_lpage_info *linfo; int i; slot = gfn_to_memslot(kvm, gfn); for (i = PT_DIRECTORY_LEVEL; i < PT_PAGE_TABLE_LEVEL + KVM_NR_PAGE_SIZES; ++i) { linfo = lpage_info_slot(gfn, slot, i); linfo->write_count -= 1; WARN_ON(linfo->write_count < 0); } kvm->arch.indirect_shadow_pages--; } static int has_wrprotected_page(struct kvm *kvm, gfn_t gfn, int level) { struct kvm_memory_slot *slot; struct kvm_lpage_info *linfo; slot = gfn_to_memslot(kvm, gfn); if (slot) { linfo = lpage_info_slot(gfn, slot, level); return linfo->write_count; } return 1; } static int host_mapping_level(struct kvm *kvm, gfn_t gfn) { unsigned long page_size; int i, ret = 0; page_size = kvm_host_page_size(kvm, gfn); for (i = PT_PAGE_TABLE_LEVEL; i < (PT_PAGE_TABLE_LEVEL + KVM_NR_PAGE_SIZES); ++i) { if (page_size >= KVM_HPAGE_SIZE(i)) ret = i; else break; } return ret; } static struct kvm_memory_slot * gfn_to_memslot_dirty_bitmap(struct kvm_vcpu *vcpu, gfn_t gfn, bool no_dirty_log) { struct kvm_memory_slot *slot; slot = gfn_to_memslot(vcpu->kvm, gfn); if (!slot || slot->flags & KVM_MEMSLOT_INVALID || (no_dirty_log && slot->dirty_bitmap)) slot = NULL; return slot; } static bool mapping_level_dirty_bitmap(struct kvm_vcpu *vcpu, gfn_t large_gfn) { return !gfn_to_memslot_dirty_bitmap(vcpu, large_gfn, true); } static int mapping_level(struct kvm_vcpu *vcpu, gfn_t large_gfn) { int host_level, level, max_level; host_level = host_mapping_level(vcpu->kvm, large_gfn); if (host_level == PT_PAGE_TABLE_LEVEL) return host_level; max_level = min(kvm_x86_ops->get_lpage_level(), host_level); for (level = PT_DIRECTORY_LEVEL; level <= max_level; ++level) if (has_wrprotected_page(vcpu->kvm, large_gfn, level)) break; return level - 1; } /* * Pte mapping structures: * * If pte_list bit zero is zero, then pte_list point to the spte. * * If pte_list bit zero is one, (then pte_list & ~1) points to a struct * pte_list_desc containing more mappings. * * Returns the number of pte entries before the spte was added or zero if * the spte was not added. * */ static int pte_list_add(struct kvm_vcpu *vcpu, u64 *spte, unsigned long *pte_list) { struct pte_list_desc *desc; int i, count = 0; if (!*pte_list) { rmap_printk("pte_list_add: %p %llx 0->1\n", spte, *spte); *pte_list = (unsigned long)spte; } else if (!(*pte_list & 1)) { rmap_printk("pte_list_add: %p %llx 1->many\n", spte, *spte); desc = mmu_alloc_pte_list_desc(vcpu); desc->sptes[0] = (u64 *)*pte_list; desc->sptes[1] = spte; *pte_list = (unsigned long)desc | 1; ++count; } else { rmap_printk("pte_list_add: %p %llx many->many\n", spte, *spte); desc = (struct pte_list_desc *)(*pte_list & ~1ul); while (desc->sptes[PTE_LIST_EXT-1] && desc->more) { desc = desc->more; count += PTE_LIST_EXT; } if (desc->sptes[PTE_LIST_EXT-1]) { desc->more = mmu_alloc_pte_list_desc(vcpu); desc = desc->more; } for (i = 0; desc->sptes[i]; ++i) ++count; desc->sptes[i] = spte; } return count; } static void pte_list_desc_remove_entry(unsigned long *pte_list, struct pte_list_desc *desc, int i, struct pte_list_desc *prev_desc) { int j; for (j = PTE_LIST_EXT - 1; !desc->sptes[j] && j > i; --j) ; desc->sptes[i] = desc->sptes[j]; desc->sptes[j] = NULL; if (j != 0) return; if (!prev_desc && !desc->more) *pte_list = (unsigned long)desc->sptes[0]; else if (prev_desc) prev_desc->more = desc->more; else *pte_list = (unsigned long)desc->more | 1; mmu_free_pte_list_desc(desc); } static void pte_list_remove(u64 *spte, unsigned long *pte_list) { struct pte_list_desc *desc; struct pte_list_desc *prev_desc; int i; if (!*pte_list) { printk(KERN_ERR "pte_list_remove: %p 0->BUG\n", spte); BUG(); } else if (!(*pte_list & 1)) { rmap_printk("pte_list_remove: %p 1->0\n", spte); if ((u64 *)*pte_list != spte) { printk(KERN_ERR "pte_list_remove: %p 1->BUG\n", spte); BUG(); } *pte_list = 0; } else { rmap_printk("pte_list_remove: %p many->many\n", spte); desc = (struct pte_list_desc *)(*pte_list & ~1ul); prev_desc = NULL; while (desc) { for (i = 0; i < PTE_LIST_EXT && desc->sptes[i]; ++i) if (desc->sptes[i] == spte) { pte_list_desc_remove_entry(pte_list, desc, i, prev_desc); return; } prev_desc = desc; desc = desc->more; } pr_err("pte_list_remove: %p many->many\n", spte); BUG(); } } typedef void (*pte_list_walk_fn) (u64 *spte); static void pte_list_walk(unsigned long *pte_list, pte_list_walk_fn fn) { struct pte_list_desc *desc; int i; if (!*pte_list) return; if (!(*pte_list & 1)) return fn((u64 *)*pte_list); desc = (struct pte_list_desc *)(*pte_list & ~1ul); while (desc) { for (i = 0; i < PTE_LIST_EXT && desc->sptes[i]; ++i) fn(desc->sptes[i]); desc = desc->more; } } static unsigned long *__gfn_to_rmap(gfn_t gfn, int level, struct kvm_memory_slot *slot) { unsigned long idx; idx = gfn_to_index(gfn, slot->base_gfn, level); return &slot->arch.rmap[level - PT_PAGE_TABLE_LEVEL][idx]; } /* * Take gfn and return the reverse mapping to it. */ static unsigned long *gfn_to_rmap(struct kvm *kvm, gfn_t gfn, int level) { struct kvm_memory_slot *slot; slot = gfn_to_memslot(kvm, gfn); return __gfn_to_rmap(gfn, level, slot); } static bool rmap_can_add(struct kvm_vcpu *vcpu) { struct kvm_mmu_memory_cache *cache; cache = &vcpu->arch.mmu_pte_list_desc_cache; return mmu_memory_cache_free_objects(cache); } static int rmap_add(struct kvm_vcpu *vcpu, u64 *spte, gfn_t gfn) { struct kvm_mmu_page *sp; unsigned long *rmapp; sp = page_header(__pa(spte)); kvm_mmu_page_set_gfn(sp, spte - sp->spt, gfn); rmapp = gfn_to_rmap(vcpu->kvm, gfn, sp->role.level); return pte_list_add(vcpu, spte, rmapp); } static void rmap_remove(struct kvm *kvm, u64 *spte) { struct kvm_mmu_page *sp; gfn_t gfn; unsigned long *rmapp; sp = page_header(__pa(spte)); gfn = kvm_mmu_page_get_gfn(sp, spte - sp->spt); rmapp = gfn_to_rmap(kvm, gfn, sp->role.level); pte_list_remove(spte, rmapp); } /* * Used by the following functions to iterate through the sptes linked by a * rmap. All fields are private and not assumed to be used outside. */ struct rmap_iterator { /* private fields */ struct pte_list_desc *desc; /* holds the sptep if not NULL */ int pos; /* index of the sptep */ }; /* * Iteration must be started by this function. This should also be used after * removing/dropping sptes from the rmap link because in such cases the * information in the itererator may not be valid. * * Returns sptep if found, NULL otherwise. */ static u64 *rmap_get_first(unsigned long rmap, struct rmap_iterator *iter) { if (!rmap) return NULL; if (!(rmap & 1)) { iter->desc = NULL; return (u64 *)rmap; } iter->desc = (struct pte_list_desc *)(rmap & ~1ul); iter->pos = 0; return iter->desc->sptes[iter->pos]; } /* * Must be used with a valid iterator: e.g. after rmap_get_first(). * * Returns sptep if found, NULL otherwise. */ static u64 *rmap_get_next(struct rmap_iterator *iter) { if (iter->desc) { if (iter->pos < PTE_LIST_EXT - 1) { u64 *sptep; ++iter->pos; sptep = iter->desc->sptes[iter->pos]; if (sptep) return sptep; } iter->desc = iter->desc->more; if (iter->desc) { iter->pos = 0; /* desc->sptes[0] cannot be NULL */ return iter->desc->sptes[iter->pos]; } } return NULL; } static void drop_spte(struct kvm *kvm, u64 *sptep) { if (mmu_spte_clear_track_bits(sptep)) rmap_remove(kvm, sptep); } static bool __drop_large_spte(struct kvm *kvm, u64 *sptep) { if (is_large_pte(*sptep)) { WARN_ON(page_header(__pa(sptep))->role.level == PT_PAGE_TABLE_LEVEL); drop_spte(kvm, sptep); --kvm->stat.lpages; return true; } return false; } static void drop_large_spte(struct kvm_vcpu *vcpu, u64 *sptep) { if (__drop_large_spte(vcpu->kvm, sptep)) kvm_flush_remote_tlbs(vcpu->kvm); } /* * Write-protect on the specified @sptep, @pt_protect indicates whether * spte writ-protection is caused by protecting shadow page table. * @flush indicates whether tlb need be flushed. * * Note: write protection is difference between drity logging and spte * protection: * - for dirty logging, the spte can be set to writable at anytime if * its dirty bitmap is properly set. * - for spte protection, the spte can be writable only after unsync-ing * shadow page. * * Return true if the spte is dropped. */ static bool spte_write_protect(struct kvm *kvm, u64 *sptep, bool *flush, bool pt_protect) { u64 spte = *sptep; if (!is_writable_pte(spte) && !(pt_protect && spte_is_locklessly_modifiable(spte))) return false; rmap_printk("rmap_write_protect: spte %p %llx\n", sptep, *sptep); if (__drop_large_spte(kvm, sptep)) { *flush |= true; return true; } if (pt_protect) spte &= ~SPTE_MMU_WRITEABLE; spte = spte & ~PT_WRITABLE_MASK; *flush |= mmu_spte_update(sptep, spte); return false; } static bool __rmap_write_protect(struct kvm *kvm, unsigned long *rmapp, bool pt_protect) { u64 *sptep; struct rmap_iterator iter; bool flush = false; for (sptep = rmap_get_first(*rmapp, &iter); sptep;) { BUG_ON(!(*sptep & PT_PRESENT_MASK)); if (spte_write_protect(kvm, sptep, &flush, pt_protect)) { sptep = rmap_get_first(*rmapp, &iter); continue; } sptep = rmap_get_next(&iter); } return flush; } /** * kvm_mmu_write_protect_pt_masked - write protect selected PT level pages * @kvm: kvm instance * @slot: slot to protect * @gfn_offset: start of the BITS_PER_LONG pages we care about * @mask: indicates which pages we should protect * * Used when we do not need to care about huge page mappings: e.g. during dirty * logging we do not have any such mappings. */ void kvm_mmu_write_protect_pt_masked(struct kvm *kvm, struct kvm_memory_slot *slot, gfn_t gfn_offset, unsigned long mask) { unsigned long *rmapp; while (mask) { rmapp = __gfn_to_rmap(slot->base_gfn + gfn_offset + __ffs(mask), PT_PAGE_TABLE_LEVEL, slot); __rmap_write_protect(kvm, rmapp, false); /* clear the first set bit */ mask &= mask - 1; } } static bool rmap_write_protect(struct kvm *kvm, u64 gfn) { struct kvm_memory_slot *slot; unsigned long *rmapp; int i; bool write_protected = false; slot = gfn_to_memslot(kvm, gfn); for (i = PT_PAGE_TABLE_LEVEL; i < PT_PAGE_TABLE_LEVEL + KVM_NR_PAGE_SIZES; ++i) { rmapp = __gfn_to_rmap(gfn, i, slot); write_protected |= __rmap_write_protect(kvm, rmapp, true); } return write_protected; } static int kvm_unmap_rmapp(struct kvm *kvm, unsigned long *rmapp, struct kvm_memory_slot *slot, unsigned long data) { u64 *sptep; struct rmap_iterator iter; int need_tlb_flush = 0; while ((sptep = rmap_get_first(*rmapp, &iter))) { BUG_ON(!(*sptep & PT_PRESENT_MASK)); rmap_printk("kvm_rmap_unmap_hva: spte %p %llx\n", sptep, *sptep); drop_spte(kvm, sptep); need_tlb_flush = 1; } return need_tlb_flush; } static int kvm_set_pte_rmapp(struct kvm *kvm, unsigned long *rmapp, struct kvm_memory_slot *slot, unsigned long data) { u64 *sptep; struct rmap_iterator iter; int need_flush = 0; u64 new_spte; pte_t *ptep = (pte_t *)data; pfn_t new_pfn; WARN_ON(pte_huge(*ptep)); new_pfn = pte_pfn(*ptep); for (sptep = rmap_get_first(*rmapp, &iter); sptep;) { BUG_ON(!is_shadow_present_pte(*sptep)); rmap_printk("kvm_set_pte_rmapp: spte %p %llx\n", sptep, *sptep); need_flush = 1; if (pte_write(*ptep)) { drop_spte(kvm, sptep); sptep = rmap_get_first(*rmapp, &iter); } else { new_spte = *sptep & ~PT64_BASE_ADDR_MASK; new_spte |= (u64)new_pfn << PAGE_SHIFT; new_spte &= ~PT_WRITABLE_MASK; new_spte &= ~SPTE_HOST_WRITEABLE; new_spte &= ~shadow_accessed_mask; mmu_spte_clear_track_bits(sptep); mmu_spte_set(sptep, new_spte); sptep = rmap_get_next(&iter); } } if (need_flush) kvm_flush_remote_tlbs(kvm); return 0; } static int kvm_handle_hva_range(struct kvm *kvm, unsigned long start, unsigned long end, unsigned long data, int (*handler)(struct kvm *kvm, unsigned long *rmapp, struct kvm_memory_slot *slot, unsigned long data)) { int j; int ret = 0; struct kvm_memslots *slots; struct kvm_memory_slot *memslot; slots = kvm_memslots(kvm); kvm_for_each_memslot(memslot, slots) { unsigned long hva_start, hva_end; gfn_t gfn_start, gfn_end; hva_start = max(start, memslot->userspace_addr); hva_end = min(end, memslot->userspace_addr + (memslot->npages << PAGE_SHIFT)); if (hva_start >= hva_end) continue; /* * {gfn(page) | page intersects with [hva_start, hva_end)} = * {gfn_start, gfn_start+1, ..., gfn_end-1}. */ gfn_start = hva_to_gfn_memslot(hva_start, memslot); gfn_end = hva_to_gfn_memslot(hva_end + PAGE_SIZE - 1, memslot); for (j = PT_PAGE_TABLE_LEVEL; j < PT_PAGE_TABLE_LEVEL + KVM_NR_PAGE_SIZES; ++j) { unsigned long idx, idx_end; unsigned long *rmapp; /* * {idx(page_j) | page_j intersects with * [hva_start, hva_end)} = {idx, idx+1, ..., idx_end}. */ idx = gfn_to_index(gfn_start, memslot->base_gfn, j); idx_end = gfn_to_index(gfn_end - 1, memslot->base_gfn, j); rmapp = __gfn_to_rmap(gfn_start, j, memslot); for (; idx <= idx_end; ++idx) ret |= handler(kvm, rmapp++, memslot, data); } } return ret; } static int kvm_handle_hva(struct kvm *kvm, unsigned long hva, unsigned long data, int (*handler)(struct kvm *kvm, unsigned long *rmapp, struct kvm_memory_slot *slot, unsigned long data)) { return kvm_handle_hva_range(kvm, hva, hva + 1, data, handler); } int kvm_unmap_hva(struct kvm *kvm, unsigned long hva) { return kvm_handle_hva(kvm, hva, 0, kvm_unmap_rmapp); } int kvm_unmap_hva_range(struct kvm *kvm, unsigned long start, unsigned long end) { return kvm_handle_hva_range(kvm, start, end, 0, kvm_unmap_rmapp); } void kvm_set_spte_hva(struct kvm *kvm, unsigned long hva, pte_t pte) { kvm_handle_hva(kvm, hva, (unsigned long)&pte, kvm_set_pte_rmapp); } static int kvm_age_rmapp(struct kvm *kvm, unsigned long *rmapp, struct kvm_memory_slot *slot, unsigned long data) { u64 *sptep; struct rmap_iterator uninitialized_var(iter); int young = 0; /* * In case of absence of EPT Access and Dirty Bits supports, * emulate the accessed bit for EPT, by checking if this page has * an EPT mapping, and clearing it if it does. On the next access, * a new EPT mapping will be established. * This has some overhead, but not as much as the cost of swapping * out actively used pages or breaking up actively used hugepages. */ if (!shadow_accessed_mask) { young = kvm_unmap_rmapp(kvm, rmapp, slot, data); goto out; } for (sptep = rmap_get_first(*rmapp, &iter); sptep; sptep = rmap_get_next(&iter)) { BUG_ON(!is_shadow_present_pte(*sptep)); if (*sptep & shadow_accessed_mask) { young = 1; clear_bit((ffs(shadow_accessed_mask) - 1), (unsigned long *)sptep); } } out: /* @data has hva passed to kvm_age_hva(). */ trace_kvm_age_page(data, slot, young); return young; } static int kvm_test_age_rmapp(struct kvm *kvm, unsigned long *rmapp, struct kvm_memory_slot *slot, unsigned long data) { u64 *sptep; struct rmap_iterator iter; int young = 0; /* * If there's no access bit in the secondary pte set by the * hardware it's up to gup-fast/gup to set the access bit in * the primary pte or in the page structure. */ if (!shadow_accessed_mask) goto out; for (sptep = rmap_get_first(*rmapp, &iter); sptep; sptep = rmap_get_next(&iter)) { BUG_ON(!is_shadow_present_pte(*sptep)); if (*sptep & shadow_accessed_mask) { young = 1; break; } } out: return young; } #define RMAP_RECYCLE_THRESHOLD 1000 static void rmap_recycle(struct kvm_vcpu *vcpu, u64 *spte, gfn_t gfn) { unsigned long *rmapp; struct kvm_mmu_page *sp; sp = page_header(__pa(spte)); rmapp = gfn_to_rmap(vcpu->kvm, gfn, sp->role.level); kvm_unmap_rmapp(vcpu->kvm, rmapp, NULL, 0); kvm_flush_remote_tlbs(vcpu->kvm); } int kvm_age_hva(struct kvm *kvm, unsigned long hva) { return kvm_handle_hva(kvm, hva, hva, kvm_age_rmapp); } int kvm_test_age_hva(struct kvm *kvm, unsigned long hva) { return kvm_handle_hva(kvm, hva, 0, kvm_test_age_rmapp); } #ifdef MMU_DEBUG static int is_empty_shadow_page(u64 *spt) { u64 *pos; u64 *end; for (pos = spt, end = pos + PAGE_SIZE / sizeof(u64); pos != end; pos++) if (is_shadow_present_pte(*pos)) { printk(KERN_ERR "%s: %p %llx\n", __func__, pos, *pos); return 0; } return 1; } #endif /* * This value is the sum of all of the kvm instances's * kvm->arch.n_used_mmu_pages values. We need a global, * aggregate version in order to make the slab shrinker * faster */ static inline void kvm_mod_used_mmu_pages(struct kvm *kvm, int nr) { kvm->arch.n_used_mmu_pages += nr; percpu_counter_add(&kvm_total_used_mmu_pages, nr); } static void kvm_mmu_free_page(struct kvm_mmu_page *sp) { ASSERT(is_empty_shadow_page(sp->spt)); hlist_del(&sp->hash_link); list_del(&sp->link); free_page((unsigned long)sp->spt); if (!sp->role.direct) free_page((unsigned long)sp->gfns); kmem_cache_free(mmu_page_header_cache, sp); } static unsigned kvm_page_table_hashfn(gfn_t gfn) { return gfn & ((1 << KVM_MMU_HASH_SHIFT) - 1); } static void mmu_page_add_parent_pte(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp, u64 *parent_pte) { if (!parent_pte) return; pte_list_add(vcpu, parent_pte, &sp->parent_ptes); } static void mmu_page_remove_parent_pte(struct kvm_mmu_page *sp, u64 *parent_pte) { pte_list_remove(parent_pte, &sp->parent_ptes); } static void drop_parent_pte(struct kvm_mmu_page *sp, u64 *parent_pte) { mmu_page_remove_parent_pte(sp, parent_pte); mmu_spte_clear_no_track(parent_pte); } static struct kvm_mmu_page *kvm_mmu_alloc_page(struct kvm_vcpu *vcpu, u64 *parent_pte, int direct) { struct kvm_mmu_page *sp; sp = mmu_memory_cache_alloc(&vcpu->arch.mmu_page_header_cache); sp->spt = mmu_memory_cache_alloc(&vcpu->arch.mmu_page_cache); if (!direct) sp->gfns = mmu_memory_cache_alloc(&vcpu->arch.mmu_page_cache); set_page_private(virt_to_page(sp->spt), (unsigned long)sp); /* * The active_mmu_pages list is the FIFO list, do not move the * page until it is zapped. kvm_zap_obsolete_pages depends on * this feature. See the comments in kvm_zap_obsolete_pages(). */ list_add(&sp->link, &vcpu->kvm->arch.active_mmu_pages); sp->parent_ptes = 0; mmu_page_add_parent_pte(vcpu, sp, parent_pte); kvm_mod_used_mmu_pages(vcpu->kvm, +1); return sp; } static void mark_unsync(u64 *spte); static void kvm_mmu_mark_parents_unsync(struct kvm_mmu_page *sp) { pte_list_walk(&sp->parent_ptes, mark_unsync); } static void mark_unsync(u64 *spte) { struct kvm_mmu_page *sp; unsigned int index; sp = page_header(__pa(spte)); index = spte - sp->spt; if (__test_and_set_bit(index, sp->unsync_child_bitmap)) return; if (sp->unsync_children++) return; kvm_mmu_mark_parents_unsync(sp); } static int nonpaging_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp) { return 1; } static void nonpaging_invlpg(struct kvm_vcpu *vcpu, gva_t gva) { } static void nonpaging_update_pte(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp, u64 *spte, const void *pte) { WARN_ON(1); } #define KVM_PAGE_ARRAY_NR 16 struct kvm_mmu_pages { struct mmu_page_and_offset { struct kvm_mmu_page *sp; unsigned int idx; } page[KVM_PAGE_ARRAY_NR]; unsigned int nr; }; static int mmu_pages_add(struct kvm_mmu_pages *pvec, struct kvm_mmu_page *sp, int idx) { int i; if (sp->unsync) for (i=0; i < pvec->nr; i++) if (pvec->page[i].sp == sp) return 0; pvec->page[pvec->nr].sp = sp; pvec->page[pvec->nr].idx = idx; pvec->nr++; return (pvec->nr == KVM_PAGE_ARRAY_NR); } static int __mmu_unsync_walk(struct kvm_mmu_page *sp, struct kvm_mmu_pages *pvec) { int i, ret, nr_unsync_leaf = 0; for_each_set_bit(i, sp->unsync_child_bitmap, 512) { struct kvm_mmu_page *child; u64 ent = sp->spt[i]; if (!is_shadow_present_pte(ent) || is_large_pte(ent)) goto clear_child_bitmap; child = page_header(ent & PT64_BASE_ADDR_MASK); if (child->unsync_children) { if (mmu_pages_add(pvec, child, i)) return -ENOSPC; ret = __mmu_unsync_walk(child, pvec); if (!ret) goto clear_child_bitmap; else if (ret > 0) nr_unsync_leaf += ret; else return ret; } else if (child->unsync) { nr_unsync_leaf++; if (mmu_pages_add(pvec, child, i)) return -ENOSPC; } else goto clear_child_bitmap; continue; clear_child_bitmap: __clear_bit(i, sp->unsync_child_bitmap); sp->unsync_children--; WARN_ON((int)sp->unsync_children < 0); } return nr_unsync_leaf; } static int mmu_unsync_walk(struct kvm_mmu_page *sp, struct kvm_mmu_pages *pvec) { if (!sp->unsync_children) return 0; mmu_pages_add(pvec, sp, 0); return __mmu_unsync_walk(sp, pvec); } static void kvm_unlink_unsync_page(struct kvm *kvm, struct kvm_mmu_page *sp) { WARN_ON(!sp->unsync); trace_kvm_mmu_sync_page(sp); sp->unsync = 0; --kvm->stat.mmu_unsync; } static int kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp, struct list_head *invalid_list); static void kvm_mmu_commit_zap_page(struct kvm *kvm, struct list_head *invalid_list); /* * NOTE: we should pay more attention on the zapped-obsolete page * (is_obsolete_sp(sp) && sp->role.invalid) when you do hash list walk * since it has been deleted from active_mmu_pages but still can be found * at hast list. * * for_each_gfn_indirect_valid_sp has skipped that kind of page and * kvm_mmu_get_page(), the only user of for_each_gfn_sp(), has skipped * all the obsolete pages. */ #define for_each_gfn_sp(_kvm, _sp, _gfn) \ hlist_for_each_entry(_sp, \ &(_kvm)->arch.mmu_page_hash[kvm_page_table_hashfn(_gfn)], hash_link) \ if ((_sp)->gfn != (_gfn)) {} else #define for_each_gfn_indirect_valid_sp(_kvm, _sp, _gfn) \ for_each_gfn_sp(_kvm, _sp, _gfn) \ if ((_sp)->role.direct || (_sp)->role.invalid) {} else /* @sp->gfn should be write-protected at the call site */ static int __kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp, struct list_head *invalid_list, bool clear_unsync) { if (sp->role.cr4_pae != !!is_pae(vcpu)) { kvm_mmu_prepare_zap_page(vcpu->kvm, sp, invalid_list); return 1; } if (clear_unsync) kvm_unlink_unsync_page(vcpu->kvm, sp); if (vcpu->arch.mmu.sync_page(vcpu, sp)) { kvm_mmu_prepare_zap_page(vcpu->kvm, sp, invalid_list); return 1; } kvm_mmu_flush_tlb(vcpu); return 0; } static int kvm_sync_page_transient(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp) { LIST_HEAD(invalid_list); int ret; ret = __kvm_sync_page(vcpu, sp, &invalid_list, false); if (ret) kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list); return ret; } #ifdef CONFIG_KVM_MMU_AUDIT #include "mmu_audit.c" #else static void kvm_mmu_audit(struct kvm_vcpu *vcpu, int point) { } static void mmu_audit_disable(void) { } #endif static int kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp, struct list_head *invalid_list) { return __kvm_sync_page(vcpu, sp, invalid_list, true); } /* @gfn should be write-protected at the call site */ static void kvm_sync_pages(struct kvm_vcpu *vcpu, gfn_t gfn) { struct kvm_mmu_page *s; LIST_HEAD(invalid_list); bool flush = false; for_each_gfn_indirect_valid_sp(vcpu->kvm, s, gfn) { if (!s->unsync) continue; WARN_ON(s->role.level != PT_PAGE_TABLE_LEVEL); kvm_unlink_unsync_page(vcpu->kvm, s); if ((s->role.cr4_pae != !!is_pae(vcpu)) || (vcpu->arch.mmu.sync_page(vcpu, s))) { kvm_mmu_prepare_zap_page(vcpu->kvm, s, &invalid_list); continue; } flush = true; } kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list); if (flush) kvm_mmu_flush_tlb(vcpu); } struct mmu_page_path { struct kvm_mmu_page *parent[PT64_ROOT_LEVEL-1]; unsigned int idx[PT64_ROOT_LEVEL-1]; }; #define for_each_sp(pvec, sp, parents, i) \ for (i = mmu_pages_next(&pvec, &parents, -1), \ sp = pvec.page[i].sp; \ i < pvec.nr && ({ sp = pvec.page[i].sp; 1;}); \ i = mmu_pages_next(&pvec, &parents, i)) static int mmu_pages_next(struct kvm_mmu_pages *pvec, struct mmu_page_path *parents, int i) { int n; for (n = i+1; n < pvec->nr; n++) { struct kvm_mmu_page *sp = pvec->page[n].sp; if (sp->role.level == PT_PAGE_TABLE_LEVEL) { parents->idx[0] = pvec->page[n].idx; return n; } parents->parent[sp->role.level-2] = sp; parents->idx[sp->role.level-1] = pvec->page[n].idx; } return n; } static void mmu_pages_clear_parents(struct mmu_page_path *parents) { struct kvm_mmu_page *sp; unsigned int level = 0; do { unsigned int idx = parents->idx[level]; sp = parents->parent[level]; if (!sp) return; --sp->unsync_children; WARN_ON((int)sp->unsync_children < 0); __clear_bit(idx, sp->unsync_child_bitmap); level++; } while (level < PT64_ROOT_LEVEL-1 && !sp->unsync_children); } static void kvm_mmu_pages_init(struct kvm_mmu_page *parent, struct mmu_page_path *parents, struct kvm_mmu_pages *pvec) { parents->parent[parent->role.level-1] = NULL; pvec->nr = 0; } static void mmu_sync_children(struct kvm_vcpu *vcpu, struct kvm_mmu_page *parent) { int i; struct kvm_mmu_page *sp; struct mmu_page_path parents; struct kvm_mmu_pages pages; LIST_HEAD(invalid_list); kvm_mmu_pages_init(parent, &parents, &pages); while (mmu_unsync_walk(parent, &pages)) { bool protected = false; for_each_sp(pages, sp, parents, i) protected |= rmap_write_protect(vcpu->kvm, sp->gfn); if (protected) kvm_flush_remote_tlbs(vcpu->kvm); for_each_sp(pages, sp, parents, i) { kvm_sync_page(vcpu, sp, &invalid_list); mmu_pages_clear_parents(&parents); } kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list); cond_resched_lock(&vcpu->kvm->mmu_lock); kvm_mmu_pages_init(parent, &parents, &pages); } } static void init_shadow_page_table(struct kvm_mmu_page *sp) { int i; for (i = 0; i < PT64_ENT_PER_PAGE; ++i) sp->spt[i] = 0ull; } static void __clear_sp_write_flooding_count(struct kvm_mmu_page *sp) { sp->write_flooding_count = 0; } static void clear_sp_write_flooding_count(u64 *spte) { struct kvm_mmu_page *sp = page_header(__pa(spte)); __clear_sp_write_flooding_count(sp); } static bool is_obsolete_sp(struct kvm *kvm, struct kvm_mmu_page *sp) { return unlikely(sp->mmu_valid_gen != kvm->arch.mmu_valid_gen); } static struct kvm_mmu_page *kvm_mmu_get_page(struct kvm_vcpu *vcpu, gfn_t gfn, gva_t gaddr, unsigned level, int direct, unsigned access, u64 *parent_pte) { union kvm_mmu_page_role role; unsigned quadrant; struct kvm_mmu_page *sp; bool need_sync = false; role = vcpu->arch.mmu.base_role; role.level = level; role.direct = direct; if (role.direct) role.cr4_pae = 0; role.access = access; if (!vcpu->arch.mmu.direct_map && vcpu->arch.mmu.root_level <= PT32_ROOT_LEVEL) { quadrant = gaddr >> (PAGE_SHIFT + (PT64_PT_BITS * level)); quadrant &= (1 << ((PT32_PT_BITS - PT64_PT_BITS) * level)) - 1; role.quadrant = quadrant; } for_each_gfn_sp(vcpu->kvm, sp, gfn) { if (is_obsolete_sp(vcpu->kvm, sp)) continue; if (!need_sync && sp->unsync) need_sync = true; if (sp->role.word != role.word) continue; if (sp->unsync && kvm_sync_page_transient(vcpu, sp)) break; mmu_page_add_parent_pte(vcpu, sp, parent_pte); if (sp->unsync_children) { kvm_make_request(KVM_REQ_MMU_SYNC, vcpu); kvm_mmu_mark_parents_unsync(sp); } else if (sp->unsync) kvm_mmu_mark_parents_unsync(sp); __clear_sp_write_flooding_count(sp); trace_kvm_mmu_get_page(sp, false); return sp; } ++vcpu->kvm->stat.mmu_cache_miss; sp = kvm_mmu_alloc_page(vcpu, parent_pte, direct); if (!sp) return sp; sp->gfn = gfn; sp->role = role; hlist_add_head(&sp->hash_link, &vcpu->kvm->arch.mmu_page_hash[kvm_page_table_hashfn(gfn)]); if (!direct) { if (rmap_write_protect(vcpu->kvm, gfn)) kvm_flush_remote_tlbs(vcpu->kvm); if (level > PT_PAGE_TABLE_LEVEL && need_sync) kvm_sync_pages(vcpu, gfn); account_shadowed(vcpu->kvm, gfn); } sp->mmu_valid_gen = vcpu->kvm->arch.mmu_valid_gen; init_shadow_page_table(sp); trace_kvm_mmu_get_page(sp, true); return sp; } static void shadow_walk_init(struct kvm_shadow_walk_iterator *iterator, struct kvm_vcpu *vcpu, u64 addr) { iterator->addr = addr; iterator->shadow_addr = vcpu->arch.mmu.root_hpa; iterator->level = vcpu->arch.mmu.shadow_root_level; if (iterator->level == PT64_ROOT_LEVEL && vcpu->arch.mmu.root_level < PT64_ROOT_LEVEL && !vcpu->arch.mmu.direct_map) --iterator->level; if (iterator->level == PT32E_ROOT_LEVEL) { iterator->shadow_addr = vcpu->arch.mmu.pae_root[(addr >> 30) & 3]; iterator->shadow_addr &= PT64_BASE_ADDR_MASK; --iterator->level; if (!iterator->shadow_addr) iterator->level = 0; } } static bool shadow_walk_okay(struct kvm_shadow_walk_iterator *iterator) { if (iterator->level < PT_PAGE_TABLE_LEVEL) return false; iterator->index = SHADOW_PT_INDEX(iterator->addr, iterator->level); iterator->sptep = ((u64 *)__va(iterator->shadow_addr)) + iterator->index; return true; } static void __shadow_walk_next(struct kvm_shadow_walk_iterator *iterator, u64 spte) { if (is_last_spte(spte, iterator->level)) { iterator->level = 0; return; } iterator->shadow_addr = spte & PT64_BASE_ADDR_MASK; --iterator->level; } static void shadow_walk_next(struct kvm_shadow_walk_iterator *iterator) { return __shadow_walk_next(iterator, *iterator->sptep); } static void link_shadow_page(u64 *sptep, struct kvm_mmu_page *sp, bool accessed) { u64 spte; BUILD_BUG_ON(VMX_EPT_READABLE_MASK != PT_PRESENT_MASK || VMX_EPT_WRITABLE_MASK != PT_WRITABLE_MASK); spte = __pa(sp->spt) | PT_PRESENT_MASK | PT_WRITABLE_MASK | shadow_user_mask | shadow_x_mask; if (accessed) spte |= shadow_accessed_mask; mmu_spte_set(sptep, spte); } static void validate_direct_spte(struct kvm_vcpu *vcpu, u64 *sptep, unsigned direct_access) { if (is_shadow_present_pte(*sptep) && !is_large_pte(*sptep)) { struct kvm_mmu_page *child; /* * For the direct sp, if the guest pte's dirty bit * changed form clean to dirty, it will corrupt the * sp's access: allow writable in the read-only sp, * so we should update the spte at this point to get * a new sp with the correct access. */ child = page_header(*sptep & PT64_BASE_ADDR_MASK); if (child->role.access == direct_access) return; drop_parent_pte(child, sptep); kvm_flush_remote_tlbs(vcpu->kvm); } } static bool mmu_page_zap_pte(struct kvm *kvm, struct kvm_mmu_page *sp, u64 *spte) { u64 pte; struct kvm_mmu_page *child; pte = *spte; if (is_shadow_present_pte(pte)) { if (is_last_spte(pte, sp->role.level)) { drop_spte(kvm, spte); if (is_large_pte(pte)) --kvm->stat.lpages; } else { child = page_header(pte & PT64_BASE_ADDR_MASK); drop_parent_pte(child, spte); } return true; } if (is_mmio_spte(pte)) mmu_spte_clear_no_track(spte); return false; } static void kvm_mmu_page_unlink_children(struct kvm *kvm, struct kvm_mmu_page *sp) { unsigned i; for (i = 0; i < PT64_ENT_PER_PAGE; ++i) mmu_page_zap_pte(kvm, sp, sp->spt + i); } static void kvm_mmu_put_page(struct kvm_mmu_page *sp, u64 *parent_pte) { mmu_page_remove_parent_pte(sp, parent_pte); } static void kvm_mmu_unlink_parents(struct kvm *kvm, struct kvm_mmu_page *sp) { u64 *sptep; struct rmap_iterator iter; while ((sptep = rmap_get_first(sp->parent_ptes, &iter))) drop_parent_pte(sp, sptep); } static int mmu_zap_unsync_children(struct kvm *kvm, struct kvm_mmu_page *parent, struct list_head *invalid_list) { int i, zapped = 0; struct mmu_page_path parents; struct kvm_mmu_pages pages; if (parent->role.level == PT_PAGE_TABLE_LEVEL) return 0; kvm_mmu_pages_init(parent, &parents, &pages); while (mmu_unsync_walk(parent, &pages)) { struct kvm_mmu_page *sp; for_each_sp(pages, sp, parents, i) { kvm_mmu_prepare_zap_page(kvm, sp, invalid_list); mmu_pages_clear_parents(&parents); zapped++; } kvm_mmu_pages_init(parent, &parents, &pages); } return zapped; } static int kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp, struct list_head *invalid_list) { int ret; trace_kvm_mmu_prepare_zap_page(sp); ++kvm->stat.mmu_shadow_zapped; ret = mmu_zap_unsync_children(kvm, sp, invalid_list); kvm_mmu_page_unlink_children(kvm, sp); kvm_mmu_unlink_parents(kvm, sp); if (!sp->role.invalid && !sp->role.direct) unaccount_shadowed(kvm, sp->gfn); if (sp->unsync) kvm_unlink_unsync_page(kvm, sp); if (!sp->root_count) { /* Count self */ ret++; list_move(&sp->link, invalid_list); kvm_mod_used_mmu_pages(kvm, -1); } else { list_move(&sp->link, &kvm->arch.active_mmu_pages); /* * The obsolete pages can not be used on any vcpus. * See the comments in kvm_mmu_invalidate_zap_all_pages(). */ if (!sp->role.invalid && !is_obsolete_sp(kvm, sp)) kvm_reload_remote_mmus(kvm); } sp->role.invalid = 1; return ret; } static void kvm_mmu_commit_zap_page(struct kvm *kvm, struct list_head *invalid_list) { struct kvm_mmu_page *sp, *nsp; if (list_empty(invalid_list)) return; /* * wmb: make sure everyone sees our modifications to the page tables * rmb: make sure we see changes to vcpu->mode */ smp_mb(); /* * Wait for all vcpus to exit guest mode and/or lockless shadow * page table walks. */ kvm_flush_remote_tlbs(kvm); list_for_each_entry_safe(sp, nsp, invalid_list, link) { WARN_ON(!sp->role.invalid || sp->root_count); kvm_mmu_free_page(sp); } } static bool prepare_zap_oldest_mmu_page(struct kvm *kvm, struct list_head *invalid_list) { struct kvm_mmu_page *sp; if (list_empty(&kvm->arch.active_mmu_pages)) return false; sp = list_entry(kvm->arch.active_mmu_pages.prev, struct kvm_mmu_page, link); kvm_mmu_prepare_zap_page(kvm, sp, invalid_list); return true; } /* * Changing the number of mmu pages allocated to the vm * Note: if goal_nr_mmu_pages is too small, you will get dead lock */ void kvm_mmu_change_mmu_pages(struct kvm *kvm, unsigned int goal_nr_mmu_pages) { LIST_HEAD(invalid_list); spin_lock(&kvm->mmu_lock); if (kvm->arch.n_used_mmu_pages > goal_nr_mmu_pages) { /* Need to free some mmu pages to achieve the goal. */ while (kvm->arch.n_used_mmu_pages > goal_nr_mmu_pages) if (!prepare_zap_oldest_mmu_page(kvm, &invalid_list)) break; kvm_mmu_commit_zap_page(kvm, &invalid_list); goal_nr_mmu_pages = kvm->arch.n_used_mmu_pages; } kvm->arch.n_max_mmu_pages = goal_nr_mmu_pages; spin_unlock(&kvm->mmu_lock); } int kvm_mmu_unprotect_page(struct kvm *kvm, gfn_t gfn) { struct kvm_mmu_page *sp; LIST_HEAD(invalid_list); int r; pgprintk("%s: looking for gfn %llx\n", __func__, gfn); r = 0; spin_lock(&kvm->mmu_lock); for_each_gfn_indirect_valid_sp(kvm, sp, gfn) { pgprintk("%s: gfn %llx role %x\n", __func__, gfn, sp->role.word); r = 1; kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list); } kvm_mmu_commit_zap_page(kvm, &invalid_list); spin_unlock(&kvm->mmu_lock); return r; } EXPORT_SYMBOL_GPL(kvm_mmu_unprotect_page); /* * The function is based on mtrr_type_lookup() in * arch/x86/kernel/cpu/mtrr/generic.c */ static int get_mtrr_type(struct mtrr_state_type *mtrr_state, u64 start, u64 end) { int i; u64 base, mask; u8 prev_match, curr_match; int num_var_ranges = KVM_NR_VAR_MTRR; if (!mtrr_state->enabled) return 0xFF; /* Make end inclusive end, instead of exclusive */ end--; /* Look in fixed ranges. Just return the type as per start */ if (mtrr_state->have_fixed && (start < 0x100000)) { int idx; if (start < 0x80000) { idx = 0; idx += (start >> 16); return mtrr_state->fixed_ranges[idx]; } else if (start < 0xC0000) { idx = 1 * 8; idx += ((start - 0x80000) >> 14); return mtrr_state->fixed_ranges[idx]; } else if (start < 0x1000000) { idx = 3 * 8; idx += ((start - 0xC0000) >> 12); return mtrr_state->fixed_ranges[idx]; } } /* * Look in variable ranges * Look of multiple ranges matching this address and pick type * as per MTRR precedence */ if (!(mtrr_state->enabled & 2)) return mtrr_state->def_type; prev_match = 0xFF; for (i = 0; i < num_var_ranges; ++i) { unsigned short start_state, end_state; if (!(mtrr_state->var_ranges[i].mask_lo & (1 << 11))) continue; base = (((u64)mtrr_state->var_ranges[i].base_hi) << 32) + (mtrr_state->var_ranges[i].base_lo & PAGE_MASK); mask = (((u64)mtrr_state->var_ranges[i].mask_hi) << 32) + (mtrr_state->var_ranges[i].mask_lo & PAGE_MASK); start_state = ((start & mask) == (base & mask)); end_state = ((end & mask) == (base & mask)); if (start_state != end_state) return 0xFE; if ((start & mask) != (base & mask)) continue; curr_match = mtrr_state->var_ranges[i].base_lo & 0xff; if (prev_match == 0xFF) { prev_match = curr_match; continue; } if (prev_match == MTRR_TYPE_UNCACHABLE || curr_match == MTRR_TYPE_UNCACHABLE) return MTRR_TYPE_UNCACHABLE; if ((prev_match == MTRR_TYPE_WRBACK && curr_match == MTRR_TYPE_WRTHROUGH) || (prev_match == MTRR_TYPE_WRTHROUGH && curr_match == MTRR_TYPE_WRBACK)) { prev_match = MTRR_TYPE_WRTHROUGH; curr_match = MTRR_TYPE_WRTHROUGH; } if (prev_match != curr_match) return MTRR_TYPE_UNCACHABLE; } if (prev_match != 0xFF) return prev_match; return mtrr_state->def_type; } u8 kvm_get_guest_memory_type(struct kvm_vcpu *vcpu, gfn_t gfn) { u8 mtrr; mtrr = get_mtrr_type(&vcpu->arch.mtrr_state, gfn << PAGE_SHIFT, (gfn << PAGE_SHIFT) + PAGE_SIZE); if (mtrr == 0xfe || mtrr == 0xff) mtrr = MTRR_TYPE_WRBACK; return mtrr; } EXPORT_SYMBOL_GPL(kvm_get_guest_memory_type); static void __kvm_unsync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp) { trace_kvm_mmu_unsync_page(sp); ++vcpu->kvm->stat.mmu_unsync; sp->unsync = 1; kvm_mmu_mark_parents_unsync(sp); } static void kvm_unsync_pages(struct kvm_vcpu *vcpu, gfn_t gfn) { struct kvm_mmu_page *s; for_each_gfn_indirect_valid_sp(vcpu->kvm, s, gfn) { if (s->unsync) continue; WARN_ON(s->role.level != PT_PAGE_TABLE_LEVEL); __kvm_unsync_page(vcpu, s); } } static int mmu_need_write_protect(struct kvm_vcpu *vcpu, gfn_t gfn, bool can_unsync) { struct kvm_mmu_page *s; bool need_unsync = false; for_each_gfn_indirect_valid_sp(vcpu->kvm, s, gfn) { if (!can_unsync) return 1; if (s->role.level != PT_PAGE_TABLE_LEVEL) return 1; if (!s->unsync) need_unsync = true; } if (need_unsync) kvm_unsync_pages(vcpu, gfn); return 0; } static int set_spte(struct kvm_vcpu *vcpu, u64 *sptep, unsigned pte_access, int level, gfn_t gfn, pfn_t pfn, bool speculative, bool can_unsync, bool host_writable) { u64 spte; int ret = 0; if (set_mmio_spte(vcpu->kvm, sptep, gfn, pfn, pte_access)) return 0; spte = PT_PRESENT_MASK; if (!speculative) spte |= shadow_accessed_mask; if (pte_access & ACC_EXEC_MASK) spte |= shadow_x_mask; else spte |= shadow_nx_mask; if (pte_access & ACC_USER_MASK) spte |= shadow_user_mask; if (level > PT_PAGE_TABLE_LEVEL) spte |= PT_PAGE_SIZE_MASK; if (tdp_enabled) spte |= kvm_x86_ops->get_mt_mask(vcpu, gfn, kvm_is_mmio_pfn(pfn)); if (host_writable) spte |= SPTE_HOST_WRITEABLE; else pte_access &= ~ACC_WRITE_MASK; spte |= (u64)pfn << PAGE_SHIFT; if (pte_access & ACC_WRITE_MASK) { /* * Other vcpu creates new sp in the window between * mapping_level() and acquiring mmu-lock. We can * allow guest to retry the access, the mapping can * be fixed if guest refault. */ if (level > PT_PAGE_TABLE_LEVEL && has_wrprotected_page(vcpu->kvm, gfn, level)) goto done; spte |= PT_WRITABLE_MASK | SPTE_MMU_WRITEABLE; /* * Optimization: for pte sync, if spte was writable the hash * lookup is unnecessary (and expensive). Write protection * is responsibility of mmu_get_page / kvm_sync_page. * Same reasoning can be applied to dirty page accounting. */ if (!can_unsync && is_writable_pte(*sptep)) goto set_pte; if (mmu_need_write_protect(vcpu, gfn, can_unsync)) { pgprintk("%s: found shadow page for %llx, marking ro\n", __func__, gfn); ret = 1; pte_access &= ~ACC_WRITE_MASK; spte &= ~(PT_WRITABLE_MASK | SPTE_MMU_WRITEABLE); } } if (pte_access & ACC_WRITE_MASK) mark_page_dirty(vcpu->kvm, gfn); set_pte: if (mmu_spte_update(sptep, spte)) kvm_flush_remote_tlbs(vcpu->kvm); done: return ret; } static void mmu_set_spte(struct kvm_vcpu *vcpu, u64 *sptep, unsigned pte_access, int write_fault, int *emulate, int level, gfn_t gfn, pfn_t pfn, bool speculative, bool host_writable) { int was_rmapped = 0; int rmap_count; pgprintk("%s: spte %llx write_fault %d gfn %llx\n", __func__, *sptep, write_fault, gfn); if (is_rmap_spte(*sptep)) { /* * If we overwrite a PTE page pointer with a 2MB PMD, unlink * the parent of the now unreachable PTE. */ if (level > PT_PAGE_TABLE_LEVEL && !is_large_pte(*sptep)) { struct kvm_mmu_page *child; u64 pte = *sptep; child = page_header(pte & PT64_BASE_ADDR_MASK); drop_parent_pte(child, sptep); kvm_flush_remote_tlbs(vcpu->kvm); } else if (pfn != spte_to_pfn(*sptep)) { pgprintk("hfn old %llx new %llx\n", spte_to_pfn(*sptep), pfn); drop_spte(vcpu->kvm, sptep); kvm_flush_remote_tlbs(vcpu->kvm); } else was_rmapped = 1; } if (set_spte(vcpu, sptep, pte_access, level, gfn, pfn, speculative, true, host_writable)) { if (write_fault) *emulate = 1; kvm_mmu_flush_tlb(vcpu); } if (unlikely(is_mmio_spte(*sptep) && emulate)) *emulate = 1; pgprintk("%s: setting spte %llx\n", __func__, *sptep); pgprintk("instantiating %s PTE (%s) at %llx (%llx) addr %p\n", is_large_pte(*sptep)? "2MB" : "4kB", *sptep & PT_PRESENT_MASK ?"RW":"R", gfn, *sptep, sptep); if (!was_rmapped && is_large_pte(*sptep)) ++vcpu->kvm->stat.lpages; if (is_shadow_present_pte(*sptep)) { if (!was_rmapped) { rmap_count = rmap_add(vcpu, sptep, gfn); if (rmap_count > RMAP_RECYCLE_THRESHOLD) rmap_recycle(vcpu, sptep, gfn); } } kvm_release_pfn_clean(pfn); } static void nonpaging_new_cr3(struct kvm_vcpu *vcpu) { mmu_free_roots(vcpu); } static pfn_t pte_prefetch_gfn_to_pfn(struct kvm_vcpu *vcpu, gfn_t gfn, bool no_dirty_log) { struct kvm_memory_slot *slot; slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, no_dirty_log); if (!slot) return KVM_PFN_ERR_FAULT; return gfn_to_pfn_memslot_atomic(slot, gfn); } static int direct_pte_prefetch_many(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp, u64 *start, u64 *end) { struct page *pages[PTE_PREFETCH_NUM]; unsigned access = sp->role.access; int i, ret; gfn_t gfn; gfn = kvm_mmu_page_get_gfn(sp, start - sp->spt); if (!gfn_to_memslot_dirty_bitmap(vcpu, gfn, access & ACC_WRITE_MASK)) return -1; ret = gfn_to_page_many_atomic(vcpu->kvm, gfn, pages, end - start); if (ret <= 0) return -1; for (i = 0; i < ret; i++, gfn++, start++) mmu_set_spte(vcpu, start, access, 0, NULL, sp->role.level, gfn, page_to_pfn(pages[i]), true, true); return 0; } static void __direct_pte_prefetch(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp, u64 *sptep) { u64 *spte, *start = NULL; int i; WARN_ON(!sp->role.direct); i = (sptep - sp->spt) & ~(PTE_PREFETCH_NUM - 1); spte = sp->spt + i; for (i = 0; i < PTE_PREFETCH_NUM; i++, spte++) { if (is_shadow_present_pte(*spte) || spte == sptep) { if (!start) continue; if (direct_pte_prefetch_many(vcpu, sp, start, spte) < 0) break; start = NULL; } else if (!start) start = spte; } } static void direct_pte_prefetch(struct kvm_vcpu *vcpu, u64 *sptep) { struct kvm_mmu_page *sp; /* * Since it's no accessed bit on EPT, it's no way to * distinguish between actually accessed translations * and prefetched, so disable pte prefetch if EPT is * enabled. */ if (!shadow_accessed_mask) return; sp = page_header(__pa(sptep)); if (sp->role.level > PT_PAGE_TABLE_LEVEL) return; __direct_pte_prefetch(vcpu, sp, sptep); } static int __direct_map(struct kvm_vcpu *vcpu, gpa_t v, int write, int map_writable, int level, gfn_t gfn, pfn_t pfn, bool prefault) { struct kvm_shadow_walk_iterator iterator; struct kvm_mmu_page *sp; int emulate = 0; gfn_t pseudo_gfn; for_each_shadow_entry(vcpu, (u64)gfn << PAGE_SHIFT, iterator) { if (iterator.level == level) { mmu_set_spte(vcpu, iterator.sptep, ACC_ALL, write, &emulate, level, gfn, pfn, prefault, map_writable); direct_pte_prefetch(vcpu, iterator.sptep); ++vcpu->stat.pf_fixed; break; } if (!is_shadow_present_pte(*iterator.sptep)) { u64 base_addr = iterator.addr; base_addr &= PT64_LVL_ADDR_MASK(iterator.level); pseudo_gfn = base_addr >> PAGE_SHIFT; sp = kvm_mmu_get_page(vcpu, pseudo_gfn, iterator.addr, iterator.level - 1, 1, ACC_ALL, iterator.sptep); link_shadow_page(iterator.sptep, sp, true); } } return emulate; } static void kvm_send_hwpoison_signal(unsigned long address, struct task_struct *tsk) { siginfo_t info; info.si_signo = SIGBUS; info.si_errno = 0; info.si_code = BUS_MCEERR_AR; info.si_addr = (void __user *)address; info.si_addr_lsb = PAGE_SHIFT; send_sig_info(SIGBUS, &info, tsk); } static int kvm_handle_bad_page(struct kvm_vcpu *vcpu, gfn_t gfn, pfn_t pfn) { /* * Do not cache the mmio info caused by writing the readonly gfn * into the spte otherwise read access on readonly gfn also can * caused mmio page fault and treat it as mmio access. * Return 1 to tell kvm to emulate it. */ if (pfn == KVM_PFN_ERR_RO_FAULT) return 1; if (pfn == KVM_PFN_ERR_HWPOISON) { kvm_send_hwpoison_signal(gfn_to_hva(vcpu->kvm, gfn), current); return 0; } return -EFAULT; } static void transparent_hugepage_adjust(struct kvm_vcpu *vcpu, gfn_t *gfnp, pfn_t *pfnp, int *levelp) { pfn_t pfn = *pfnp; gfn_t gfn = *gfnp; int level = *levelp; /* * Check if it's a transparent hugepage. If this would be an * hugetlbfs page, level wouldn't be set to * PT_PAGE_TABLE_LEVEL and there would be no adjustment done * here. */ if (!is_error_noslot_pfn(pfn) && !kvm_is_mmio_pfn(pfn) && level == PT_PAGE_TABLE_LEVEL && PageTransCompound(pfn_to_page(pfn)) && !has_wrprotected_page(vcpu->kvm, gfn, PT_DIRECTORY_LEVEL)) { unsigned long mask; /* * mmu_notifier_retry was successful and we hold the * mmu_lock here, so the pmd can't become splitting * from under us, and in turn * __split_huge_page_refcount() can't run from under * us and we can safely transfer the refcount from * PG_tail to PG_head as we switch the pfn to tail to * head. */ *levelp = level = PT_DIRECTORY_LEVEL; mask = KVM_PAGES_PER_HPAGE(level) - 1; VM_BUG_ON((gfn & mask) != (pfn & mask)); if (pfn & mask) { gfn &= ~mask; *gfnp = gfn; kvm_release_pfn_clean(pfn); pfn &= ~mask; kvm_get_pfn(pfn); *pfnp = pfn; } } } static bool handle_abnormal_pfn(struct kvm_vcpu *vcpu, gva_t gva, gfn_t gfn, pfn_t pfn, unsigned access, int *ret_val) { bool ret = true; /* The pfn is invalid, report the error! */ if (unlikely(is_error_pfn(pfn))) { *ret_val = kvm_handle_bad_page(vcpu, gfn, pfn); goto exit; } if (unlikely(is_noslot_pfn(pfn))) vcpu_cache_mmio_info(vcpu, gva, gfn, access); ret = false; exit: return ret; } static bool page_fault_can_be_fast(struct kvm_vcpu *vcpu, u32 error_code) { /* * Do not fix the mmio spte with invalid generation number which * need to be updated by slow page fault path. */ if (unlikely(error_code & PFERR_RSVD_MASK)) return false; /* * #PF can be fast only if the shadow page table is present and it * is caused by write-protect, that means we just need change the * W bit of the spte which can be done out of mmu-lock. */ if (!(error_code & PFERR_PRESENT_MASK) || !(error_code & PFERR_WRITE_MASK)) return false; return true; } static bool fast_pf_fix_direct_spte(struct kvm_vcpu *vcpu, u64 *sptep, u64 spte) { struct kvm_mmu_page *sp = page_header(__pa(sptep)); gfn_t gfn; WARN_ON(!sp->role.direct); /* * The gfn of direct spte is stable since it is calculated * by sp->gfn. */ gfn = kvm_mmu_page_get_gfn(sp, sptep - sp->spt); if (cmpxchg64(sptep, spte, spte | PT_WRITABLE_MASK) == spte) mark_page_dirty(vcpu->kvm, gfn); return true; } /* * Return value: * - true: let the vcpu to access on the same address again. * - false: let the real page fault path to fix it. */ static bool fast_page_fault(struct kvm_vcpu *vcpu, gva_t gva, int level, u32 error_code) { struct kvm_shadow_walk_iterator iterator; bool ret = false; u64 spte = 0ull; if (!page_fault_can_be_fast(vcpu, error_code)) return false; walk_shadow_page_lockless_begin(vcpu); for_each_shadow_entry_lockless(vcpu, gva, iterator, spte) if (!is_shadow_present_pte(spte) || iterator.level < level) break; /* * If the mapping has been changed, let the vcpu fault on the * same address again. */ if (!is_rmap_spte(spte)) { ret = true; goto exit; } if (!is_last_spte(spte, level)) goto exit; /* * Check if it is a spurious fault caused by TLB lazily flushed. * * Need not check the access of upper level table entries since * they are always ACC_ALL. */ if (is_writable_pte(spte)) { ret = true; goto exit; } /* * Currently, to simplify the code, only the spte write-protected * by dirty-log can be fast fixed. */ if (!spte_is_locklessly_modifiable(spte)) goto exit; /* * Currently, fast page fault only works for direct mapping since * the gfn is not stable for indirect shadow page. * See Documentation/virtual/kvm/locking.txt to get more detail. */ ret = fast_pf_fix_direct_spte(vcpu, iterator.sptep, spte); exit: trace_fast_page_fault(vcpu, gva, error_code, iterator.sptep, spte, ret); walk_shadow_page_lockless_end(vcpu); return ret; } static bool try_async_pf(struct kvm_vcpu *vcpu, bool prefault, gfn_t gfn, gva_t gva, pfn_t *pfn, bool write, bool *writable); static void make_mmu_pages_available(struct kvm_vcpu *vcpu); static int nonpaging_map(struct kvm_vcpu *vcpu, gva_t v, u32 error_code, gfn_t gfn, bool prefault) { int r; int level; int force_pt_level; pfn_t pfn; unsigned long mmu_seq; bool map_writable, write = error_code & PFERR_WRITE_MASK; force_pt_level = mapping_level_dirty_bitmap(vcpu, gfn); if (likely(!force_pt_level)) { level = mapping_level(vcpu, gfn); /* * This path builds a PAE pagetable - so we can map * 2mb pages at maximum. Therefore check if the level * is larger than that. */ if (level > PT_DIRECTORY_LEVEL) level = PT_DIRECTORY_LEVEL; gfn &= ~(KVM_PAGES_PER_HPAGE(level) - 1); } else level = PT_PAGE_TABLE_LEVEL; if (fast_page_fault(vcpu, v, level, error_code)) return 0; mmu_seq = vcpu->kvm->mmu_notifier_seq; smp_rmb(); if (try_async_pf(vcpu, prefault, gfn, v, &pfn, write, &map_writable)) return 0; if (handle_abnormal_pfn(vcpu, v, gfn, pfn, ACC_ALL, &r)) return r; spin_lock(&vcpu->kvm->mmu_lock); if (mmu_notifier_retry(vcpu->kvm, mmu_seq)) goto out_unlock; make_mmu_pages_available(vcpu); if (likely(!force_pt_level)) transparent_hugepage_adjust(vcpu, &gfn, &pfn, &level); r = __direct_map(vcpu, v, write, map_writable, level, gfn, pfn, prefault); spin_unlock(&vcpu->kvm->mmu_lock); return r; out_unlock: spin_unlock(&vcpu->kvm->mmu_lock); kvm_release_pfn_clean(pfn); return 0; } static void mmu_free_roots(struct kvm_vcpu *vcpu) { int i; struct kvm_mmu_page *sp; LIST_HEAD(invalid_list); if (!VALID_PAGE(vcpu->arch.mmu.root_hpa)) return; if (vcpu->arch.mmu.shadow_root_level == PT64_ROOT_LEVEL && (vcpu->arch.mmu.root_level == PT64_ROOT_LEVEL || vcpu->arch.mmu.direct_map)) { hpa_t root = vcpu->arch.mmu.root_hpa; spin_lock(&vcpu->kvm->mmu_lock); sp = page_header(root); --sp->root_count; if (!sp->root_count && sp->role.invalid) { kvm_mmu_prepare_zap_page(vcpu->kvm, sp, &invalid_list); kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list); } spin_unlock(&vcpu->kvm->mmu_lock); vcpu->arch.mmu.root_hpa = INVALID_PAGE; return; } spin_lock(&vcpu->kvm->mmu_lock); for (i = 0; i < 4; ++i) { hpa_t root = vcpu->arch.mmu.pae_root[i]; if (root) { root &= PT64_BASE_ADDR_MASK; sp = page_header(root); --sp->root_count; if (!sp->root_count && sp->role.invalid) kvm_mmu_prepare_zap_page(vcpu->kvm, sp, &invalid_list); } vcpu->arch.mmu.pae_root[i] = INVALID_PAGE; } kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list); spin_unlock(&vcpu->kvm->mmu_lock); vcpu->arch.mmu.root_hpa = INVALID_PAGE; } static int mmu_check_root(struct kvm_vcpu *vcpu, gfn_t root_gfn) { int ret = 0; if (!kvm_is_visible_gfn(vcpu->kvm, root_gfn)) { kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu); ret = 1; } return ret; } static int mmu_alloc_direct_roots(struct kvm_vcpu *vcpu) { struct kvm_mmu_page *sp; unsigned i; if (vcpu->arch.mmu.shadow_root_level == PT64_ROOT_LEVEL) { spin_lock(&vcpu->kvm->mmu_lock); make_mmu_pages_available(vcpu); sp = kvm_mmu_get_page(vcpu, 0, 0, PT64_ROOT_LEVEL, 1, ACC_ALL, NULL); ++sp->root_count; spin_unlock(&vcpu->kvm->mmu_lock); vcpu->arch.mmu.root_hpa = __pa(sp->spt); } else if (vcpu->arch.mmu.shadow_root_level == PT32E_ROOT_LEVEL) { for (i = 0; i < 4; ++i) { hpa_t root = vcpu->arch.mmu.pae_root[i]; ASSERT(!VALID_PAGE(root)); spin_lock(&vcpu->kvm->mmu_lock); make_mmu_pages_available(vcpu); sp = kvm_mmu_get_page(vcpu, i << (30 - PAGE_SHIFT), i << 30, PT32_ROOT_LEVEL, 1, ACC_ALL, NULL); root = __pa(sp->spt); ++sp->root_count; spin_unlock(&vcpu->kvm->mmu_lock); vcpu->arch.mmu.pae_root[i] = root | PT_PRESENT_MASK; } vcpu->arch.mmu.root_hpa = __pa(vcpu->arch.mmu.pae_root); } else BUG(); return 0; } static int mmu_alloc_shadow_roots(struct kvm_vcpu *vcpu) { struct kvm_mmu_page *sp; u64 pdptr, pm_mask; gfn_t root_gfn; int i; root_gfn = vcpu->arch.mmu.get_cr3(vcpu) >> PAGE_SHIFT; if (mmu_check_root(vcpu, root_gfn)) return 1; /* * Do we shadow a long mode page table? If so we need to * write-protect the guests page table root. */ if (vcpu->arch.mmu.root_level == PT64_ROOT_LEVEL) { hpa_t root = vcpu->arch.mmu.root_hpa; ASSERT(!VALID_PAGE(root)); spin_lock(&vcpu->kvm->mmu_lock); make_mmu_pages_available(vcpu); sp = kvm_mmu_get_page(vcpu, root_gfn, 0, PT64_ROOT_LEVEL, 0, ACC_ALL, NULL); root = __pa(sp->spt); ++sp->root_count; spin_unlock(&vcpu->kvm->mmu_lock); vcpu->arch.mmu.root_hpa = root; return 0; } /* * We shadow a 32 bit page table. This may be a legacy 2-level * or a PAE 3-level page table. In either case we need to be aware that * the shadow page table may be a PAE or a long mode page table. */ pm_mask = PT_PRESENT_MASK; if (vcpu->arch.mmu.shadow_root_level == PT64_ROOT_LEVEL) pm_mask |= PT_ACCESSED_MASK | PT_WRITABLE_MASK | PT_USER_MASK; for (i = 0; i < 4; ++i) { hpa_t root = vcpu->arch.mmu.pae_root[i]; ASSERT(!VALID_PAGE(root)); if (vcpu->arch.mmu.root_level == PT32E_ROOT_LEVEL) { pdptr = vcpu->arch.mmu.get_pdptr(vcpu, i); if (!is_present_gpte(pdptr)) { vcpu->arch.mmu.pae_root[i] = 0; continue; } root_gfn = pdptr >> PAGE_SHIFT; if (mmu_check_root(vcpu, root_gfn)) return 1; } spin_lock(&vcpu->kvm->mmu_lock); make_mmu_pages_available(vcpu); sp = kvm_mmu_get_page(vcpu, root_gfn, i << 30, PT32_ROOT_LEVEL, 0, ACC_ALL, NULL); root = __pa(sp->spt); ++sp->root_count; spin_unlock(&vcpu->kvm->mmu_lock); vcpu->arch.mmu.pae_root[i] = root | pm_mask; } vcpu->arch.mmu.root_hpa = __pa(vcpu->arch.mmu.pae_root); /* * If we shadow a 32 bit page table with a long mode page * table we enter this path. */ if (vcpu->arch.mmu.shadow_root_level == PT64_ROOT_LEVEL) { if (vcpu->arch.mmu.lm_root == NULL) { /* * The additional page necessary for this is only * allocated on demand. */ u64 *lm_root; lm_root = (void*)get_zeroed_page(GFP_KERNEL); if (lm_root == NULL) return 1; lm_root[0] = __pa(vcpu->arch.mmu.pae_root) | pm_mask; vcpu->arch.mmu.lm_root = lm_root; } vcpu->arch.mmu.root_hpa = __pa(vcpu->arch.mmu.lm_root); } return 0; } static int mmu_alloc_roots(struct kvm_vcpu *vcpu) { if (vcpu->arch.mmu.direct_map) return mmu_alloc_direct_roots(vcpu); else return mmu_alloc_shadow_roots(vcpu); } static void mmu_sync_roots(struct kvm_vcpu *vcpu) { int i; struct kvm_mmu_page *sp; if (vcpu->arch.mmu.direct_map) return; if (!VALID_PAGE(vcpu->arch.mmu.root_hpa)) return; vcpu_clear_mmio_info(vcpu, ~0ul); kvm_mmu_audit(vcpu, AUDIT_PRE_SYNC); if (vcpu->arch.mmu.root_level == PT64_ROOT_LEVEL) { hpa_t root = vcpu->arch.mmu.root_hpa; sp = page_header(root); mmu_sync_children(vcpu, sp); kvm_mmu_audit(vcpu, AUDIT_POST_SYNC); return; } for (i = 0; i < 4; ++i) { hpa_t root = vcpu->arch.mmu.pae_root[i]; if (root && VALID_PAGE(root)) { root &= PT64_BASE_ADDR_MASK; sp = page_header(root); mmu_sync_children(vcpu, sp); } } kvm_mmu_audit(vcpu, AUDIT_POST_SYNC); } void kvm_mmu_sync_roots(struct kvm_vcpu *vcpu) { spin_lock(&vcpu->kvm->mmu_lock); mmu_sync_roots(vcpu); spin_unlock(&vcpu->kvm->mmu_lock); } static gpa_t nonpaging_gva_to_gpa(struct kvm_vcpu *vcpu, gva_t vaddr, u32 access, struct x86_exception *exception) { if (exception) exception->error_code = 0; return vaddr; } static gpa_t nonpaging_gva_to_gpa_nested(struct kvm_vcpu *vcpu, gva_t vaddr, u32 access, struct x86_exception *exception) { if (exception) exception->error_code = 0; return vcpu->arch.nested_mmu.translate_gpa(vcpu, vaddr, access); } static bool quickly_check_mmio_pf(struct kvm_vcpu *vcpu, u64 addr, bool direct) { if (direct) return vcpu_match_mmio_gpa(vcpu, addr); return vcpu_match_mmio_gva(vcpu, addr); } /* * On direct hosts, the last spte is only allows two states * for mmio page fault: * - It is the mmio spte * - It is zapped or it is being zapped. * * This function completely checks the spte when the last spte * is not the mmio spte. */ static bool check_direct_spte_mmio_pf(u64 spte) { return __check_direct_spte_mmio_pf(spte); } static u64 walk_shadow_page_get_mmio_spte(struct kvm_vcpu *vcpu, u64 addr) { struct kvm_shadow_walk_iterator iterator; u64 spte = 0ull; walk_shadow_page_lockless_begin(vcpu); for_each_shadow_entry_lockless(vcpu, addr, iterator, spte) if (!is_shadow_present_pte(spte)) break; walk_shadow_page_lockless_end(vcpu); return spte; } int handle_mmio_page_fault_common(struct kvm_vcpu *vcpu, u64 addr, bool direct) { u64 spte; if (quickly_check_mmio_pf(vcpu, addr, direct)) return RET_MMIO_PF_EMULATE; spte = walk_shadow_page_get_mmio_spte(vcpu, addr); if (is_mmio_spte(spte)) { gfn_t gfn = get_mmio_spte_gfn(spte); unsigned access = get_mmio_spte_access(spte); if (!check_mmio_spte(vcpu->kvm, spte)) return RET_MMIO_PF_INVALID; if (direct) addr = 0; trace_handle_mmio_page_fault(addr, gfn, access); vcpu_cache_mmio_info(vcpu, addr, gfn, access); return RET_MMIO_PF_EMULATE; } /* * It's ok if the gva is remapped by other cpus on shadow guest, * it's a BUG if the gfn is not a mmio page. */ if (direct && !check_direct_spte_mmio_pf(spte)) return RET_MMIO_PF_BUG; /* * If the page table is zapped by other cpus, let CPU fault again on * the address. */ return RET_MMIO_PF_RETRY; } EXPORT_SYMBOL_GPL(handle_mmio_page_fault_common); static int handle_mmio_page_fault(struct kvm_vcpu *vcpu, u64 addr, u32 error_code, bool direct) { int ret; ret = handle_mmio_page_fault_common(vcpu, addr, direct); WARN_ON(ret == RET_MMIO_PF_BUG); return ret; } static int nonpaging_page_fault(struct kvm_vcpu *vcpu, gva_t gva, u32 error_code, bool prefault) { gfn_t gfn; int r; pgprintk("%s: gva %lx error %x\n", __func__, gva, error_code); if (unlikely(error_code & PFERR_RSVD_MASK)) { r = handle_mmio_page_fault(vcpu, gva, error_code, true); if (likely(r != RET_MMIO_PF_INVALID)) return r; } r = mmu_topup_memory_caches(vcpu); if (r) return r; ASSERT(vcpu); ASSERT(VALID_PAGE(vcpu->arch.mmu.root_hpa)); gfn = gva >> PAGE_SHIFT; return nonpaging_map(vcpu, gva & PAGE_MASK, error_code, gfn, prefault); } static int kvm_arch_setup_async_pf(struct kvm_vcpu *vcpu, gva_t gva, gfn_t gfn) { struct kvm_arch_async_pf arch; arch.token = (vcpu->arch.apf.id++ << 12) | vcpu->vcpu_id; arch.gfn = gfn; arch.direct_map = vcpu->arch.mmu.direct_map; arch.cr3 = vcpu->arch.mmu.get_cr3(vcpu); return kvm_setup_async_pf(vcpu, gva, gfn, &arch); } static bool can_do_async_pf(struct kvm_vcpu *vcpu) { if (unlikely(!irqchip_in_kernel(vcpu->kvm) || kvm_event_needs_reinjection(vcpu))) return false; return kvm_x86_ops->interrupt_allowed(vcpu); } static bool try_async_pf(struct kvm_vcpu *vcpu, bool prefault, gfn_t gfn, gva_t gva, pfn_t *pfn, bool write, bool *writable) { bool async; *pfn = gfn_to_pfn_async(vcpu->kvm, gfn, &async, write, writable); if (!async) return false; /* *pfn has correct page already */ if (!prefault && can_do_async_pf(vcpu)) { trace_kvm_try_async_get_page(gva, gfn); if (kvm_find_async_pf_gfn(vcpu, gfn)) { trace_kvm_async_pf_doublefault(gva, gfn); kvm_make_request(KVM_REQ_APF_HALT, vcpu); return true; } else if (kvm_arch_setup_async_pf(vcpu, gva, gfn)) return true; } *pfn = gfn_to_pfn_prot(vcpu->kvm, gfn, write, writable); return false; } static int tdp_page_fault(struct kvm_vcpu *vcpu, gva_t gpa, u32 error_code, bool prefault) { pfn_t pfn; int r; int level; int force_pt_level; gfn_t gfn = gpa >> PAGE_SHIFT; unsigned long mmu_seq; int write = error_code & PFERR_WRITE_MASK; bool map_writable; ASSERT(vcpu); ASSERT(VALID_PAGE(vcpu->arch.mmu.root_hpa)); if (unlikely(error_code & PFERR_RSVD_MASK)) { r = handle_mmio_page_fault(vcpu, gpa, error_code, true); if (likely(r != RET_MMIO_PF_INVALID)) return r; } r = mmu_topup_memory_caches(vcpu); if (r) return r; force_pt_level = mapping_level_dirty_bitmap(vcpu, gfn); if (likely(!force_pt_level)) { level = mapping_level(vcpu, gfn); gfn &= ~(KVM_PAGES_PER_HPAGE(level) - 1); } else level = PT_PAGE_TABLE_LEVEL; if (fast_page_fault(vcpu, gpa, level, error_code)) return 0; mmu_seq = vcpu->kvm->mmu_notifier_seq; smp_rmb(); if (try_async_pf(vcpu, prefault, gfn, gpa, &pfn, write, &map_writable)) return 0; if (handle_abnormal_pfn(vcpu, 0, gfn, pfn, ACC_ALL, &r)) return r; spin_lock(&vcpu->kvm->mmu_lock); if (mmu_notifier_retry(vcpu->kvm, mmu_seq)) goto out_unlock; make_mmu_pages_available(vcpu); if (likely(!force_pt_level)) transparent_hugepage_adjust(vcpu, &gfn, &pfn, &level); r = __direct_map(vcpu, gpa, write, map_writable, level, gfn, pfn, prefault); spin_unlock(&vcpu->kvm->mmu_lock); return r; out_unlock: spin_unlock(&vcpu->kvm->mmu_lock); kvm_release_pfn_clean(pfn); return 0; } static void nonpaging_free(struct kvm_vcpu *vcpu) { mmu_free_roots(vcpu); } static int nonpaging_init_context(struct kvm_vcpu *vcpu, struct kvm_mmu *context) { context->new_cr3 = nonpaging_new_cr3; context->page_fault = nonpaging_page_fault; context->gva_to_gpa = nonpaging_gva_to_gpa; context->free = nonpaging_free; context->sync_page = nonpaging_sync_page; context->invlpg = nonpaging_invlpg; context->update_pte = nonpaging_update_pte; context->root_level = 0; context->shadow_root_level = PT32E_ROOT_LEVEL; context->root_hpa = INVALID_PAGE; context->direct_map = true; context->nx = false; return 0; } void kvm_mmu_flush_tlb(struct kvm_vcpu *vcpu) { ++vcpu->stat.tlb_flush; kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu); } static void paging_new_cr3(struct kvm_vcpu *vcpu) { pgprintk("%s: cr3 %lx\n", __func__, kvm_read_cr3(vcpu)); mmu_free_roots(vcpu); } static unsigned long get_cr3(struct kvm_vcpu *vcpu) { return kvm_read_cr3(vcpu); } static void inject_page_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault) { vcpu->arch.mmu.inject_page_fault(vcpu, fault); } static void paging_free(struct kvm_vcpu *vcpu) { nonpaging_free(vcpu); } static bool sync_mmio_spte(struct kvm *kvm, u64 *sptep, gfn_t gfn, unsigned access, int *nr_present) { if (unlikely(is_mmio_spte(*sptep))) { if (gfn != get_mmio_spte_gfn(*sptep)) { mmu_spte_clear_no_track(sptep); return true; } (*nr_present)++; mark_mmio_spte(kvm, sptep, gfn, access); return true; } return false; } static inline bool is_last_gpte(struct kvm_mmu *mmu, unsigned level, unsigned gpte) { unsigned index; index = level - 1; index |= (gpte & PT_PAGE_SIZE_MASK) >> (PT_PAGE_SIZE_SHIFT - 2); return mmu->last_pte_bitmap & (1 << index); } #define PTTYPE_EPT 18 /* arbitrary */ #define PTTYPE PTTYPE_EPT #include "paging_tmpl.h" #undef PTTYPE #define PTTYPE 64 #include "paging_tmpl.h" #undef PTTYPE #define PTTYPE 32 #include "paging_tmpl.h" #undef PTTYPE static void reset_rsvds_bits_mask(struct kvm_vcpu *vcpu, struct kvm_mmu *context) { int maxphyaddr = cpuid_maxphyaddr(vcpu); u64 exb_bit_rsvd = 0; context->bad_mt_xwr = 0; if (!context->nx) exb_bit_rsvd = rsvd_bits(63, 63); switch (context->root_level) { case PT32_ROOT_LEVEL: /* no rsvd bits for 2 level 4K page table entries */ context->rsvd_bits_mask[0][1] = 0; context->rsvd_bits_mask[0][0] = 0; context->rsvd_bits_mask[1][0] = context->rsvd_bits_mask[0][0]; if (!is_pse(vcpu)) { context->rsvd_bits_mask[1][1] = 0; break; } if (is_cpuid_PSE36()) /* 36bits PSE 4MB page */ context->rsvd_bits_mask[1][1] = rsvd_bits(17, 21); else /* 32 bits PSE 4MB page */ context->rsvd_bits_mask[1][1] = rsvd_bits(13, 21); break; case PT32E_ROOT_LEVEL: context->rsvd_bits_mask[0][2] = rsvd_bits(maxphyaddr, 63) | rsvd_bits(7, 8) | rsvd_bits(1, 2); /* PDPTE */ context->rsvd_bits_mask[0][1] = exb_bit_rsvd | rsvd_bits(maxphyaddr, 62); /* PDE */ context->rsvd_bits_mask[0][0] = exb_bit_rsvd | rsvd_bits(maxphyaddr, 62); /* PTE */ context->rsvd_bits_mask[1][1] = exb_bit_rsvd | rsvd_bits(maxphyaddr, 62) | rsvd_bits(13, 20); /* large page */ context->rsvd_bits_mask[1][0] = context->rsvd_bits_mask[0][0]; break; case PT64_ROOT_LEVEL: context->rsvd_bits_mask[0][3] = exb_bit_rsvd | rsvd_bits(maxphyaddr, 51) | rsvd_bits(7, 8); context->rsvd_bits_mask[0][2] = exb_bit_rsvd | rsvd_bits(maxphyaddr, 51) | rsvd_bits(7, 8); context->rsvd_bits_mask[0][1] = exb_bit_rsvd | rsvd_bits(maxphyaddr, 51); context->rsvd_bits_mask[0][0] = exb_bit_rsvd | rsvd_bits(maxphyaddr, 51); context->rsvd_bits_mask[1][3] = context->rsvd_bits_mask[0][3]; context->rsvd_bits_mask[1][2] = exb_bit_rsvd | rsvd_bits(maxphyaddr, 51) | rsvd_bits(13, 29); context->rsvd_bits_mask[1][1] = exb_bit_rsvd | rsvd_bits(maxphyaddr, 51) | rsvd_bits(13, 20); /* large page */ context->rsvd_bits_mask[1][0] = context->rsvd_bits_mask[0][0]; break; } } static void reset_rsvds_bits_mask_ept(struct kvm_vcpu *vcpu, struct kvm_mmu *context, bool execonly) { int maxphyaddr = cpuid_maxphyaddr(vcpu); int pte; context->rsvd_bits_mask[0][3] = rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 7); context->rsvd_bits_mask[0][2] = rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 6); context->rsvd_bits_mask[0][1] = rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 6); context->rsvd_bits_mask[0][0] = rsvd_bits(maxphyaddr, 51); /* large page */ context->rsvd_bits_mask[1][3] = context->rsvd_bits_mask[0][3]; context->rsvd_bits_mask[1][2] = rsvd_bits(maxphyaddr, 51) | rsvd_bits(12, 29); context->rsvd_bits_mask[1][1] = rsvd_bits(maxphyaddr, 51) | rsvd_bits(12, 20); context->rsvd_bits_mask[1][0] = context->rsvd_bits_mask[0][0]; for (pte = 0; pte < 64; pte++) { int rwx_bits = pte & 7; int mt = pte >> 3; if (mt == 0x2 || mt == 0x3 || mt == 0x7 || rwx_bits == 0x2 || rwx_bits == 0x6 || (rwx_bits == 0x4 && !execonly)) context->bad_mt_xwr |= (1ull << pte); } } static void update_permission_bitmask(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu, bool ept) { unsigned bit, byte, pfec; u8 map; bool fault, x, w, u, wf, uf, ff, smep; smep = kvm_read_cr4_bits(vcpu, X86_CR4_SMEP); for (byte = 0; byte < ARRAY_SIZE(mmu->permissions); ++byte) { pfec = byte << 1; map = 0; wf = pfec & PFERR_WRITE_MASK; uf = pfec & PFERR_USER_MASK; ff = pfec & PFERR_FETCH_MASK; for (bit = 0; bit < 8; ++bit) { x = bit & ACC_EXEC_MASK; w = bit & ACC_WRITE_MASK; u = bit & ACC_USER_MASK; if (!ept) { /* Not really needed: !nx will cause pte.nx to fault */ x |= !mmu->nx; /* Allow supervisor writes if !cr0.wp */ w |= !is_write_protection(vcpu) && !uf; /* Disallow supervisor fetches of user code if cr4.smep */ x &= !(smep && u && !uf); } else /* Not really needed: no U/S accesses on ept */ u = 1; fault = (ff && !x) || (uf && !u) || (wf && !w); map |= fault << bit; } mmu->permissions[byte] = map; } } static void update_last_pte_bitmap(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu) { u8 map; unsigned level, root_level = mmu->root_level; const unsigned ps_set_index = 1 << 2; /* bit 2 of index: ps */ if (root_level == PT32E_ROOT_LEVEL) --root_level; /* PT_PAGE_TABLE_LEVEL always terminates */ map = 1 | (1 << ps_set_index); for (level = PT_DIRECTORY_LEVEL; level <= root_level; ++level) { if (level <= PT_PDPE_LEVEL && (mmu->root_level >= PT32E_ROOT_LEVEL || is_pse(vcpu))) map |= 1 << (ps_set_index | (level - 1)); } mmu->last_pte_bitmap = map; } static int paging64_init_context_common(struct kvm_vcpu *vcpu, struct kvm_mmu *context, int level) { context->nx = is_nx(vcpu); context->root_level = level; reset_rsvds_bits_mask(vcpu, context); update_permission_bitmask(vcpu, context, false); update_last_pte_bitmap(vcpu, context); ASSERT(is_pae(vcpu)); context->new_cr3 = paging_new_cr3; context->page_fault = paging64_page_fault; context->gva_to_gpa = paging64_gva_to_gpa; context->sync_page = paging64_sync_page; context->invlpg = paging64_invlpg; context->update_pte = paging64_update_pte; context->free = paging_free; context->shadow_root_level = level; context->root_hpa = INVALID_PAGE; context->direct_map = false; return 0; } static int paging64_init_context(struct kvm_vcpu *vcpu, struct kvm_mmu *context) { return paging64_init_context_common(vcpu, context, PT64_ROOT_LEVEL); } static int paging32_init_context(struct kvm_vcpu *vcpu, struct kvm_mmu *context) { context->nx = false; context->root_level = PT32_ROOT_LEVEL; reset_rsvds_bits_mask(vcpu, context); update_permission_bitmask(vcpu, context, false); update_last_pte_bitmap(vcpu, context); context->new_cr3 = paging_new_cr3; context->page_fault = paging32_page_fault; context->gva_to_gpa = paging32_gva_to_gpa; context->free = paging_free; context->sync_page = paging32_sync_page; context->invlpg = paging32_invlpg; context->update_pte = paging32_update_pte; context->shadow_root_level = PT32E_ROOT_LEVEL; context->root_hpa = INVALID_PAGE; context->direct_map = false; return 0; } static int paging32E_init_context(struct kvm_vcpu *vcpu, struct kvm_mmu *context) { return paging64_init_context_common(vcpu, context, PT32E_ROOT_LEVEL); } static int init_kvm_tdp_mmu(struct kvm_vcpu *vcpu) { struct kvm_mmu *context = vcpu->arch.walk_mmu; context->base_role.word = 0; context->new_cr3 = nonpaging_new_cr3; context->page_fault = tdp_page_fault; context->free = nonpaging_free; context->sync_page = nonpaging_sync_page; context->invlpg = nonpaging_invlpg; context->update_pte = nonpaging_update_pte; context->shadow_root_level = kvm_x86_ops->get_tdp_level(); context->root_hpa = INVALID_PAGE; context->direct_map = true; context->set_cr3 = kvm_x86_ops->set_tdp_cr3; context->get_cr3 = get_cr3; context->get_pdptr = kvm_pdptr_read; context->inject_page_fault = kvm_inject_page_fault; if (!is_paging(vcpu)) { context->nx = false; context->gva_to_gpa = nonpaging_gva_to_gpa; context->root_level = 0; } else if (is_long_mode(vcpu)) { context->nx = is_nx(vcpu); context->root_level = PT64_ROOT_LEVEL; reset_rsvds_bits_mask(vcpu, context); context->gva_to_gpa = paging64_gva_to_gpa; } else if (is_pae(vcpu)) { context->nx = is_nx(vcpu); context->root_level = PT32E_ROOT_LEVEL; reset_rsvds_bits_mask(vcpu, context); context->gva_to_gpa = paging64_gva_to_gpa; } else { context->nx = false; context->root_level = PT32_ROOT_LEVEL; reset_rsvds_bits_mask(vcpu, context); context->gva_to_gpa = paging32_gva_to_gpa; } update_permission_bitmask(vcpu, context, false); update_last_pte_bitmap(vcpu, context); return 0; } int kvm_init_shadow_mmu(struct kvm_vcpu *vcpu, struct kvm_mmu *context) { int r; bool smep = kvm_read_cr4_bits(vcpu, X86_CR4_SMEP); ASSERT(vcpu); ASSERT(!VALID_PAGE(vcpu->arch.mmu.root_hpa)); if (!is_paging(vcpu)) r = nonpaging_init_context(vcpu, context); else if (is_long_mode(vcpu)) r = paging64_init_context(vcpu, context); else if (is_pae(vcpu)) r = paging32E_init_context(vcpu, context); else r = paging32_init_context(vcpu, context); vcpu->arch.mmu.base_role.nxe = is_nx(vcpu); vcpu->arch.mmu.base_role.cr4_pae = !!is_pae(vcpu); vcpu->arch.mmu.base_role.cr0_wp = is_write_protection(vcpu); vcpu->arch.mmu.base_role.smep_andnot_wp = smep && !is_write_protection(vcpu); return r; } EXPORT_SYMBOL_GPL(kvm_init_shadow_mmu); int kvm_init_shadow_ept_mmu(struct kvm_vcpu *vcpu, struct kvm_mmu *context, bool execonly) { ASSERT(vcpu); ASSERT(!VALID_PAGE(vcpu->arch.mmu.root_hpa)); context->shadow_root_level = kvm_x86_ops->get_tdp_level(); context->nx = true; context->new_cr3 = paging_new_cr3; context->page_fault = ept_page_fault; context->gva_to_gpa = ept_gva_to_gpa; context->sync_page = ept_sync_page; context->invlpg = ept_invlpg; context->update_pte = ept_update_pte; context->free = paging_free; context->root_level = context->shadow_root_level; context->root_hpa = INVALID_PAGE; context->direct_map = false; update_permission_bitmask(vcpu, context, true); reset_rsvds_bits_mask_ept(vcpu, context, execonly); return 0; } EXPORT_SYMBOL_GPL(kvm_init_shadow_ept_mmu); static int init_kvm_softmmu(struct kvm_vcpu *vcpu) { int r = kvm_init_shadow_mmu(vcpu, vcpu->arch.walk_mmu); vcpu->arch.walk_mmu->set_cr3 = kvm_x86_ops->set_cr3; vcpu->arch.walk_mmu->get_cr3 = get_cr3; vcpu->arch.walk_mmu->get_pdptr = kvm_pdptr_read; vcpu->arch.walk_mmu->inject_page_fault = kvm_inject_page_fault; return r; } static int init_kvm_nested_mmu(struct kvm_vcpu *vcpu) { struct kvm_mmu *g_context = &vcpu->arch.nested_mmu; g_context->get_cr3 = get_cr3; g_context->get_pdptr = kvm_pdptr_read; g_context->inject_page_fault = kvm_inject_page_fault; /* * Note that arch.mmu.gva_to_gpa translates l2_gva to l1_gpa. The * translation of l2_gpa to l1_gpa addresses is done using the * arch.nested_mmu.gva_to_gpa function. Basically the gva_to_gpa * functions between mmu and nested_mmu are swapped. */ if (!is_paging(vcpu)) { g_context->nx = false; g_context->root_level = 0; g_context->gva_to_gpa = nonpaging_gva_to_gpa_nested; } else if (is_long_mode(vcpu)) { g_context->nx = is_nx(vcpu); g_context->root_level = PT64_ROOT_LEVEL; reset_rsvds_bits_mask(vcpu, g_context); g_context->gva_to_gpa = paging64_gva_to_gpa_nested; } else if (is_pae(vcpu)) { g_context->nx = is_nx(vcpu); g_context->root_level = PT32E_ROOT_LEVEL; reset_rsvds_bits_mask(vcpu, g_context); g_context->gva_to_gpa = paging64_gva_to_gpa_nested; } else { g_context->nx = false; g_context->root_level = PT32_ROOT_LEVEL; reset_rsvds_bits_mask(vcpu, g_context); g_context->gva_to_gpa = paging32_gva_to_gpa_nested; } update_permission_bitmask(vcpu, g_context, false); update_last_pte_bitmap(vcpu, g_context); return 0; } static int init_kvm_mmu(struct kvm_vcpu *vcpu) { if (mmu_is_nested(vcpu)) return init_kvm_nested_mmu(vcpu); else if (tdp_enabled) return init_kvm_tdp_mmu(vcpu); else return init_kvm_softmmu(vcpu); } static void destroy_kvm_mmu(struct kvm_vcpu *vcpu) { ASSERT(vcpu); if (VALID_PAGE(vcpu->arch.mmu.root_hpa)) /* mmu.free() should set root_hpa = INVALID_PAGE */ vcpu->arch.mmu.free(vcpu); } int kvm_mmu_reset_context(struct kvm_vcpu *vcpu) { destroy_kvm_mmu(vcpu); return init_kvm_mmu(vcpu); } EXPORT_SYMBOL_GPL(kvm_mmu_reset_context); int kvm_mmu_load(struct kvm_vcpu *vcpu) { int r; r = mmu_topup_memory_caches(vcpu); if (r) goto out; r = mmu_alloc_roots(vcpu); kvm_mmu_sync_roots(vcpu); if (r) goto out; /* set_cr3() should ensure TLB has been flushed */ vcpu->arch.mmu.set_cr3(vcpu, vcpu->arch.mmu.root_hpa); out: return r; } EXPORT_SYMBOL_GPL(kvm_mmu_load); void kvm_mmu_unload(struct kvm_vcpu *vcpu) { mmu_free_roots(vcpu); } EXPORT_SYMBOL_GPL(kvm_mmu_unload); static void mmu_pte_write_new_pte(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp, u64 *spte, const void *new) { if (sp->role.level != PT_PAGE_TABLE_LEVEL) { ++vcpu->kvm->stat.mmu_pde_zapped; return; } ++vcpu->kvm->stat.mmu_pte_updated; vcpu->arch.mmu.update_pte(vcpu, sp, spte, new); } static bool need_remote_flush(u64 old, u64 new) { if (!is_shadow_present_pte(old)) return false; if (!is_shadow_present_pte(new)) return true; if ((old ^ new) & PT64_BASE_ADDR_MASK) return true; old ^= shadow_nx_mask; new ^= shadow_nx_mask; return (old & ~new & PT64_PERM_MASK) != 0; } static void mmu_pte_write_flush_tlb(struct kvm_vcpu *vcpu, bool zap_page, bool remote_flush, bool local_flush) { if (zap_page) return; if (remote_flush) kvm_flush_remote_tlbs(vcpu->kvm); else if (local_flush) kvm_mmu_flush_tlb(vcpu); } static u64 mmu_pte_write_fetch_gpte(struct kvm_vcpu *vcpu, gpa_t *gpa, const u8 *new, int *bytes) { u64 gentry; int r; /* * Assume that the pte write on a page table of the same type * as the current vcpu paging mode since we update the sptes only * when they have the same mode. */ if (is_pae(vcpu) && *bytes == 4) { /* Handle a 32-bit guest writing two halves of a 64-bit gpte */ *gpa &= ~(gpa_t)7; *bytes = 8; r = kvm_read_guest(vcpu->kvm, *gpa, &gentry, 8); if (r) gentry = 0; new = (const u8 *)&gentry; } switch (*bytes) { case 4: gentry = *(const u32 *)new; break; case 8: gentry = *(const u64 *)new; break; default: gentry = 0; break; } return gentry; } /* * If we're seeing too many writes to a page, it may no longer be a page table, * or we may be forking, in which case it is better to unmap the page. */ static bool detect_write_flooding(struct kvm_mmu_page *sp) { /* * Skip write-flooding detected for the sp whose level is 1, because * it can become unsync, then the guest page is not write-protected. */ if (sp->role.level == PT_PAGE_TABLE_LEVEL) return false; return ++sp->write_flooding_count >= 3; } /* * Misaligned accesses are too much trouble to fix up; also, they usually * indicate a page is not used as a page table. */ static bool detect_write_misaligned(struct kvm_mmu_page *sp, gpa_t gpa, int bytes) { unsigned offset, pte_size, misaligned; pgprintk("misaligned: gpa %llx bytes %d role %x\n", gpa, bytes, sp->role.word); offset = offset_in_page(gpa); pte_size = sp->role.cr4_pae ? 8 : 4; /* * Sometimes, the OS only writes the last one bytes to update status * bits, for example, in linux, andb instruction is used in clear_bit(). */ if (!(offset & (pte_size - 1)) && bytes == 1) return false; misaligned = (offset ^ (offset + bytes - 1)) & ~(pte_size - 1); misaligned |= bytes < 4; return misaligned; } static u64 *get_written_sptes(struct kvm_mmu_page *sp, gpa_t gpa, int *nspte) { unsigned page_offset, quadrant; u64 *spte; int level; page_offset = offset_in_page(gpa); level = sp->role.level; *nspte = 1; if (!sp->role.cr4_pae) { page_offset <<= 1; /* 32->64 */ /* * A 32-bit pde maps 4MB while the shadow pdes map * only 2MB. So we need to double the offset again * and zap two pdes instead of one. */ if (level == PT32_ROOT_LEVEL) { page_offset &= ~7; /* kill rounding error */ page_offset <<= 1; *nspte = 2; } quadrant = page_offset >> PAGE_SHIFT; page_offset &= ~PAGE_MASK; if (quadrant != sp->role.quadrant) return NULL; } spte = &sp->spt[page_offset / sizeof(*spte)]; return spte; } void kvm_mmu_pte_write(struct kvm_vcpu *vcpu, gpa_t gpa, const u8 *new, int bytes) { gfn_t gfn = gpa >> PAGE_SHIFT; union kvm_mmu_page_role mask = { .word = 0 }; struct kvm_mmu_page *sp; LIST_HEAD(invalid_list); u64 entry, gentry, *spte; int npte; bool remote_flush, local_flush, zap_page; /* * If we don't have indirect shadow pages, it means no page is * write-protected, so we can exit simply. */ if (!ACCESS_ONCE(vcpu->kvm->arch.indirect_shadow_pages)) return; zap_page = remote_flush = local_flush = false; pgprintk("%s: gpa %llx bytes %d\n", __func__, gpa, bytes); gentry = mmu_pte_write_fetch_gpte(vcpu, &gpa, new, &bytes); /* * No need to care whether allocation memory is successful * or not since pte prefetch is skiped if it does not have * enough objects in the cache. */ mmu_topup_memory_caches(vcpu); spin_lock(&vcpu->kvm->mmu_lock); ++vcpu->kvm->stat.mmu_pte_write; kvm_mmu_audit(vcpu, AUDIT_PRE_PTE_WRITE); mask.cr0_wp = mask.cr4_pae = mask.nxe = 1; for_each_gfn_indirect_valid_sp(vcpu->kvm, sp, gfn) { if (detect_write_misaligned(sp, gpa, bytes) || detect_write_flooding(sp)) { zap_page |= !!kvm_mmu_prepare_zap_page(vcpu->kvm, sp, &invalid_list); ++vcpu->kvm->stat.mmu_flooded; continue; } spte = get_written_sptes(sp, gpa, &npte); if (!spte) continue; local_flush = true; while (npte--) { entry = *spte; mmu_page_zap_pte(vcpu->kvm, sp, spte); if (gentry && !((sp->role.word ^ vcpu->arch.mmu.base_role.word) & mask.word) && rmap_can_add(vcpu)) mmu_pte_write_new_pte(vcpu, sp, spte, &gentry); if (need_remote_flush(entry, *spte)) remote_flush = true; ++spte; } } mmu_pte_write_flush_tlb(vcpu, zap_page, remote_flush, local_flush); kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list); kvm_mmu_audit(vcpu, AUDIT_POST_PTE_WRITE); spin_unlock(&vcpu->kvm->mmu_lock); } int kvm_mmu_unprotect_page_virt(struct kvm_vcpu *vcpu, gva_t gva) { gpa_t gpa; int r; if (vcpu->arch.mmu.direct_map) return 0; gpa = kvm_mmu_gva_to_gpa_read(vcpu, gva, NULL); r = kvm_mmu_unprotect_page(vcpu->kvm, gpa >> PAGE_SHIFT); return r; } EXPORT_SYMBOL_GPL(kvm_mmu_unprotect_page_virt); static void make_mmu_pages_available(struct kvm_vcpu *vcpu) { LIST_HEAD(invalid_list); if (likely(kvm_mmu_available_pages(vcpu->kvm) >= KVM_MIN_FREE_MMU_PAGES)) return; while (kvm_mmu_available_pages(vcpu->kvm) < KVM_REFILL_PAGES) { if (!prepare_zap_oldest_mmu_page(vcpu->kvm, &invalid_list)) break; ++vcpu->kvm->stat.mmu_recycled; } kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list); } static bool is_mmio_page_fault(struct kvm_vcpu *vcpu, gva_t addr) { if (vcpu->arch.mmu.direct_map || mmu_is_nested(vcpu)) return vcpu_match_mmio_gpa(vcpu, addr); return vcpu_match_mmio_gva(vcpu, addr); } int kvm_mmu_page_fault(struct kvm_vcpu *vcpu, gva_t cr2, u32 error_code, void *insn, int insn_len) { int r, emulation_type = EMULTYPE_RETRY; enum emulation_result er; r = vcpu->arch.mmu.page_fault(vcpu, cr2, error_code, false); if (r < 0) goto out; if (!r) { r = 1; goto out; } if (is_mmio_page_fault(vcpu, cr2)) emulation_type = 0; er = x86_emulate_instruction(vcpu, cr2, emulation_type, insn, insn_len); switch (er) { case EMULATE_DONE: return 1; case EMULATE_USER_EXIT: ++vcpu->stat.mmio_exits; /* fall through */ case EMULATE_FAIL: return 0; default: BUG(); } out: return r; } EXPORT_SYMBOL_GPL(kvm_mmu_page_fault); void kvm_mmu_invlpg(struct kvm_vcpu *vcpu, gva_t gva) { vcpu->arch.mmu.invlpg(vcpu, gva); kvm_mmu_flush_tlb(vcpu); ++vcpu->stat.invlpg; } EXPORT_SYMBOL_GPL(kvm_mmu_invlpg); void kvm_enable_tdp(void) { tdp_enabled = true; } EXPORT_SYMBOL_GPL(kvm_enable_tdp); void kvm_disable_tdp(void) { tdp_enabled = false; } EXPORT_SYMBOL_GPL(kvm_disable_tdp); static void free_mmu_pages(struct kvm_vcpu *vcpu) { free_page((unsigned long)vcpu->arch.mmu.pae_root); if (vcpu->arch.mmu.lm_root != NULL) free_page((unsigned long)vcpu->arch.mmu.lm_root); } static int alloc_mmu_pages(struct kvm_vcpu *vcpu) { struct page *page; int i; ASSERT(vcpu); /* * When emulating 32-bit mode, cr3 is only 32 bits even on x86_64. * Therefore we need to allocate shadow page tables in the first * 4GB of memory, which happens to fit the DMA32 zone. */ page = alloc_page(GFP_KERNEL | __GFP_DMA32); if (!page) return -ENOMEM; vcpu->arch.mmu.pae_root = page_address(page); for (i = 0; i < 4; ++i) vcpu->arch.mmu.pae_root[i] = INVALID_PAGE; return 0; } int kvm_mmu_create(struct kvm_vcpu *vcpu) { ASSERT(vcpu); vcpu->arch.walk_mmu = &vcpu->arch.mmu; vcpu->arch.mmu.root_hpa = INVALID_PAGE; vcpu->arch.mmu.translate_gpa = translate_gpa; vcpu->arch.nested_mmu.translate_gpa = translate_nested_gpa; return alloc_mmu_pages(vcpu); } int kvm_mmu_setup(struct kvm_vcpu *vcpu) { ASSERT(vcpu); ASSERT(!VALID_PAGE(vcpu->arch.mmu.root_hpa)); return init_kvm_mmu(vcpu); } void kvm_mmu_slot_remove_write_access(struct kvm *kvm, int slot) { struct kvm_memory_slot *memslot; gfn_t last_gfn; int i; memslot = id_to_memslot(kvm->memslots, slot); last_gfn = memslot->base_gfn + memslot->npages - 1; spin_lock(&kvm->mmu_lock); for (i = PT_PAGE_TABLE_LEVEL; i < PT_PAGE_TABLE_LEVEL + KVM_NR_PAGE_SIZES; ++i) { unsigned long *rmapp; unsigned long last_index, index; rmapp = memslot->arch.rmap[i - PT_PAGE_TABLE_LEVEL]; last_index = gfn_to_index(last_gfn, memslot->base_gfn, i); for (index = 0; index <= last_index; ++index, ++rmapp) { if (*rmapp) __rmap_write_protect(kvm, rmapp, false); if (need_resched() || spin_needbreak(&kvm->mmu_lock)) { kvm_flush_remote_tlbs(kvm); cond_resched_lock(&kvm->mmu_lock); } } } kvm_flush_remote_tlbs(kvm); spin_unlock(&kvm->mmu_lock); } #define BATCH_ZAP_PAGES 10 static void kvm_zap_obsolete_pages(struct kvm *kvm) { struct kvm_mmu_page *sp, *node; int batch = 0; restart: list_for_each_entry_safe_reverse(sp, node, &kvm->arch.active_mmu_pages, link) { int ret; /* * No obsolete page exists before new created page since * active_mmu_pages is the FIFO list. */ if (!is_obsolete_sp(kvm, sp)) break; /* * Since we are reversely walking the list and the invalid * list will be moved to the head, skip the invalid page * can help us to avoid the infinity list walking. */ if (sp->role.invalid) continue; /* * Need not flush tlb since we only zap the sp with invalid * generation number. */ if (batch >= BATCH_ZAP_PAGES && cond_resched_lock(&kvm->mmu_lock)) { batch = 0; goto restart; } ret = kvm_mmu_prepare_zap_page(kvm, sp, &kvm->arch.zapped_obsolete_pages); batch += ret; if (ret) goto restart; } /* * Should flush tlb before free page tables since lockless-walking * may use the pages. */ kvm_mmu_commit_zap_page(kvm, &kvm->arch.zapped_obsolete_pages); } /* * Fast invalidate all shadow pages and use lock-break technique * to zap obsolete pages. * * It's required when memslot is being deleted or VM is being * destroyed, in these cases, we should ensure that KVM MMU does * not use any resource of the being-deleted slot or all slots * after calling the function. */ void kvm_mmu_invalidate_zap_all_pages(struct kvm *kvm) { spin_lock(&kvm->mmu_lock); trace_kvm_mmu_invalidate_zap_all_pages(kvm); kvm->arch.mmu_valid_gen++; /* * Notify all vcpus to reload its shadow page table * and flush TLB. Then all vcpus will switch to new * shadow page table with the new mmu_valid_gen. * * Note: we should do this under the protection of * mmu-lock, otherwise, vcpu would purge shadow page * but miss tlb flush. */ kvm_reload_remote_mmus(kvm); kvm_zap_obsolete_pages(kvm); spin_unlock(&kvm->mmu_lock); } static bool kvm_has_zapped_obsolete_pages(struct kvm *kvm) { return unlikely(!list_empty_careful(&kvm->arch.zapped_obsolete_pages)); } void kvm_mmu_invalidate_mmio_sptes(struct kvm *kvm) { /* * The very rare case: if the generation-number is round, * zap all shadow pages. */ if (unlikely(kvm_current_mmio_generation(kvm) >= MMIO_MAX_GEN)) { printk_ratelimited(KERN_INFO "kvm: zapping shadow pages for mmio generation wraparound\n"); kvm_mmu_invalidate_zap_all_pages(kvm); } } static int mmu_shrink(struct shrinker *shrink, struct shrink_control *sc) { struct kvm *kvm; int nr_to_scan = sc->nr_to_scan; if (nr_to_scan == 0) goto out; raw_spin_lock(&kvm_lock); list_for_each_entry(kvm, &vm_list, vm_list) { int idx; LIST_HEAD(invalid_list); /* * Never scan more than sc->nr_to_scan VM instances. * Will not hit this condition practically since we do not try * to shrink more than one VM and it is very unlikely to see * !n_used_mmu_pages so many times. */ if (!nr_to_scan--) break; /* * n_used_mmu_pages is accessed without holding kvm->mmu_lock * here. We may skip a VM instance errorneosly, but we do not * want to shrink a VM that only started to populate its MMU * anyway. */ if (!kvm->arch.n_used_mmu_pages && !kvm_has_zapped_obsolete_pages(kvm)) continue; idx = srcu_read_lock(&kvm->srcu); spin_lock(&kvm->mmu_lock); if (kvm_has_zapped_obsolete_pages(kvm)) { kvm_mmu_commit_zap_page(kvm, &kvm->arch.zapped_obsolete_pages); goto unlock; } prepare_zap_oldest_mmu_page(kvm, &invalid_list); kvm_mmu_commit_zap_page(kvm, &invalid_list); unlock: spin_unlock(&kvm->mmu_lock); srcu_read_unlock(&kvm->srcu, idx); list_move_tail(&kvm->vm_list, &vm_list); break; } raw_spin_unlock(&kvm_lock); out: return percpu_counter_read_positive(&kvm_total_used_mmu_pages); } static struct shrinker mmu_shrinker = { .shrink = mmu_shrink, .seeks = DEFAULT_SEEKS * 10, }; static void mmu_destroy_caches(void) { if (pte_list_desc_cache) kmem_cache_destroy(pte_list_desc_cache); if (mmu_page_header_cache) kmem_cache_destroy(mmu_page_header_cache); } int kvm_mmu_module_init(void) { pte_list_desc_cache = kmem_cache_create("pte_list_desc", sizeof(struct pte_list_desc), 0, 0, NULL); if (!pte_list_desc_cache) goto nomem; mmu_page_header_cache = kmem_cache_create("kvm_mmu_page_header", sizeof(struct kvm_mmu_page), 0, 0, NULL); if (!mmu_page_header_cache) goto nomem; if (percpu_counter_init(&kvm_total_used_mmu_pages, 0)) goto nomem; register_shrinker(&mmu_shrinker); return 0; nomem: mmu_destroy_caches(); return -ENOMEM; } /* * Caculate mmu pages needed for kvm. */ unsigned int kvm_mmu_calculate_mmu_pages(struct kvm *kvm) { unsigned int nr_mmu_pages; unsigned int nr_pages = 0; struct kvm_memslots *slots; struct kvm_memory_slot *memslot; slots = kvm_memslots(kvm); kvm_for_each_memslot(memslot, slots) nr_pages += memslot->npages; nr_mmu_pages = nr_pages * KVM_PERMILLE_MMU_PAGES / 1000; nr_mmu_pages = max(nr_mmu_pages, (unsigned int) KVM_MIN_ALLOC_MMU_PAGES); return nr_mmu_pages; } int kvm_mmu_get_spte_hierarchy(struct kvm_vcpu *vcpu, u64 addr, u64 sptes[4]) { struct kvm_shadow_walk_iterator iterator; u64 spte; int nr_sptes = 0; walk_shadow_page_lockless_begin(vcpu); for_each_shadow_entry_lockless(vcpu, addr, iterator, spte) { sptes[iterator.level-1] = spte; nr_sptes++; if (!is_shadow_present_pte(spte)) break; } walk_shadow_page_lockless_end(vcpu); return nr_sptes; } EXPORT_SYMBOL_GPL(kvm_mmu_get_spte_hierarchy); void kvm_mmu_destroy(struct kvm_vcpu *vcpu) { ASSERT(vcpu); destroy_kvm_mmu(vcpu); free_mmu_pages(vcpu); mmu_free_memory_caches(vcpu); } void kvm_mmu_module_exit(void) { mmu_destroy_caches(); percpu_counter_destroy(&kvm_total_used_mmu_pages); unregister_shrinker(&mmu_shrinker); mmu_audit_disable(); }
./CrossVul/dataset_final_sorted/CWE-20/c/bad_2162_2
crossvul-cpp_data_good_1718_0
/* $OpenBSD: monitor.c,v 1.150 2015/06/22 23:42:16 djm Exp $ */ /* * Copyright 2002 Niels Provos <provos@citi.umich.edu> * Copyright 2002 Markus Friedl <markus@openbsd.org> * 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 ``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 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 "includes.h" #include <sys/types.h> #include <sys/socket.h> #include "openbsd-compat/sys-tree.h" #include <sys/wait.h> #include <errno.h> #include <fcntl.h> #ifdef HAVE_PATHS_H #include <paths.h> #endif #include <pwd.h> #include <signal.h> #ifdef HAVE_STDINT_H #include <stdint.h> #endif #include <stdlib.h> #include <string.h> #include <stdarg.h> #include <stdio.h> #include <unistd.h> #ifdef HAVE_POLL_H #include <poll.h> #else # ifdef HAVE_SYS_POLL_H # include <sys/poll.h> # endif #endif #ifdef SKEY #include <skey.h> #endif #ifdef WITH_OPENSSL #include <openssl/dh.h> #endif #include "openbsd-compat/sys-queue.h" #include "atomicio.h" #include "xmalloc.h" #include "ssh.h" #include "key.h" #include "buffer.h" #include "hostfile.h" #include "auth.h" #include "cipher.h" #include "kex.h" #include "dh.h" #ifdef TARGET_OS_MAC /* XXX Broken krb5 headers on Mac */ #undef TARGET_OS_MAC #include "zlib.h" #define TARGET_OS_MAC 1 #else #include "zlib.h" #endif #include "packet.h" #include "auth-options.h" #include "sshpty.h" #include "channels.h" #include "session.h" #include "sshlogin.h" #include "canohost.h" #include "log.h" #include "misc.h" #include "servconf.h" #include "monitor.h" #include "monitor_mm.h" #ifdef GSSAPI #include "ssh-gss.h" #endif #include "monitor_wrap.h" #include "monitor_fdpass.h" #include "compat.h" #include "ssh2.h" #include "roaming.h" #include "authfd.h" #include "match.h" #include "ssherr.h" #ifdef GSSAPI static Gssctxt *gsscontext = NULL; #endif /* Imports */ extern ServerOptions options; extern u_int utmp_len; extern u_char session_id[]; extern Buffer auth_debug; extern int auth_debug_init; extern Buffer loginmsg; /* State exported from the child */ static struct sshbuf *child_state; /* Functions on the monitor that answer unprivileged requests */ int mm_answer_moduli(int, Buffer *); int mm_answer_sign(int, Buffer *); int mm_answer_pwnamallow(int, Buffer *); int mm_answer_auth2_read_banner(int, Buffer *); int mm_answer_authserv(int, Buffer *); int mm_answer_authpassword(int, Buffer *); int mm_answer_bsdauthquery(int, Buffer *); int mm_answer_bsdauthrespond(int, Buffer *); int mm_answer_skeyquery(int, Buffer *); int mm_answer_skeyrespond(int, Buffer *); int mm_answer_keyallowed(int, Buffer *); int mm_answer_keyverify(int, Buffer *); int mm_answer_pty(int, Buffer *); int mm_answer_pty_cleanup(int, Buffer *); int mm_answer_term(int, Buffer *); int mm_answer_rsa_keyallowed(int, Buffer *); int mm_answer_rsa_challenge(int, Buffer *); int mm_answer_rsa_response(int, Buffer *); int mm_answer_sesskey(int, Buffer *); int mm_answer_sessid(int, Buffer *); #ifdef USE_PAM int mm_answer_pam_start(int, Buffer *); int mm_answer_pam_account(int, Buffer *); int mm_answer_pam_init_ctx(int, Buffer *); int mm_answer_pam_query(int, Buffer *); int mm_answer_pam_respond(int, Buffer *); int mm_answer_pam_free_ctx(int, Buffer *); #endif #ifdef GSSAPI int mm_answer_gss_setup_ctx(int, Buffer *); int mm_answer_gss_accept_ctx(int, Buffer *); int mm_answer_gss_userok(int, Buffer *); int mm_answer_gss_checkmic(int, Buffer *); #endif #ifdef SSH_AUDIT_EVENTS int mm_answer_audit_event(int, Buffer *); int mm_answer_audit_command(int, Buffer *); #endif static int monitor_read_log(struct monitor *); static Authctxt *authctxt; #ifdef WITH_SSH1 static BIGNUM *ssh1_challenge = NULL; /* used for ssh1 rsa auth */ #endif /* local state for key verify */ static u_char *key_blob = NULL; static u_int key_bloblen = 0; static int key_blobtype = MM_NOKEY; static char *hostbased_cuser = NULL; static char *hostbased_chost = NULL; static char *auth_method = "unknown"; static char *auth_submethod = NULL; static u_int session_id2_len = 0; static u_char *session_id2 = NULL; static pid_t monitor_child_pid; struct mon_table { enum monitor_reqtype type; int flags; int (*f)(int, Buffer *); }; #define MON_ISAUTH 0x0004 /* Required for Authentication */ #define MON_AUTHDECIDE 0x0008 /* Decides Authentication */ #define MON_ONCE 0x0010 /* Disable after calling */ #define MON_ALOG 0x0020 /* Log auth attempt without authenticating */ #define MON_AUTH (MON_ISAUTH|MON_AUTHDECIDE) #define MON_PERMIT 0x1000 /* Request is permitted */ struct mon_table mon_dispatch_proto20[] = { #ifdef WITH_OPENSSL {MONITOR_REQ_MODULI, MON_ONCE, mm_answer_moduli}, #endif {MONITOR_REQ_SIGN, MON_ONCE, mm_answer_sign}, {MONITOR_REQ_PWNAM, MON_ONCE, mm_answer_pwnamallow}, {MONITOR_REQ_AUTHSERV, MON_ONCE, mm_answer_authserv}, {MONITOR_REQ_AUTH2_READ_BANNER, MON_ONCE, mm_answer_auth2_read_banner}, {MONITOR_REQ_AUTHPASSWORD, MON_AUTH, mm_answer_authpassword}, #ifdef USE_PAM {MONITOR_REQ_PAM_START, MON_ONCE, mm_answer_pam_start}, {MONITOR_REQ_PAM_ACCOUNT, 0, mm_answer_pam_account}, {MONITOR_REQ_PAM_INIT_CTX, MON_ISAUTH, mm_answer_pam_init_ctx}, {MONITOR_REQ_PAM_QUERY, MON_ISAUTH, mm_answer_pam_query}, {MONITOR_REQ_PAM_RESPOND, MON_ISAUTH, mm_answer_pam_respond}, {MONITOR_REQ_PAM_FREE_CTX, MON_ONCE|MON_AUTHDECIDE, mm_answer_pam_free_ctx}, #endif #ifdef SSH_AUDIT_EVENTS {MONITOR_REQ_AUDIT_EVENT, MON_PERMIT, mm_answer_audit_event}, #endif #ifdef BSD_AUTH {MONITOR_REQ_BSDAUTHQUERY, MON_ISAUTH, mm_answer_bsdauthquery}, {MONITOR_REQ_BSDAUTHRESPOND, MON_AUTH, mm_answer_bsdauthrespond}, #endif #ifdef SKEY {MONITOR_REQ_SKEYQUERY, MON_ISAUTH, mm_answer_skeyquery}, {MONITOR_REQ_SKEYRESPOND, MON_AUTH, mm_answer_skeyrespond}, #endif {MONITOR_REQ_KEYALLOWED, MON_ISAUTH, mm_answer_keyallowed}, {MONITOR_REQ_KEYVERIFY, MON_AUTH, mm_answer_keyverify}, #ifdef GSSAPI {MONITOR_REQ_GSSSETUP, MON_ISAUTH, mm_answer_gss_setup_ctx}, {MONITOR_REQ_GSSSTEP, MON_ISAUTH, mm_answer_gss_accept_ctx}, {MONITOR_REQ_GSSUSEROK, MON_AUTH, mm_answer_gss_userok}, {MONITOR_REQ_GSSCHECKMIC, MON_ISAUTH, mm_answer_gss_checkmic}, #endif {0, 0, NULL} }; struct mon_table mon_dispatch_postauth20[] = { #ifdef WITH_OPENSSL {MONITOR_REQ_MODULI, 0, mm_answer_moduli}, #endif {MONITOR_REQ_SIGN, 0, mm_answer_sign}, {MONITOR_REQ_PTY, 0, mm_answer_pty}, {MONITOR_REQ_PTYCLEANUP, 0, mm_answer_pty_cleanup}, {MONITOR_REQ_TERM, 0, mm_answer_term}, #ifdef SSH_AUDIT_EVENTS {MONITOR_REQ_AUDIT_EVENT, MON_PERMIT, mm_answer_audit_event}, {MONITOR_REQ_AUDIT_COMMAND, MON_PERMIT, mm_answer_audit_command}, #endif {0, 0, NULL} }; struct mon_table mon_dispatch_proto15[] = { #ifdef WITH_SSH1 {MONITOR_REQ_PWNAM, MON_ONCE, mm_answer_pwnamallow}, {MONITOR_REQ_SESSKEY, MON_ONCE, mm_answer_sesskey}, {MONITOR_REQ_SESSID, MON_ONCE, mm_answer_sessid}, {MONITOR_REQ_AUTHPASSWORD, MON_AUTH, mm_answer_authpassword}, {MONITOR_REQ_RSAKEYALLOWED, MON_ISAUTH|MON_ALOG, mm_answer_rsa_keyallowed}, {MONITOR_REQ_KEYALLOWED, MON_ISAUTH|MON_ALOG, mm_answer_keyallowed}, {MONITOR_REQ_RSACHALLENGE, MON_ONCE, mm_answer_rsa_challenge}, {MONITOR_REQ_RSARESPONSE, MON_ONCE|MON_AUTHDECIDE, mm_answer_rsa_response}, #ifdef BSD_AUTH {MONITOR_REQ_BSDAUTHQUERY, MON_ISAUTH, mm_answer_bsdauthquery}, {MONITOR_REQ_BSDAUTHRESPOND, MON_AUTH, mm_answer_bsdauthrespond}, #endif #ifdef SKEY {MONITOR_REQ_SKEYQUERY, MON_ISAUTH, mm_answer_skeyquery}, {MONITOR_REQ_SKEYRESPOND, MON_AUTH, mm_answer_skeyrespond}, #endif #ifdef USE_PAM {MONITOR_REQ_PAM_START, MON_ONCE, mm_answer_pam_start}, {MONITOR_REQ_PAM_ACCOUNT, 0, mm_answer_pam_account}, {MONITOR_REQ_PAM_INIT_CTX, MON_ISAUTH, mm_answer_pam_init_ctx}, {MONITOR_REQ_PAM_QUERY, MON_ISAUTH, mm_answer_pam_query}, {MONITOR_REQ_PAM_RESPOND, MON_ISAUTH, mm_answer_pam_respond}, {MONITOR_REQ_PAM_FREE_CTX, MON_ONCE|MON_AUTHDECIDE, mm_answer_pam_free_ctx}, #endif #ifdef SSH_AUDIT_EVENTS {MONITOR_REQ_AUDIT_EVENT, MON_PERMIT, mm_answer_audit_event}, #endif #endif /* WITH_SSH1 */ {0, 0, NULL} }; struct mon_table mon_dispatch_postauth15[] = { #ifdef WITH_SSH1 {MONITOR_REQ_PTY, MON_ONCE, mm_answer_pty}, {MONITOR_REQ_PTYCLEANUP, MON_ONCE, mm_answer_pty_cleanup}, {MONITOR_REQ_TERM, 0, mm_answer_term}, #ifdef SSH_AUDIT_EVENTS {MONITOR_REQ_AUDIT_EVENT, MON_PERMIT, mm_answer_audit_event}, {MONITOR_REQ_AUDIT_COMMAND, MON_PERMIT|MON_ONCE, mm_answer_audit_command}, #endif #endif /* WITH_SSH1 */ {0, 0, NULL} }; struct mon_table *mon_dispatch; /* Specifies if a certain message is allowed at the moment */ static void monitor_permit(struct mon_table *ent, enum monitor_reqtype type, int permit) { while (ent->f != NULL) { if (ent->type == type) { ent->flags &= ~MON_PERMIT; ent->flags |= permit ? MON_PERMIT : 0; return; } ent++; } } static void monitor_permit_authentications(int permit) { struct mon_table *ent = mon_dispatch; while (ent->f != NULL) { if (ent->flags & MON_AUTH) { ent->flags &= ~MON_PERMIT; ent->flags |= permit ? MON_PERMIT : 0; } ent++; } } void monitor_child_preauth(Authctxt *_authctxt, struct monitor *pmonitor) { struct mon_table *ent; int authenticated = 0, partial = 0; debug3("preauth child monitor started"); close(pmonitor->m_recvfd); close(pmonitor->m_log_sendfd); pmonitor->m_log_sendfd = pmonitor->m_recvfd = -1; authctxt = _authctxt; memset(authctxt, 0, sizeof(*authctxt)); authctxt->loginmsg = &loginmsg; if (compat20) { mon_dispatch = mon_dispatch_proto20; /* Permit requests for moduli and signatures */ monitor_permit(mon_dispatch, MONITOR_REQ_MODULI, 1); monitor_permit(mon_dispatch, MONITOR_REQ_SIGN, 1); } else { mon_dispatch = mon_dispatch_proto15; monitor_permit(mon_dispatch, MONITOR_REQ_SESSKEY, 1); } /* The first few requests do not require asynchronous access */ while (!authenticated) { partial = 0; auth_method = "unknown"; auth_submethod = NULL; authenticated = (monitor_read(pmonitor, mon_dispatch, &ent) == 1); /* Special handling for multiple required authentications */ if (options.num_auth_methods != 0) { if (!compat20) fatal("AuthenticationMethods is not supported" "with SSH protocol 1"); if (authenticated && !auth2_update_methods_lists(authctxt, auth_method, auth_submethod)) { debug3("%s: method %s: partial", __func__, auth_method); authenticated = 0; partial = 1; } } if (authenticated) { if (!(ent->flags & MON_AUTHDECIDE)) fatal("%s: unexpected authentication from %d", __func__, ent->type); if (authctxt->pw->pw_uid == 0 && !auth_root_allowed(auth_method)) authenticated = 0; #ifdef USE_PAM /* PAM needs to perform account checks after auth */ if (options.use_pam && authenticated) { Buffer m; buffer_init(&m); mm_request_receive_expect(pmonitor->m_sendfd, MONITOR_REQ_PAM_ACCOUNT, &m); authenticated = mm_answer_pam_account(pmonitor->m_sendfd, &m); buffer_free(&m); } #endif } if (ent->flags & (MON_AUTHDECIDE|MON_ALOG)) { auth_log(authctxt, authenticated, partial, auth_method, auth_submethod); if (!partial && !authenticated) authctxt->failures++; } } if (!authctxt->valid) fatal("%s: authenticated invalid user", __func__); if (strcmp(auth_method, "unknown") == 0) fatal("%s: authentication method name unknown", __func__); debug("%s: %s has been authenticated by privileged process", __func__, authctxt->user); mm_get_keystate(pmonitor); /* Drain any buffered messages from the child */ while (pmonitor->m_log_recvfd != -1 && monitor_read_log(pmonitor) == 0) ; close(pmonitor->m_sendfd); close(pmonitor->m_log_recvfd); pmonitor->m_sendfd = pmonitor->m_log_recvfd = -1; } static void monitor_set_child_handler(pid_t pid) { monitor_child_pid = pid; } static void monitor_child_handler(int sig) { kill(monitor_child_pid, sig); } void monitor_child_postauth(struct monitor *pmonitor) { close(pmonitor->m_recvfd); pmonitor->m_recvfd = -1; monitor_set_child_handler(pmonitor->m_pid); signal(SIGHUP, &monitor_child_handler); signal(SIGTERM, &monitor_child_handler); signal(SIGINT, &monitor_child_handler); #ifdef SIGXFSZ signal(SIGXFSZ, SIG_IGN); #endif if (compat20) { mon_dispatch = mon_dispatch_postauth20; /* Permit requests for moduli and signatures */ monitor_permit(mon_dispatch, MONITOR_REQ_MODULI, 1); monitor_permit(mon_dispatch, MONITOR_REQ_SIGN, 1); monitor_permit(mon_dispatch, MONITOR_REQ_TERM, 1); } else { mon_dispatch = mon_dispatch_postauth15; monitor_permit(mon_dispatch, MONITOR_REQ_TERM, 1); } if (!no_pty_flag) { monitor_permit(mon_dispatch, MONITOR_REQ_PTY, 1); monitor_permit(mon_dispatch, MONITOR_REQ_PTYCLEANUP, 1); } for (;;) monitor_read(pmonitor, mon_dispatch, NULL); } void monitor_sync(struct monitor *pmonitor) { if (options.compression) { /* The member allocation is not visible, so sync it */ mm_share_sync(&pmonitor->m_zlib, &pmonitor->m_zback); } } /* Allocation functions for zlib */ static void * mm_zalloc(struct mm_master *mm, u_int ncount, u_int size) { size_t len = (size_t) size * ncount; void *address; if (len == 0 || ncount > SIZE_MAX / size) fatal("%s: mm_zalloc(%u, %u)", __func__, ncount, size); address = mm_malloc(mm, len); return (address); } static void mm_zfree(struct mm_master *mm, void *address) { mm_free(mm, address); } static int monitor_read_log(struct monitor *pmonitor) { Buffer logmsg; u_int len, level; char *msg; buffer_init(&logmsg); /* Read length */ buffer_append_space(&logmsg, 4); if (atomicio(read, pmonitor->m_log_recvfd, buffer_ptr(&logmsg), buffer_len(&logmsg)) != buffer_len(&logmsg)) { if (errno == EPIPE) { buffer_free(&logmsg); debug("%s: child log fd closed", __func__); close(pmonitor->m_log_recvfd); pmonitor->m_log_recvfd = -1; return -1; } fatal("%s: log fd read: %s", __func__, strerror(errno)); } len = buffer_get_int(&logmsg); if (len <= 4 || len > 8192) fatal("%s: invalid log message length %u", __func__, len); /* Read severity, message */ buffer_clear(&logmsg); buffer_append_space(&logmsg, len); if (atomicio(read, pmonitor->m_log_recvfd, buffer_ptr(&logmsg), buffer_len(&logmsg)) != buffer_len(&logmsg)) fatal("%s: log fd read: %s", __func__, strerror(errno)); /* Log it */ level = buffer_get_int(&logmsg); msg = buffer_get_string(&logmsg, NULL); if (log_level_name(level) == NULL) fatal("%s: invalid log level %u (corrupted message?)", __func__, level); do_log2(level, "%s [preauth]", msg); buffer_free(&logmsg); free(msg); return 0; } int monitor_read(struct monitor *pmonitor, struct mon_table *ent, struct mon_table **pent) { Buffer m; int ret; u_char type; struct pollfd pfd[2]; for (;;) { memset(&pfd, 0, sizeof(pfd)); pfd[0].fd = pmonitor->m_sendfd; pfd[0].events = POLLIN; pfd[1].fd = pmonitor->m_log_recvfd; pfd[1].events = pfd[1].fd == -1 ? 0 : POLLIN; if (poll(pfd, pfd[1].fd == -1 ? 1 : 2, -1) == -1) { if (errno == EINTR || errno == EAGAIN) continue; fatal("%s: poll: %s", __func__, strerror(errno)); } if (pfd[1].revents) { /* * Drain all log messages before processing next * monitor request. */ monitor_read_log(pmonitor); continue; } if (pfd[0].revents) break; /* Continues below */ } buffer_init(&m); mm_request_receive(pmonitor->m_sendfd, &m); type = buffer_get_char(&m); debug3("%s: checking request %d", __func__, type); while (ent->f != NULL) { if (ent->type == type) break; ent++; } if (ent->f != NULL) { if (!(ent->flags & MON_PERMIT)) fatal("%s: unpermitted request %d", __func__, type); ret = (*ent->f)(pmonitor->m_sendfd, &m); buffer_free(&m); /* The child may use this request only once, disable it */ if (ent->flags & MON_ONCE) { debug2("%s: %d used once, disabling now", __func__, type); ent->flags &= ~MON_PERMIT; } if (pent != NULL) *pent = ent; return ret; } fatal("%s: unsupported request: %d", __func__, type); /* NOTREACHED */ return (-1); } /* allowed key state */ static int monitor_allowed_key(u_char *blob, u_int bloblen) { /* make sure key is allowed */ if (key_blob == NULL || key_bloblen != bloblen || timingsafe_bcmp(key_blob, blob, key_bloblen)) return (0); return (1); } static void monitor_reset_key_state(void) { /* reset state */ free(key_blob); free(hostbased_cuser); free(hostbased_chost); key_blob = NULL; key_bloblen = 0; key_blobtype = MM_NOKEY; hostbased_cuser = NULL; hostbased_chost = NULL; } #ifdef WITH_OPENSSL int mm_answer_moduli(int sock, Buffer *m) { DH *dh; int min, want, max; min = buffer_get_int(m); want = buffer_get_int(m); max = buffer_get_int(m); debug3("%s: got parameters: %d %d %d", __func__, min, want, max); /* We need to check here, too, in case the child got corrupted */ if (max < min || want < min || max < want) fatal("%s: bad parameters: %d %d %d", __func__, min, want, max); buffer_clear(m); dh = choose_dh(min, want, max); if (dh == NULL) { buffer_put_char(m, 0); return (0); } else { /* Send first bignum */ buffer_put_char(m, 1); buffer_put_bignum2(m, dh->p); buffer_put_bignum2(m, dh->g); DH_free(dh); } mm_request_send(sock, MONITOR_ANS_MODULI, m); return (0); } #endif int mm_answer_sign(int sock, Buffer *m) { struct ssh *ssh = active_state; /* XXX */ extern int auth_sock; /* XXX move to state struct? */ struct sshkey *key; struct sshbuf *sigbuf; u_char *p; u_char *signature; size_t datlen, siglen; int r, keyid, is_proof = 0; const char proof_req[] = "hostkeys-prove-00@openssh.com"; debug3("%s", __func__); if ((r = sshbuf_get_u32(m, &keyid)) != 0 || (r = sshbuf_get_string(m, &p, &datlen)) != 0) fatal("%s: buffer error: %s", __func__, ssh_err(r)); /* * Supported KEX types use SHA1 (20 bytes), SHA256 (32 bytes), * SHA384 (48 bytes) and SHA512 (64 bytes). * * Otherwise, verify the signature request is for a hostkey * proof. * * XXX perform similar check for KEX signature requests too? * it's not trivial, since what is signed is the hash, rather * than the full kex structure... */ if (datlen != 20 && datlen != 32 && datlen != 48 && datlen != 64) { /* * Construct expected hostkey proof and compare it to what * the client sent us. */ if (session_id2_len == 0) /* hostkeys is never first */ fatal("%s: bad data length: %zu", __func__, datlen); if ((key = get_hostkey_public_by_index(keyid, ssh)) == NULL) fatal("%s: no hostkey for index %d", __func__, keyid); if ((sigbuf = sshbuf_new()) == NULL) fatal("%s: sshbuf_new", __func__); if ((r = sshbuf_put_cstring(sigbuf, proof_req)) != 0 || (r = sshbuf_put_string(sigbuf, session_id2, session_id2_len) != 0) || (r = sshkey_puts(key, sigbuf)) != 0) fatal("%s: couldn't prepare private key " "proof buffer: %s", __func__, ssh_err(r)); if (datlen != sshbuf_len(sigbuf) || memcmp(p, sshbuf_ptr(sigbuf), sshbuf_len(sigbuf)) != 0) fatal("%s: bad data length: %zu, hostkey proof len %zu", __func__, datlen, sshbuf_len(sigbuf)); sshbuf_free(sigbuf); is_proof = 1; } /* save session id, it will be passed on the first call */ if (session_id2_len == 0) { session_id2_len = datlen; session_id2 = xmalloc(session_id2_len); memcpy(session_id2, p, session_id2_len); } if ((key = get_hostkey_by_index(keyid)) != NULL) { if ((r = sshkey_sign(key, &signature, &siglen, p, datlen, datafellows)) != 0) fatal("%s: sshkey_sign failed: %s", __func__, ssh_err(r)); } else if ((key = get_hostkey_public_by_index(keyid, ssh)) != NULL && auth_sock > 0) { if ((r = ssh_agent_sign(auth_sock, key, &signature, &siglen, p, datlen, datafellows)) != 0) { fatal("%s: ssh_agent_sign failed: %s", __func__, ssh_err(r)); } } else fatal("%s: no hostkey from index %d", __func__, keyid); debug3("%s: %s signature %p(%zu)", __func__, is_proof ? "KEX" : "hostkey proof", signature, siglen); sshbuf_reset(m); if ((r = sshbuf_put_string(m, signature, siglen)) != 0) fatal("%s: buffer error: %s", __func__, ssh_err(r)); free(p); free(signature); mm_request_send(sock, MONITOR_ANS_SIGN, m); /* Turn on permissions for getpwnam */ monitor_permit(mon_dispatch, MONITOR_REQ_PWNAM, 1); return (0); } /* Retrieves the password entry and also checks if the user is permitted */ int mm_answer_pwnamallow(int sock, Buffer *m) { char *username; struct passwd *pwent; int allowed = 0; u_int i; debug3("%s", __func__); if (authctxt->attempt++ != 0) fatal("%s: multiple attempts for getpwnam", __func__); username = buffer_get_string(m, NULL); pwent = getpwnamallow(username); authctxt->user = xstrdup(username); setproctitle("%s [priv]", pwent ? username : "unknown"); free(username); buffer_clear(m); if (pwent == NULL) { buffer_put_char(m, 0); authctxt->pw = fakepw(); goto out; } allowed = 1; authctxt->pw = pwent; authctxt->valid = 1; buffer_put_char(m, 1); buffer_put_string(m, pwent, sizeof(struct passwd)); buffer_put_cstring(m, pwent->pw_name); buffer_put_cstring(m, "*"); #ifdef HAVE_STRUCT_PASSWD_PW_GECOS buffer_put_cstring(m, pwent->pw_gecos); #endif #ifdef HAVE_STRUCT_PASSWD_PW_CLASS buffer_put_cstring(m, pwent->pw_class); #endif buffer_put_cstring(m, pwent->pw_dir); buffer_put_cstring(m, pwent->pw_shell); out: buffer_put_string(m, &options, sizeof(options)); #define M_CP_STROPT(x) do { \ if (options.x != NULL) \ buffer_put_cstring(m, options.x); \ } while (0) #define M_CP_STRARRAYOPT(x, nx) do { \ for (i = 0; i < options.nx; i++) \ buffer_put_cstring(m, options.x[i]); \ } while (0) /* See comment in servconf.h */ COPY_MATCH_STRING_OPTS(); #undef M_CP_STROPT #undef M_CP_STRARRAYOPT /* Create valid auth method lists */ if (compat20 && auth2_setup_methods_lists(authctxt) != 0) { /* * The monitor will continue long enough to let the child * run to it's packet_disconnect(), but it must not allow any * authentication to succeed. */ debug("%s: no valid authentication method lists", __func__); } debug3("%s: sending MONITOR_ANS_PWNAM: %d", __func__, allowed); mm_request_send(sock, MONITOR_ANS_PWNAM, m); /* For SSHv1 allow authentication now */ if (!compat20) monitor_permit_authentications(1); else { /* Allow service/style information on the auth context */ monitor_permit(mon_dispatch, MONITOR_REQ_AUTHSERV, 1); monitor_permit(mon_dispatch, MONITOR_REQ_AUTH2_READ_BANNER, 1); } #ifdef USE_PAM if (options.use_pam) monitor_permit(mon_dispatch, MONITOR_REQ_PAM_START, 1); #endif return (0); } int mm_answer_auth2_read_banner(int sock, Buffer *m) { char *banner; buffer_clear(m); banner = auth2_read_banner(); buffer_put_cstring(m, banner != NULL ? banner : ""); mm_request_send(sock, MONITOR_ANS_AUTH2_READ_BANNER, m); free(banner); return (0); } int mm_answer_authserv(int sock, Buffer *m) { monitor_permit_authentications(1); authctxt->service = buffer_get_string(m, NULL); authctxt->style = buffer_get_string(m, NULL); debug3("%s: service=%s, style=%s", __func__, authctxt->service, authctxt->style); if (strlen(authctxt->style) == 0) { free(authctxt->style); authctxt->style = NULL; } return (0); } int mm_answer_authpassword(int sock, Buffer *m) { static int call_count; char *passwd; int authenticated; u_int plen; passwd = buffer_get_string(m, &plen); /* Only authenticate if the context is valid */ authenticated = options.password_authentication && auth_password(authctxt, passwd); explicit_bzero(passwd, strlen(passwd)); free(passwd); buffer_clear(m); buffer_put_int(m, authenticated); debug3("%s: sending result %d", __func__, authenticated); mm_request_send(sock, MONITOR_ANS_AUTHPASSWORD, m); call_count++; if (plen == 0 && call_count == 1) auth_method = "none"; else auth_method = "password"; /* Causes monitor loop to terminate if authenticated */ return (authenticated); } #ifdef BSD_AUTH int mm_answer_bsdauthquery(int sock, Buffer *m) { char *name, *infotxt; u_int numprompts; u_int *echo_on; char **prompts; u_int success; success = bsdauth_query(authctxt, &name, &infotxt, &numprompts, &prompts, &echo_on) < 0 ? 0 : 1; buffer_clear(m); buffer_put_int(m, success); if (success) buffer_put_cstring(m, prompts[0]); debug3("%s: sending challenge success: %u", __func__, success); mm_request_send(sock, MONITOR_ANS_BSDAUTHQUERY, m); if (success) { free(name); free(infotxt); free(prompts); free(echo_on); } return (0); } int mm_answer_bsdauthrespond(int sock, Buffer *m) { char *response; int authok; if (authctxt->as == 0) fatal("%s: no bsd auth session", __func__); response = buffer_get_string(m, NULL); authok = options.challenge_response_authentication && auth_userresponse(authctxt->as, response, 0); authctxt->as = NULL; debug3("%s: <%s> = <%d>", __func__, response, authok); free(response); buffer_clear(m); buffer_put_int(m, authok); debug3("%s: sending authenticated: %d", __func__, authok); mm_request_send(sock, MONITOR_ANS_BSDAUTHRESPOND, m); if (compat20) { auth_method = "keyboard-interactive"; auth_submethod = "bsdauth"; } else auth_method = "bsdauth"; return (authok != 0); } #endif #ifdef SKEY int mm_answer_skeyquery(int sock, Buffer *m) { struct skey skey; char challenge[1024]; u_int success; success = _compat_skeychallenge(&skey, authctxt->user, challenge, sizeof(challenge)) < 0 ? 0 : 1; buffer_clear(m); buffer_put_int(m, success); if (success) buffer_put_cstring(m, challenge); debug3("%s: sending challenge success: %u", __func__, success); mm_request_send(sock, MONITOR_ANS_SKEYQUERY, m); return (0); } int mm_answer_skeyrespond(int sock, Buffer *m) { char *response; int authok; response = buffer_get_string(m, NULL); authok = (options.challenge_response_authentication && authctxt->valid && skey_haskey(authctxt->pw->pw_name) == 0 && skey_passcheck(authctxt->pw->pw_name, response) != -1); free(response); buffer_clear(m); buffer_put_int(m, authok); debug3("%s: sending authenticated: %d", __func__, authok); mm_request_send(sock, MONITOR_ANS_SKEYRESPOND, m); auth_method = "skey"; return (authok != 0); } #endif #ifdef USE_PAM int mm_answer_pam_start(int sock, Buffer *m) { if (!options.use_pam) fatal("UsePAM not set, but ended up in %s anyway", __func__); start_pam(authctxt); monitor_permit(mon_dispatch, MONITOR_REQ_PAM_ACCOUNT, 1); return (0); } int mm_answer_pam_account(int sock, Buffer *m) { u_int ret; if (!options.use_pam) fatal("UsePAM not set, but ended up in %s anyway", __func__); ret = do_pam_account(); buffer_put_int(m, ret); buffer_put_string(m, buffer_ptr(&loginmsg), buffer_len(&loginmsg)); mm_request_send(sock, MONITOR_ANS_PAM_ACCOUNT, m); return (ret); } static void *sshpam_ctxt, *sshpam_authok; extern KbdintDevice sshpam_device; int mm_answer_pam_init_ctx(int sock, Buffer *m) { debug3("%s", __func__); sshpam_ctxt = (sshpam_device.init_ctx)(authctxt); sshpam_authok = NULL; buffer_clear(m); if (sshpam_ctxt != NULL) { monitor_permit(mon_dispatch, MONITOR_REQ_PAM_FREE_CTX, 1); buffer_put_int(m, 1); } else { buffer_put_int(m, 0); } mm_request_send(sock, MONITOR_ANS_PAM_INIT_CTX, m); return (0); } int mm_answer_pam_query(int sock, Buffer *m) { char *name = NULL, *info = NULL, **prompts = NULL; u_int i, num = 0, *echo_on = 0; int ret; debug3("%s", __func__); sshpam_authok = NULL; ret = (sshpam_device.query)(sshpam_ctxt, &name, &info, &num, &prompts, &echo_on); if (ret == 0 && num == 0) sshpam_authok = sshpam_ctxt; if (num > 1 || name == NULL || info == NULL) ret = -1; buffer_clear(m); buffer_put_int(m, ret); buffer_put_cstring(m, name); free(name); buffer_put_cstring(m, info); free(info); buffer_put_int(m, num); for (i = 0; i < num; ++i) { buffer_put_cstring(m, prompts[i]); free(prompts[i]); buffer_put_int(m, echo_on[i]); } free(prompts); free(echo_on); auth_method = "keyboard-interactive"; auth_submethod = "pam"; mm_request_send(sock, MONITOR_ANS_PAM_QUERY, m); return (0); } int mm_answer_pam_respond(int sock, Buffer *m) { char **resp; u_int i, num; int ret; debug3("%s", __func__); sshpam_authok = NULL; num = buffer_get_int(m); if (num > 0) { resp = xcalloc(num, sizeof(char *)); for (i = 0; i < num; ++i) resp[i] = buffer_get_string(m, NULL); ret = (sshpam_device.respond)(sshpam_ctxt, num, resp); for (i = 0; i < num; ++i) free(resp[i]); free(resp); } else { ret = (sshpam_device.respond)(sshpam_ctxt, num, NULL); } buffer_clear(m); buffer_put_int(m, ret); mm_request_send(sock, MONITOR_ANS_PAM_RESPOND, m); auth_method = "keyboard-interactive"; auth_submethod = "pam"; if (ret == 0) sshpam_authok = sshpam_ctxt; return (0); } int mm_answer_pam_free_ctx(int sock, Buffer *m) { debug3("%s", __func__); (sshpam_device.free_ctx)(sshpam_ctxt); buffer_clear(m); mm_request_send(sock, MONITOR_ANS_PAM_FREE_CTX, m); auth_method = "keyboard-interactive"; auth_submethod = "pam"; return (sshpam_authok == sshpam_ctxt); } #endif int mm_answer_keyallowed(int sock, Buffer *m) { Key *key; char *cuser, *chost; u_char *blob; u_int bloblen, pubkey_auth_attempt; enum mm_keytype type = 0; int allowed = 0; debug3("%s entering", __func__); type = buffer_get_int(m); cuser = buffer_get_string(m, NULL); chost = buffer_get_string(m, NULL); blob = buffer_get_string(m, &bloblen); pubkey_auth_attempt = buffer_get_int(m); key = key_from_blob(blob, bloblen); if ((compat20 && type == MM_RSAHOSTKEY) || (!compat20 && type != MM_RSAHOSTKEY)) fatal("%s: key type and protocol mismatch", __func__); debug3("%s: key_from_blob: %p", __func__, key); if (key != NULL && authctxt->valid) { /* These should not make it past the privsep child */ if (key_type_plain(key->type) == KEY_RSA && (datafellows & SSH_BUG_RSASIGMD5) != 0) fatal("%s: passed a SSH_BUG_RSASIGMD5 key", __func__); switch (type) { case MM_USERKEY: allowed = options.pubkey_authentication && !auth2_userkey_already_used(authctxt, key) && match_pattern_list(sshkey_ssh_name(key), options.pubkey_key_types, 0) == 1 && user_key_allowed(authctxt->pw, key, pubkey_auth_attempt); pubkey_auth_info(authctxt, key, NULL); auth_method = "publickey"; if (options.pubkey_authentication && (!pubkey_auth_attempt || allowed != 1)) auth_clear_options(); break; case MM_HOSTKEY: allowed = options.hostbased_authentication && match_pattern_list(sshkey_ssh_name(key), options.hostbased_key_types, 0) == 1 && hostbased_key_allowed(authctxt->pw, cuser, chost, key); pubkey_auth_info(authctxt, key, "client user \"%.100s\", client host \"%.100s\"", cuser, chost); auth_method = "hostbased"; break; #ifdef WITH_SSH1 case MM_RSAHOSTKEY: key->type = KEY_RSA1; /* XXX */ allowed = options.rhosts_rsa_authentication && auth_rhosts_rsa_key_allowed(authctxt->pw, cuser, chost, key); if (options.rhosts_rsa_authentication && allowed != 1) auth_clear_options(); auth_method = "rsa"; break; #endif default: fatal("%s: unknown key type %d", __func__, type); break; } } if (key != NULL) key_free(key); /* clear temporarily storage (used by verify) */ monitor_reset_key_state(); if (allowed) { /* Save temporarily for comparison in verify */ key_blob = blob; key_bloblen = bloblen; key_blobtype = type; hostbased_cuser = cuser; hostbased_chost = chost; } else { /* Log failed attempt */ auth_log(authctxt, 0, 0, auth_method, NULL); free(blob); free(cuser); free(chost); } debug3("%s: key %p is %s", __func__, key, allowed ? "allowed" : "not allowed"); buffer_clear(m); buffer_put_int(m, allowed); buffer_put_int(m, forced_command != NULL); mm_request_send(sock, MONITOR_ANS_KEYALLOWED, m); if (type == MM_RSAHOSTKEY) monitor_permit(mon_dispatch, MONITOR_REQ_RSACHALLENGE, allowed); return (0); } static int monitor_valid_userblob(u_char *data, u_int datalen) { Buffer b; char *p, *userstyle; u_int len; int fail = 0; buffer_init(&b); buffer_append(&b, data, datalen); if (datafellows & SSH_OLD_SESSIONID) { p = buffer_ptr(&b); len = buffer_len(&b); if ((session_id2 == NULL) || (len < session_id2_len) || (timingsafe_bcmp(p, session_id2, session_id2_len) != 0)) fail++; buffer_consume(&b, session_id2_len); } else { p = buffer_get_string(&b, &len); if ((session_id2 == NULL) || (len != session_id2_len) || (timingsafe_bcmp(p, session_id2, session_id2_len) != 0)) fail++; free(p); } if (buffer_get_char(&b) != SSH2_MSG_USERAUTH_REQUEST) fail++; p = buffer_get_cstring(&b, NULL); xasprintf(&userstyle, "%s%s%s", authctxt->user, authctxt->style ? ":" : "", authctxt->style ? authctxt->style : ""); if (strcmp(userstyle, p) != 0) { logit("wrong user name passed to monitor: expected %s != %.100s", userstyle, p); fail++; } free(userstyle); free(p); buffer_skip_string(&b); if (datafellows & SSH_BUG_PKAUTH) { if (!buffer_get_char(&b)) fail++; } else { p = buffer_get_cstring(&b, NULL); if (strcmp("publickey", p) != 0) fail++; free(p); if (!buffer_get_char(&b)) fail++; buffer_skip_string(&b); } buffer_skip_string(&b); if (buffer_len(&b) != 0) fail++; buffer_free(&b); return (fail == 0); } static int monitor_valid_hostbasedblob(u_char *data, u_int datalen, char *cuser, char *chost) { Buffer b; char *p, *userstyle; u_int len; int fail = 0; buffer_init(&b); buffer_append(&b, data, datalen); p = buffer_get_string(&b, &len); if ((session_id2 == NULL) || (len != session_id2_len) || (timingsafe_bcmp(p, session_id2, session_id2_len) != 0)) fail++; free(p); if (buffer_get_char(&b) != SSH2_MSG_USERAUTH_REQUEST) fail++; p = buffer_get_cstring(&b, NULL); xasprintf(&userstyle, "%s%s%s", authctxt->user, authctxt->style ? ":" : "", authctxt->style ? authctxt->style : ""); if (strcmp(userstyle, p) != 0) { logit("wrong user name passed to monitor: expected %s != %.100s", userstyle, p); fail++; } free(userstyle); free(p); buffer_skip_string(&b); /* service */ p = buffer_get_cstring(&b, NULL); if (strcmp(p, "hostbased") != 0) fail++; free(p); buffer_skip_string(&b); /* pkalg */ buffer_skip_string(&b); /* pkblob */ /* verify client host, strip trailing dot if necessary */ p = buffer_get_string(&b, NULL); if (((len = strlen(p)) > 0) && p[len - 1] == '.') p[len - 1] = '\0'; if (strcmp(p, chost) != 0) fail++; free(p); /* verify client user */ p = buffer_get_string(&b, NULL); if (strcmp(p, cuser) != 0) fail++; free(p); if (buffer_len(&b) != 0) fail++; buffer_free(&b); return (fail == 0); } int mm_answer_keyverify(int sock, Buffer *m) { Key *key; u_char *signature, *data, *blob; u_int signaturelen, datalen, bloblen; int verified = 0; int valid_data = 0; blob = buffer_get_string(m, &bloblen); signature = buffer_get_string(m, &signaturelen); data = buffer_get_string(m, &datalen); if (hostbased_cuser == NULL || hostbased_chost == NULL || !monitor_allowed_key(blob, bloblen)) fatal("%s: bad key, not previously allowed", __func__); key = key_from_blob(blob, bloblen); if (key == NULL) fatal("%s: bad public key blob", __func__); switch (key_blobtype) { case MM_USERKEY: valid_data = monitor_valid_userblob(data, datalen); break; case MM_HOSTKEY: valid_data = monitor_valid_hostbasedblob(data, datalen, hostbased_cuser, hostbased_chost); break; default: valid_data = 0; break; } if (!valid_data) fatal("%s: bad signature data blob", __func__); verified = key_verify(key, signature, signaturelen, data, datalen); debug3("%s: key %p signature %s", __func__, key, (verified == 1) ? "verified" : "unverified"); /* If auth was successful then record key to ensure it isn't reused */ if (verified == 1) auth2_record_userkey(authctxt, key); else key_free(key); free(blob); free(signature); free(data); auth_method = key_blobtype == MM_USERKEY ? "publickey" : "hostbased"; monitor_reset_key_state(); buffer_clear(m); buffer_put_int(m, verified); mm_request_send(sock, MONITOR_ANS_KEYVERIFY, m); return (verified == 1); } static void mm_record_login(Session *s, struct passwd *pw) { socklen_t fromlen; struct sockaddr_storage from; if (options.use_login) return; /* * Get IP address of client. If the connection is not a socket, let * the address be 0.0.0.0. */ memset(&from, 0, sizeof(from)); fromlen = sizeof(from); if (packet_connection_is_on_socket()) { if (getpeername(packet_get_connection_in(), (struct sockaddr *)&from, &fromlen) < 0) { debug("getpeername: %.100s", strerror(errno)); cleanup_exit(255); } } /* Record that there was a login on that tty from the remote host. */ record_login(s->pid, s->tty, pw->pw_name, pw->pw_uid, get_remote_name_or_ip(utmp_len, options.use_dns), (struct sockaddr *)&from, fromlen); } static void mm_session_close(Session *s) { debug3("%s: session %d pid %ld", __func__, s->self, (long)s->pid); if (s->ttyfd != -1) { debug3("%s: tty %s ptyfd %d", __func__, s->tty, s->ptyfd); session_pty_cleanup2(s); } session_unused(s->self); } int mm_answer_pty(int sock, Buffer *m) { extern struct monitor *pmonitor; Session *s; int res, fd0; debug3("%s entering", __func__); buffer_clear(m); s = session_new(); if (s == NULL) goto error; s->authctxt = authctxt; s->pw = authctxt->pw; s->pid = pmonitor->m_pid; res = pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty)); if (res == 0) goto error; pty_setowner(authctxt->pw, s->tty); buffer_put_int(m, 1); buffer_put_cstring(m, s->tty); /* We need to trick ttyslot */ if (dup2(s->ttyfd, 0) == -1) fatal("%s: dup2", __func__); mm_record_login(s, authctxt->pw); /* Now we can close the file descriptor again */ close(0); /* send messages generated by record_login */ buffer_put_string(m, buffer_ptr(&loginmsg), buffer_len(&loginmsg)); buffer_clear(&loginmsg); mm_request_send(sock, MONITOR_ANS_PTY, m); if (mm_send_fd(sock, s->ptyfd) == -1 || mm_send_fd(sock, s->ttyfd) == -1) fatal("%s: send fds failed", __func__); /* make sure nothing uses fd 0 */ if ((fd0 = open(_PATH_DEVNULL, O_RDONLY)) < 0) fatal("%s: open(/dev/null): %s", __func__, strerror(errno)); if (fd0 != 0) error("%s: fd0 %d != 0", __func__, fd0); /* slave is not needed */ close(s->ttyfd); s->ttyfd = s->ptyfd; /* no need to dup() because nobody closes ptyfd */ s->ptymaster = s->ptyfd; debug3("%s: tty %s ptyfd %d", __func__, s->tty, s->ttyfd); return (0); error: if (s != NULL) mm_session_close(s); buffer_put_int(m, 0); mm_request_send(sock, MONITOR_ANS_PTY, m); return (0); } int mm_answer_pty_cleanup(int sock, Buffer *m) { Session *s; char *tty; debug3("%s entering", __func__); tty = buffer_get_string(m, NULL); if ((s = session_by_tty(tty)) != NULL) mm_session_close(s); buffer_clear(m); free(tty); return (0); } #ifdef WITH_SSH1 int mm_answer_sesskey(int sock, Buffer *m) { BIGNUM *p; int rsafail; /* Turn off permissions */ monitor_permit(mon_dispatch, MONITOR_REQ_SESSKEY, 0); if ((p = BN_new()) == NULL) fatal("%s: BN_new", __func__); buffer_get_bignum2(m, p); rsafail = ssh1_session_key(p); buffer_clear(m); buffer_put_int(m, rsafail); buffer_put_bignum2(m, p); BN_clear_free(p); mm_request_send(sock, MONITOR_ANS_SESSKEY, m); /* Turn on permissions for sessid passing */ monitor_permit(mon_dispatch, MONITOR_REQ_SESSID, 1); return (0); } int mm_answer_sessid(int sock, Buffer *m) { int i; debug3("%s entering", __func__); if (buffer_len(m) != 16) fatal("%s: bad ssh1 session id", __func__); for (i = 0; i < 16; i++) session_id[i] = buffer_get_char(m); /* Turn on permissions for getpwnam */ monitor_permit(mon_dispatch, MONITOR_REQ_PWNAM, 1); return (0); } int mm_answer_rsa_keyallowed(int sock, Buffer *m) { BIGNUM *client_n; Key *key = NULL; u_char *blob = NULL; u_int blen = 0; int allowed = 0; debug3("%s entering", __func__); auth_method = "rsa"; if (options.rsa_authentication && authctxt->valid) { if ((client_n = BN_new()) == NULL) fatal("%s: BN_new", __func__); buffer_get_bignum2(m, client_n); allowed = auth_rsa_key_allowed(authctxt->pw, client_n, &key); BN_clear_free(client_n); } buffer_clear(m); buffer_put_int(m, allowed); buffer_put_int(m, forced_command != NULL); /* clear temporarily storage (used by generate challenge) */ monitor_reset_key_state(); if (allowed && key != NULL) { key->type = KEY_RSA; /* cheat for key_to_blob */ if (key_to_blob(key, &blob, &blen) == 0) fatal("%s: key_to_blob failed", __func__); buffer_put_string(m, blob, blen); /* Save temporarily for comparison in verify */ key_blob = blob; key_bloblen = blen; key_blobtype = MM_RSAUSERKEY; } if (key != NULL) key_free(key); mm_request_send(sock, MONITOR_ANS_RSAKEYALLOWED, m); monitor_permit(mon_dispatch, MONITOR_REQ_RSACHALLENGE, allowed); monitor_permit(mon_dispatch, MONITOR_REQ_RSARESPONSE, 0); return (0); } int mm_answer_rsa_challenge(int sock, Buffer *m) { Key *key = NULL; u_char *blob; u_int blen; debug3("%s entering", __func__); if (!authctxt->valid) fatal("%s: authctxt not valid", __func__); blob = buffer_get_string(m, &blen); if (!monitor_allowed_key(blob, blen)) fatal("%s: bad key, not previously allowed", __func__); if (key_blobtype != MM_RSAUSERKEY && key_blobtype != MM_RSAHOSTKEY) fatal("%s: key type mismatch", __func__); if ((key = key_from_blob(blob, blen)) == NULL) fatal("%s: received bad key", __func__); if (key->type != KEY_RSA) fatal("%s: received bad key type %d", __func__, key->type); key->type = KEY_RSA1; if (ssh1_challenge) BN_clear_free(ssh1_challenge); ssh1_challenge = auth_rsa_generate_challenge(key); buffer_clear(m); buffer_put_bignum2(m, ssh1_challenge); debug3("%s sending reply", __func__); mm_request_send(sock, MONITOR_ANS_RSACHALLENGE, m); monitor_permit(mon_dispatch, MONITOR_REQ_RSARESPONSE, 1); free(blob); key_free(key); return (0); } int mm_answer_rsa_response(int sock, Buffer *m) { Key *key = NULL; u_char *blob, *response; u_int blen, len; int success; debug3("%s entering", __func__); if (!authctxt->valid) fatal("%s: authctxt not valid", __func__); if (ssh1_challenge == NULL) fatal("%s: no ssh1_challenge", __func__); blob = buffer_get_string(m, &blen); if (!monitor_allowed_key(blob, blen)) fatal("%s: bad key, not previously allowed", __func__); if (key_blobtype != MM_RSAUSERKEY && key_blobtype != MM_RSAHOSTKEY) fatal("%s: key type mismatch: %d", __func__, key_blobtype); if ((key = key_from_blob(blob, blen)) == NULL) fatal("%s: received bad key", __func__); response = buffer_get_string(m, &len); if (len != 16) fatal("%s: received bad response to challenge", __func__); success = auth_rsa_verify_response(key, ssh1_challenge, response); free(blob); key_free(key); free(response); auth_method = key_blobtype == MM_RSAUSERKEY ? "rsa" : "rhosts-rsa"; /* reset state */ BN_clear_free(ssh1_challenge); ssh1_challenge = NULL; monitor_reset_key_state(); buffer_clear(m); buffer_put_int(m, success); mm_request_send(sock, MONITOR_ANS_RSARESPONSE, m); return (success); } #endif int mm_answer_term(int sock, Buffer *req) { extern struct monitor *pmonitor; int res, status; debug3("%s: tearing down sessions", __func__); /* The child is terminating */ session_destroy_all(&mm_session_close); #ifdef USE_PAM if (options.use_pam) sshpam_cleanup(); #endif while (waitpid(pmonitor->m_pid, &status, 0) == -1) if (errno != EINTR) exit(1); res = WIFEXITED(status) ? WEXITSTATUS(status) : 1; /* Terminate process */ exit(res); } #ifdef SSH_AUDIT_EVENTS /* Report that an audit event occurred */ int mm_answer_audit_event(int socket, Buffer *m) { ssh_audit_event_t event; debug3("%s entering", __func__); event = buffer_get_int(m); switch(event) { case SSH_AUTH_FAIL_PUBKEY: case SSH_AUTH_FAIL_HOSTBASED: case SSH_AUTH_FAIL_GSSAPI: case SSH_LOGIN_EXCEED_MAXTRIES: case SSH_LOGIN_ROOT_DENIED: case SSH_CONNECTION_CLOSE: case SSH_INVALID_USER: audit_event(event); break; default: fatal("Audit event type %d not permitted", event); } return (0); } int mm_answer_audit_command(int socket, Buffer *m) { u_int len; char *cmd; debug3("%s entering", __func__); cmd = buffer_get_string(m, &len); /* sanity check command, if so how? */ audit_run_command(cmd); free(cmd); return (0); } #endif /* SSH_AUDIT_EVENTS */ void monitor_apply_keystate(struct monitor *pmonitor) { struct ssh *ssh = active_state; /* XXX */ struct kex *kex; int r; debug3("%s: packet_set_state", __func__); if ((r = ssh_packet_set_state(ssh, child_state)) != 0) fatal("%s: packet_set_state: %s", __func__, ssh_err(r)); sshbuf_free(child_state); child_state = NULL; if ((kex = ssh->kex) != 0) { /* XXX set callbacks */ #ifdef WITH_OPENSSL kex->kex[KEX_DH_GRP1_SHA1] = kexdh_server; kex->kex[KEX_DH_GRP14_SHA1] = kexdh_server; kex->kex[KEX_DH_GEX_SHA1] = kexgex_server; kex->kex[KEX_DH_GEX_SHA256] = kexgex_server; # ifdef OPENSSL_HAS_ECC kex->kex[KEX_ECDH_SHA2] = kexecdh_server; # endif #endif /* WITH_OPENSSL */ kex->kex[KEX_C25519_SHA256] = kexc25519_server; kex->load_host_public_key=&get_hostkey_public_by_type; kex->load_host_private_key=&get_hostkey_private_by_type; kex->host_key_index=&get_hostkey_index; kex->sign = sshd_hostkey_sign; } /* Update with new address */ if (options.compression) { ssh_packet_set_compress_hooks(ssh, pmonitor->m_zlib, (ssh_packet_comp_alloc_func *)mm_zalloc, (ssh_packet_comp_free_func *)mm_zfree); } } /* This function requries careful sanity checking */ void mm_get_keystate(struct monitor *pmonitor) { debug3("%s: Waiting for new keys", __func__); if ((child_state = sshbuf_new()) == NULL) fatal("%s: sshbuf_new failed", __func__); mm_request_receive_expect(pmonitor->m_sendfd, MONITOR_REQ_KEYEXPORT, child_state); debug3("%s: GOT new keys", __func__); } /* XXX */ #define FD_CLOSEONEXEC(x) do { \ if (fcntl(x, F_SETFD, FD_CLOEXEC) == -1) \ fatal("fcntl(%d, F_SETFD)", x); \ } while (0) static void monitor_openfds(struct monitor *mon, int do_logfds) { int pair[2]; if (socketpair(AF_UNIX, SOCK_STREAM, 0, pair) == -1) fatal("%s: socketpair: %s", __func__, strerror(errno)); FD_CLOSEONEXEC(pair[0]); FD_CLOSEONEXEC(pair[1]); mon->m_recvfd = pair[0]; mon->m_sendfd = pair[1]; if (do_logfds) { if (pipe(pair) == -1) fatal("%s: pipe: %s", __func__, strerror(errno)); FD_CLOSEONEXEC(pair[0]); FD_CLOSEONEXEC(pair[1]); mon->m_log_recvfd = pair[0]; mon->m_log_sendfd = pair[1]; } else mon->m_log_recvfd = mon->m_log_sendfd = -1; } #define MM_MEMSIZE 65536 struct monitor * monitor_init(void) { struct ssh *ssh = active_state; /* XXX */ struct monitor *mon; mon = xcalloc(1, sizeof(*mon)); monitor_openfds(mon, 1); /* Used to share zlib space across processes */ if (options.compression) { mon->m_zback = mm_create(NULL, MM_MEMSIZE); mon->m_zlib = mm_create(mon->m_zback, 20 * MM_MEMSIZE); /* Compression needs to share state across borders */ ssh_packet_set_compress_hooks(ssh, mon->m_zlib, (ssh_packet_comp_alloc_func *)mm_zalloc, (ssh_packet_comp_free_func *)mm_zfree); } return mon; } void monitor_reinit(struct monitor *mon) { monitor_openfds(mon, 0); } #ifdef GSSAPI int mm_answer_gss_setup_ctx(int sock, Buffer *m) { gss_OID_desc goid; OM_uint32 major; u_int len; goid.elements = buffer_get_string(m, &len); goid.length = len; major = ssh_gssapi_server_ctx(&gsscontext, &goid); free(goid.elements); buffer_clear(m); buffer_put_int(m, major); mm_request_send(sock, MONITOR_ANS_GSSSETUP, m); /* Now we have a context, enable the step */ monitor_permit(mon_dispatch, MONITOR_REQ_GSSSTEP, 1); return (0); } int mm_answer_gss_accept_ctx(int sock, Buffer *m) { gss_buffer_desc in; gss_buffer_desc out = GSS_C_EMPTY_BUFFER; OM_uint32 major, minor; OM_uint32 flags = 0; /* GSI needs this */ u_int len; in.value = buffer_get_string(m, &len); in.length = len; major = ssh_gssapi_accept_ctx(gsscontext, &in, &out, &flags); free(in.value); buffer_clear(m); buffer_put_int(m, major); buffer_put_string(m, out.value, out.length); buffer_put_int(m, flags); mm_request_send(sock, MONITOR_ANS_GSSSTEP, m); gss_release_buffer(&minor, &out); if (major == GSS_S_COMPLETE) { monitor_permit(mon_dispatch, MONITOR_REQ_GSSSTEP, 0); monitor_permit(mon_dispatch, MONITOR_REQ_GSSUSEROK, 1); monitor_permit(mon_dispatch, MONITOR_REQ_GSSCHECKMIC, 1); } return (0); } int mm_answer_gss_checkmic(int sock, Buffer *m) { gss_buffer_desc gssbuf, mic; OM_uint32 ret; u_int len; gssbuf.value = buffer_get_string(m, &len); gssbuf.length = len; mic.value = buffer_get_string(m, &len); mic.length = len; ret = ssh_gssapi_checkmic(gsscontext, &gssbuf, &mic); free(gssbuf.value); free(mic.value); buffer_clear(m); buffer_put_int(m, ret); mm_request_send(sock, MONITOR_ANS_GSSCHECKMIC, m); if (!GSS_ERROR(ret)) monitor_permit(mon_dispatch, MONITOR_REQ_GSSUSEROK, 1); return (0); } int mm_answer_gss_userok(int sock, Buffer *m) { int authenticated; authenticated = authctxt->valid && ssh_gssapi_userok(authctxt->user); buffer_clear(m); buffer_put_int(m, authenticated); debug3("%s: sending result %d", __func__, authenticated); mm_request_send(sock, MONITOR_ANS_GSSUSEROK, m); auth_method = "gssapi-with-mic"; /* Monitor loop will terminate if authenticated */ return (authenticated); } #endif /* GSSAPI */
./CrossVul/dataset_final_sorted/CWE-20/c/good_1718_0
crossvul-cpp_data_good_1564_2
/* Copyright (C) 2009 RedHat inc. 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <sys/statvfs.h> #include "internal_libabrt.h" int low_free_space(unsigned setting_MaxCrashReportsSize, const char *dump_location) { struct statvfs vfs; if (statvfs(dump_location, &vfs) != 0) { perror_msg("statvfs('%s')", dump_location); return 0; } /* Check that at least MaxCrashReportsSize/4 MBs are free */ /* fs_free_mb_x4 ~= vfs.f_bfree * vfs.f_bsize * 4, expressed in MBytes. * Need to neither overflow nor round f_bfree down too much. */ unsigned long fs_free_mb_x4 = ((unsigned long long)vfs.f_bfree / (1024/4)) * vfs.f_bsize / 1024; if (fs_free_mb_x4 < setting_MaxCrashReportsSize) { error_msg("Only %luMiB is available on %s", fs_free_mb_x4 / 4, dump_location); return 1; } return 0; } /* rhbz#539551: "abrt going crazy when crashing process is respawned". * Check total size of problem dirs, if it overflows, * delete oldest/biggest dirs. */ void trim_problem_dirs(const char *dirname, double cap_size, const char *exclude_path) { const char *excluded_basename = NULL; if (exclude_path) { unsigned len_dirname = strlen(dirname); /* Trim trailing '/'s, but dont trim name "/" to "" */ while (len_dirname > 1 && dirname[len_dirname-1] == '/') len_dirname--; if (strncmp(dirname, exclude_path, len_dirname) == 0 && exclude_path[len_dirname] == '/' ) { /* exclude_path is "dirname/something" */ excluded_basename = exclude_path + len_dirname + 1; } } log_debug("excluded_basename:'%s'", excluded_basename); int count = 20; while (--count >= 0) { /* We exclude our own dir from candidates for deletion (3rd param): */ char *worst_basename = NULL; double cur_size = get_dirsize_find_largest_dir(dirname, &worst_basename, excluded_basename); if (cur_size <= cap_size || !worst_basename) { log_info("cur_size:%.0f cap_size:%.0f, no (more) trimming", cur_size, cap_size); free(worst_basename); break; } log("%s is %.0f bytes (more than %.0fMiB), deleting '%s'", dirname, cur_size, cap_size / (1024*1024), worst_basename); char *d = concat_path_file(dirname, worst_basename); free(worst_basename); delete_dump_dir(d); free(d); } } /** * * @param[out] status See `man 2 wait` for status information. * @return Malloc'ed string */ static char* exec_vp(char **args, int redirect_stderr, int exec_timeout_sec, int *status) { /* Nuke everything which may make setlocale() switch to non-POSIX locale: * we need to avoid having gdb output in some obscure language. */ static const char *const env_vec[] = { "LANG", "LC_ALL", "LC_COLLATE", "LC_CTYPE", "LC_MESSAGES", "LC_MONETARY", "LC_NUMERIC", "LC_TIME", /* Workaround for * http://sourceware.org/bugzilla/show_bug.cgi?id=9622 * (gdb emitting ESC sequences even with -batch) */ "TERM", NULL }; int flags = EXECFLG_INPUT_NUL | EXECFLG_OUTPUT | EXECFLG_SETSID | EXECFLG_QUIET; if (redirect_stderr) flags |= EXECFLG_ERR2OUT; VERB1 flags &= ~EXECFLG_QUIET; int pipeout[2]; pid_t child = fork_execv_on_steroids(flags, args, pipeout, (char**)env_vec, /*dir:*/ NULL, /*uid(unused):*/ 0); /* We use this function to run gdb and unstrip. Bugs in gdb or corrupted * coredumps were observed to cause gdb to enter infinite loop. * Therefore we have a (largish) timeout, after which we kill the child. */ ndelay_on(pipeout[0]); int t = time(NULL); /* int is enough, no need to use time_t */ int endtime = t + exec_timeout_sec; struct strbuf *buf_out = strbuf_new(); while (1) { int timeout = endtime - t; if (timeout < 0) { kill(child, SIGKILL); strbuf_append_strf(buf_out, "\n" "Timeout exceeded: %u seconds, killing %s.\n" "Looks like gdb hung while generating backtrace.\n" "This may be a bug in gdb. Consider submitting a bug report to gdb developers.\n" "Please attach coredump from this crash to the bug report if you do.\n", exec_timeout_sec, args[0] ); break; } /* We don't check poll result - checking read result is enough */ struct pollfd pfd; pfd.fd = pipeout[0]; pfd.events = POLLIN; poll(&pfd, 1, timeout * 1000); char buff[1024]; int r = read(pipeout[0], buff, sizeof(buff) - 1); if (r <= 0) { /* I did see EAGAIN happening here */ if (r < 0 && errno == EAGAIN) goto next; break; } buff[r] = '\0'; strbuf_append_str(buf_out, buff); next: t = time(NULL); } close(pipeout[0]); /* Prevent having zombie child process, and maybe collect status * (note that status == NULL is ok too) */ safe_waitpid(child, status, 0); return strbuf_free_nobuf(buf_out); } char *run_unstrip_n(const char *dump_dir_name, unsigned timeout_sec) { int flags = EXECFLG_INPUT_NUL | EXECFLG_OUTPUT | EXECFLG_SETSID | EXECFLG_QUIET; VERB1 flags &= ~EXECFLG_QUIET; int pipeout[2]; char* args[4]; args[0] = (char*)"eu-unstrip"; args[1] = xasprintf("--core=%s/"FILENAME_COREDUMP, dump_dir_name); args[2] = (char*)"-n"; args[3] = NULL; pid_t child = fork_execv_on_steroids(flags, args, pipeout, /*env_vec:*/ NULL, /*dir:*/ NULL, /*uid(unused):*/ 0); free(args[1]); /* Bugs in unstrip or corrupted coredumps can cause it to enter infinite loop. * Therefore we have a (largish) timeout, after which we kill the child. */ ndelay_on(pipeout[0]); int t = time(NULL); /* int is enough, no need to use time_t */ int endtime = t + timeout_sec; struct strbuf *buf_out = strbuf_new(); while (1) { int timeout = endtime - t; if (timeout < 0) { kill(child, SIGKILL); strbuf_free(buf_out); buf_out = NULL; break; } /* We don't check poll result - checking read result is enough */ struct pollfd pfd; pfd.fd = pipeout[0]; pfd.events = POLLIN; poll(&pfd, 1, timeout * 1000); char buff[1024]; int r = read(pipeout[0], buff, sizeof(buff) - 1); if (r <= 0) { /* I did see EAGAIN happening here */ if (r < 0 && errno == EAGAIN) goto next; break; } buff[r] = '\0'; strbuf_append_str(buf_out, buff); next: t = time(NULL); } close(pipeout[0]); /* Prevent having zombie child process */ int status; safe_waitpid(child, &status, 0); if (status != 0 || buf_out == NULL) { /* unstrip didnt exit with exit code 0, or we timed out */ strbuf_free(buf_out); return NULL; } return strbuf_free_nobuf(buf_out); } char *get_backtrace(const char *dump_dir_name, unsigned timeout_sec, const char *debuginfo_dirs) { INITIALIZE_LIBABRT(); struct dump_dir *dd = dd_opendir(dump_dir_name, /*flags:*/ 0); if (!dd) return NULL; char *executable = dd_load_text(dd, FILENAME_EXECUTABLE); dd_close(dd); /* Let user know what's going on */ log(_("Generating backtrace")); unsigned i = 0; char *args[25]; args[i++] = (char*)"gdb"; args[i++] = (char*)"-batch"; struct strbuf *set_debug_file_directory = strbuf_new(); unsigned auto_load_base_index = 0; if(debuginfo_dirs == NULL) { // set non-existent debug file directory to prevent resolving // function names - we need offsets for core backtrace. strbuf_append_str(set_debug_file_directory, "set debug-file-directory /"); } else { strbuf_append_str(set_debug_file_directory, "set debug-file-directory /usr/lib/debug"); struct strbuf *debug_directories = strbuf_new(); const char *p = debuginfo_dirs; while (1) { while (*p == ':') p++; if (*p == '\0') break; const char *colon_or_nul = strchrnul(p, ':'); strbuf_append_strf(debug_directories, "%s%.*s/usr/lib/debug", (debug_directories->len == 0 ? "" : ":"), (int)(colon_or_nul - p), p); p = colon_or_nul; } strbuf_append_strf(set_debug_file_directory, ":%s", debug_directories->buf); args[i++] = (char*)"-iex"; auto_load_base_index = i; args[i++] = xasprintf("add-auto-load-safe-path %s", debug_directories->buf); args[i++] = (char*)"-iex"; args[i++] = xasprintf("add-auto-load-scripts-directory %s", debug_directories->buf); strbuf_free(debug_directories); } args[i++] = (char*)"-ex"; const unsigned debug_dir_cmd_index = i++; args[debug_dir_cmd_index] = strbuf_free_nobuf(set_debug_file_directory); /* "file BINARY_FILE" is needed, without it gdb cannot properly * unwind the stack. Currently the unwind information is located * in .eh_frame which is stored only in binary, not in coredump * or debuginfo. * * Fedora GDB does not strictly need it, it will find the binary * by its build-id. But for binaries either without build-id * (= built on non-Fedora GCC) or which do not have * their debuginfo rpm installed gdb would not find BINARY_FILE * so it is still makes sense to supply "file BINARY_FILE". * * Unfortunately, "file BINARY_FILE" doesn't work well if BINARY_FILE * was deleted (as often happens during system updates): * gdb uses specified BINARY_FILE * even if it is completely unrelated to the coredump. * See https://bugzilla.redhat.com/show_bug.cgi?id=525721 * * TODO: check mtimes on COREFILE and BINARY_FILE and not supply * BINARY_FILE if it is newer (to at least avoid gdb complaining). */ args[i++] = (char*)"-ex"; const unsigned file_cmd_index = i++; args[file_cmd_index] = xasprintf("file %s", executable); free(executable); args[i++] = (char*)"-ex"; const unsigned core_cmd_index = i++; args[core_cmd_index] = xasprintf("core-file %s/"FILENAME_COREDUMP, dump_dir_name); args[i++] = (char*)"-ex"; const unsigned bt_cmd_index = i++; /*args[9] = ... see below */ args[i++] = (char*)"-ex"; args[i++] = (char*)"info sharedlib"; /* glibc's abort() stores its message in __abort_msg variable */ args[i++] = (char*)"-ex"; args[i++] = (char*)"print (char*)__abort_msg"; args[i++] = (char*)"-ex"; args[i++] = (char*)"print (char*)__glib_assert_msg"; args[i++] = (char*)"-ex"; args[i++] = (char*)"info all-registers"; args[i++] = (char*)"-ex"; const unsigned dis_cmd_index = i++; args[dis_cmd_index] = (char*)"disassemble"; args[i++] = NULL; /* Get the backtrace, but try to cap its size */ /* Limit bt depth. With no limit, gdb sometimes OOMs the machine */ unsigned bt_depth = 1024; const char *thread_apply_all = "thread apply all"; const char *full = " full"; char *bt = NULL; while (1) { args[bt_cmd_index] = xasprintf("%s backtrace %u%s", thread_apply_all, bt_depth, full); bt = exec_vp(args, /*redirect_stderr:*/ 1, timeout_sec, NULL); free(args[bt_cmd_index]); if ((bt && strnlen(bt, 256*1024) < 256*1024) || bt_depth <= 32) { break; } bt_depth /= 2; if (bt) log("Backtrace is too big (%u bytes), reducing depth to %u", (unsigned)strlen(bt), bt_depth); else /* (NB: in fact, current impl. of exec_vp() never returns NULL) */ log("Failed to generate backtrace, reducing depth to %u", bt_depth); free(bt); /* Replace -ex disassemble (which disasms entire function $pc points to) * to a version which analyzes limited, small patch of code around $pc. * (Users reported a case where bare "disassemble" attempted to process * entire .bss). * TODO: what if "$pc-N" underflows? in my test, this happens: * Dump of assembler code from 0xfffffffffffffff0 to 0x30: * End of assembler dump. * (IOW: "empty" dump) */ args[dis_cmd_index] = (char*)"disassemble $pc-20, $pc+64"; if (bt_depth <= 64 && thread_apply_all[0] != '\0') { /* This program likely has gazillion threads, dont try to bt them all */ bt_depth = 128; thread_apply_all = ""; } if (bt_depth <= 64 && full[0] != '\0') { /* Looks like there are gigantic local structures or arrays, disable "full" bt */ bt_depth = 128; full = ""; } } if (auto_load_base_index > 0) { free(args[auto_load_base_index]); free(args[auto_load_base_index + 2]); } free(args[debug_dir_cmd_index]); free(args[file_cmd_index]); free(args[core_cmd_index]); return bt; } char* problem_data_save(problem_data_t *pd) { load_abrt_conf(); struct dump_dir *dd = NULL; if (g_settings_privatereports) dd = create_dump_dir_from_problem_data_ext(pd, g_settings_dump_location, 0); else dd = create_dump_dir_from_problem_data(pd, g_settings_dump_location); char *problem_id = NULL; if (dd) { problem_id = xstrdup(dd->dd_dirname); dd_close(dd); } log_info("problem id: '%s'", problem_id); return problem_id; } bool dir_is_in_dump_location(const char *dir_name) { unsigned len = strlen(g_settings_dump_location); /* The path must start with "g_settings_dump_location" */ if (strncmp(dir_name, g_settings_dump_location, len) != 0) { log_debug("Bad parent directory: '%s' not in '%s'", g_settings_dump_location, dir_name); return false; } /* and must be a sub-directory of the g_settings_dump_location dir */ const char *base_name = dir_name + len; while (*base_name && *base_name == '/') ++base_name; if (*(base_name - 1) != '/' || !str_is_correct_filename(base_name)) { log_debug("Invalid dump directory name: '%s'", base_name); return false; } /* and we are sure it is a directory */ struct stat sb; if (lstat(dir_name, &sb) < 0) { VERB2 perror_msg("stat('%s')", dir_name); return errno== ENOENT; } return S_ISDIR(sb.st_mode); } bool dir_has_correct_permissions(const char *dir_name) { if (g_settings_privatereports) { struct stat statbuf; if (lstat(dir_name, &statbuf) != 0 || !S_ISDIR(statbuf.st_mode)) { error_msg("Path '%s' isn't directory", dir_name); return false; } /* Get ABRT's group gid */ struct group *gr = getgrnam("abrt"); if (!gr) { error_msg("Group 'abrt' does not exist"); return false; } if (statbuf.st_uid != 0 || !(statbuf.st_gid == 0 || statbuf.st_gid == gr->gr_gid) || statbuf.st_mode & 07) return false; } return true; }
./CrossVul/dataset_final_sorted/CWE-20/c/good_1564_2
crossvul-cpp_data_good_5420_0
/* $Id: file.c,v 1.266 2012/05/22 09:45:56 inu Exp $ */ #include "fm.h" #include <sys/types.h> #include "myctype.h" #include <signal.h> #include <setjmp.h> #if defined(HAVE_WAITPID) || defined(HAVE_WAIT3) #include <sys/wait.h> #endif #include <stdio.h> #include <time.h> #include <sys/stat.h> #include <fcntl.h> #include <utime.h> /* foo */ #include "html.h" #include "parsetagx.h" #include "local.h" #include "regex.h" #ifndef max #define max(a,b) ((a) > (b) ? (a) : (b)) #endif /* not max */ #ifndef min #define min(a,b) ((a) > (b) ? (b) : (a)) #endif /* not min */ #define MAX_INPUT_SIZE 80 /* TODO - max should be screen line length */ static int frame_source = 0; static char *guess_filename(char *file); static int _MoveFile(char *path1, char *path2); static void uncompress_stream(URLFile *uf, char **src); static FILE *lessopen_stream(char *path); static Buffer *loadcmdout(char *cmd, Buffer *(*loadproc) (URLFile *, Buffer *), Buffer *defaultbuf); #ifndef USE_ANSI_COLOR #define addnewline(a,b,c,d,e,f,g) _addnewline(a,b,c,e,f,g) #endif static void addnewline(Buffer *buf, char *line, Lineprop *prop, Linecolor *color, int pos, int width, int nlines); static void addLink(Buffer *buf, struct parsed_tag *tag); static JMP_BUF AbortLoading; static struct table *tables[MAX_TABLE]; static struct table_mode table_mode[MAX_TABLE]; #if defined(USE_M17N) || defined(USE_IMAGE) static ParsedURL *cur_baseURL = NULL; #endif #ifdef USE_M17N static wc_ces cur_document_charset = 0; #endif static Str cur_title; static Str cur_select; static Str select_str; static int select_is_multiple; static int n_selectitem; static Str cur_option; static Str cur_option_value; static Str cur_option_label; static int cur_option_selected; static int cur_status; #ifdef MENU_SELECT /* menu based <select> */ FormSelectOption *select_option; int max_select = MAX_SELECT; static int n_select; static int cur_option_maxwidth; #endif /* MENU_SELECT */ static Str cur_textarea; Str *textarea_str; static int cur_textarea_size; static int cur_textarea_rows; static int cur_textarea_readonly; static int n_textarea; static int ignore_nl_textarea; int max_textarea = MAX_TEXTAREA; static int http_response_code; #ifdef USE_M17N static wc_ces content_charset = 0; static wc_ces meta_charset = 0; static char *check_charset(char *p); static char *check_accept_charset(char *p); #endif #define set_prevchar(x,y,n) Strcopy_charp_n((x),(y),(n)) #define set_space_to_prevchar(x) Strcopy_charp_n((x)," ",1) struct link_stack { int cmd; short offset; short pos; struct link_stack *next; }; static struct link_stack *link_stack = NULL; #define FORMSTACK_SIZE 10 #define FRAMESTACK_SIZE 10 #ifdef USE_NNTP #define Str_news_endline(s) ((s)->ptr[0]=='.'&&((s)->ptr[1]=='\n'||(s)->ptr[1]=='\r'||(s)->ptr[1]=='\0')) #endif /* USE_NNTP */ #define INITIAL_FORM_SIZE 10 static FormList **forms; static int *form_stack; static int form_max = -1; static int forms_size = 0; #define cur_form_id ((form_sp >= 0)? form_stack[form_sp] : -1) static int form_sp = 0; static clen_t current_content_length; static int cur_hseq; #ifdef USE_IMAGE static int cur_iseq; #endif #define MAX_UL_LEVEL 9 #define UL_SYMBOL(x) (N_GRAPH_SYMBOL + (x)) #define UL_SYMBOL_DISC UL_SYMBOL(9) #define UL_SYMBOL_CIRCLE UL_SYMBOL(10) #define UL_SYMBOL_SQUARE UL_SYMBOL(11) #define IMG_SYMBOL UL_SYMBOL(12) #define HR_SYMBOL 26 #ifdef USE_COOKIE /* This array should be somewhere else */ /* FIXME: gettextize? */ char *violations[COO_EMAX] = { "internal error", "tail match failed", "wrong number of dots", "RFC 2109 4.3.2 rule 1", "RFC 2109 4.3.2 rule 2.1", "RFC 2109 4.3.2 rule 2.2", "RFC 2109 4.3.2 rule 3", "RFC 2109 4.3.2 rule 4", "RFC XXXX 4.3.2 rule 5" }; #endif /* *INDENT-OFF* */ static struct compression_decoder { int type; char *ext; char *mime_type; int auxbin_p; char *cmd; char *name; char *encoding; char *encodings[4]; } compression_decoders[] = { { CMP_COMPRESS, ".gz", "application/x-gzip", 0, GUNZIP_CMDNAME, GUNZIP_NAME, "gzip", {"gzip", "x-gzip", NULL} }, { CMP_COMPRESS, ".Z", "application/x-compress", 0, GUNZIP_CMDNAME, GUNZIP_NAME, "compress", {"compress", "x-compress", NULL} }, { CMP_BZIP2, ".bz2", "application/x-bzip", 0, BUNZIP2_CMDNAME, BUNZIP2_NAME, "bzip, bzip2", {"x-bzip", "bzip", "bzip2", NULL} }, { CMP_DEFLATE, ".deflate", "application/x-deflate", 1, INFLATE_CMDNAME, INFLATE_NAME, "deflate", {"deflate", "x-deflate", NULL} }, { CMP_NOCOMPRESS, NULL, NULL, 0, NULL, NULL, NULL, {NULL}}, }; /* *INDENT-ON* */ #define SAVE_BUF_SIZE 1536 static MySignalHandler KeyAbort(SIGNAL_ARG) { LONGJMP(AbortLoading, 1); SIGNAL_RETURN; } static void UFhalfclose(URLFile *f) { switch (f->scheme) { case SCM_FTP: closeFTP(); break; #ifdef USE_NNTP case SCM_NEWS: case SCM_NNTP: closeNews(); break; #endif default: UFclose(f); break; } } int currentLn(Buffer *buf) { if (buf->currentLine) /* return buf->currentLine->real_linenumber + 1; */ return buf->currentLine->linenumber + 1; else return 1; } static Buffer * loadSomething(URLFile *f, Buffer *(*loadproc) (URLFile *, Buffer *), Buffer *defaultbuf) { Buffer *buf; if ((buf = loadproc(f, defaultbuf)) == NULL) return NULL; if (buf->buffername == NULL || buf->buffername[0] == '\0') { buf->buffername = checkHeader(buf, "Subject:"); if (buf->buffername == NULL && buf->filename != NULL) buf->buffername = conv_from_system(lastFileName(buf->filename)); } if (buf->currentURL.scheme == SCM_UNKNOWN) buf->currentURL.scheme = f->scheme; if (f->scheme == SCM_LOCAL && buf->sourcefile == NULL) buf->sourcefile = buf->filename; if (loadproc == loadHTMLBuffer #ifdef USE_IMAGE || loadproc == loadImageBuffer #endif ) buf->type = "text/html"; else buf->type = "text/plain"; return buf; } int dir_exist(char *path) { struct stat stbuf; if (path == NULL || *path == '\0') return 0; if (stat(path, &stbuf) == -1) return 0; return IS_DIRECTORY(stbuf.st_mode); } static int is_dump_text_type(char *type) { struct mailcap *mcap; return (type && (mcap = searchExtViewer(type)) && (mcap->flags & (MAILCAP_HTMLOUTPUT | MAILCAP_COPIOUSOUTPUT))); } static int is_text_type(char *type) { return (type == NULL || type[0] == '\0' || strncasecmp(type, "text/", 5) == 0 || (strncasecmp(type, "application/", 12) == 0 && strstr(type, "xhtml") != NULL) || strncasecmp(type, "message/", sizeof("message/") - 1) == 0); } static int is_plain_text_type(char *type) { return ((type && strcasecmp(type, "text/plain") == 0) || (is_text_type(type) && !is_dump_text_type(type))); } int is_html_type(char *type) { return (type && (strcasecmp(type, "text/html") == 0 || strcasecmp(type, "application/xhtml+xml") == 0)); } static void check_compression(char *path, URLFile *uf) { int len; struct compression_decoder *d; if (path == NULL) return; len = strlen(path); uf->compression = CMP_NOCOMPRESS; for (d = compression_decoders; d->type != CMP_NOCOMPRESS; d++) { int elen; if (d->ext == NULL) continue; elen = strlen(d->ext); if (len > elen && strcasecmp(&path[len - elen], d->ext) == 0) { uf->compression = d->type; uf->guess_type = d->mime_type; break; } } } static char * compress_application_type(int compression) { struct compression_decoder *d; for (d = compression_decoders; d->type != CMP_NOCOMPRESS; d++) { if (d->type == compression) return d->mime_type; } return NULL; } static char * uncompressed_file_type(char *path, char **ext) { int len, slen; Str fn; char *t0; struct compression_decoder *d; if (path == NULL) return NULL; slen = 0; len = strlen(path); for (d = compression_decoders; d->type != CMP_NOCOMPRESS; d++) { if (d->ext == NULL) continue; slen = strlen(d->ext); if (len > slen && strcasecmp(&path[len - slen], d->ext) == 0) break; } if (d->type == CMP_NOCOMPRESS) return NULL; fn = Strnew_charp(path); Strshrink(fn, slen); if (ext) *ext = filename_extension(fn->ptr, 0); t0 = guessContentType(fn->ptr); if (t0 == NULL) t0 = "text/plain"; return t0; } static int setModtime(char *path, time_t modtime) { struct utimbuf t; struct stat st; if (stat(path, &st) == 0) t.actime = st.st_atime; else t.actime = time(NULL); t.modtime = modtime; return utime(path, &t); } void examineFile(char *path, URLFile *uf) { struct stat stbuf; uf->guess_type = NULL; if (path == NULL || *path == '\0' || stat(path, &stbuf) == -1 || NOT_REGULAR(stbuf.st_mode)) { uf->stream = NULL; return; } uf->stream = openIS(path); if (!do_download) { if (use_lessopen && getenv("LESSOPEN") != NULL) { FILE *fp; uf->guess_type = guessContentType(path); if (uf->guess_type == NULL) uf->guess_type = "text/plain"; if (is_html_type(uf->guess_type)) return; if ((fp = lessopen_stream(path))) { UFclose(uf); uf->stream = newFileStream(fp, (void (*)())pclose); uf->guess_type = "text/plain"; return; } } check_compression(path, uf); if (uf->compression != CMP_NOCOMPRESS) { char *ext = uf->ext; char *t0 = uncompressed_file_type(path, &ext); uf->guess_type = t0; uf->ext = ext; uncompress_stream(uf, NULL); return; } } } #define S_IXANY (S_IXUSR|S_IXGRP|S_IXOTH) int check_command(char *cmd, int auxbin_p) { static char *path = NULL; Str dirs; char *p, *np; Str pathname; struct stat st; if (path == NULL) path = getenv("PATH"); if (auxbin_p) dirs = Strnew_charp(w3m_auxbin_dir()); else dirs = Strnew_charp(path); for (p = dirs->ptr; p != NULL; p = np) { np = strchr(p, PATH_SEPARATOR); if (np) *np++ = '\0'; pathname = Strnew(); Strcat_charp(pathname, p); Strcat_char(pathname, '/'); Strcat_charp(pathname, cmd); if (stat(pathname->ptr, &st) == 0 && S_ISREG(st.st_mode) && (st.st_mode & S_IXANY) != 0) return 1; } return 0; } char * acceptableEncoding() { static Str encodings = NULL; struct compression_decoder *d; TextList *l; char *p; if (encodings != NULL) return encodings->ptr; l = newTextList(); for (d = compression_decoders; d->type != CMP_NOCOMPRESS; d++) { if (check_command(d->cmd, d->auxbin_p)) { pushText(l, d->encoding); } } encodings = Strnew(); while ((p = popText(l)) != NULL) { if (encodings->length) Strcat_charp(encodings, ", "); Strcat_charp(encodings, p); } return encodings->ptr; } /* * convert line */ #ifdef USE_M17N Str convertLine(URLFile *uf, Str line, int mode, wc_ces * charset, wc_ces doc_charset) #else Str convertLine0(URLFile *uf, Str line, int mode) #endif { #ifdef USE_M17N line = wc_Str_conv_with_detect(line, charset, doc_charset, InnerCharset); #endif if (mode != RAW_MODE) cleanup_line(line, mode); #ifdef USE_NNTP if (uf && uf->scheme == SCM_NEWS) Strchop(line); #endif /* USE_NNTP */ return line; } int matchattr(char *p, char *attr, int len, Str *value) { int quoted; char *q = NULL; if (strncasecmp(p, attr, len) == 0) { p += len; SKIP_BLANKS(p); if (value) { *value = Strnew(); if (*p == '=') { p++; SKIP_BLANKS(p); quoted = 0; while (!IS_ENDL(*p) && (quoted || *p != ';')) { if (!IS_SPACE(*p)) q = p; if (*p == '"') quoted = (quoted) ? 0 : 1; else Strcat_char(*value, *p); p++; } if (q) Strshrink(*value, p - q - 1); } return 1; } else { if (IS_ENDT(*p)) { return 1; } } } return 0; } #ifdef USE_IMAGE #ifdef USE_XFACE static char * xface2xpm(char *xface) { Image image; ImageCache *cache; FILE *f; struct stat st; SKIP_BLANKS(xface); image.url = xface; image.ext = ".xpm"; image.width = 48; image.height = 48; image.cache = NULL; cache = getImage(&image, NULL, IMG_FLAG_AUTO); if (cache->loaded & IMG_FLAG_LOADED && !stat(cache->file, &st)) return cache->file; cache->loaded = IMG_FLAG_ERROR; f = popen(Sprintf("%s > %s", shell_quote(auxbinFile(XFACE2XPM)), shell_quote(cache->file))->ptr, "w"); if (!f) return NULL; fputs(xface, f); pclose(f); if (stat(cache->file, &st) || !st.st_size) return NULL; cache->loaded = IMG_FLAG_LOADED | IMG_FLAG_DONT_REMOVE; cache->index = 0; return cache->file; } #endif #endif void readHeader(URLFile *uf, Buffer *newBuf, int thru, ParsedURL *pu) { char *p, *q; #ifdef USE_COOKIE char *emsg; #endif char c; Str lineBuf2 = NULL; Str tmp; TextList *headerlist; #ifdef USE_M17N wc_ces charset = WC_CES_US_ASCII, mime_charset; #endif char *tmpf; FILE *src = NULL; Lineprop *propBuffer; headerlist = newBuf->document_header = newTextList(); if (uf->scheme == SCM_HTTP #ifdef USE_SSL || uf->scheme == SCM_HTTPS #endif /* USE_SSL */ ) http_response_code = -1; else http_response_code = 0; if (thru && !newBuf->header_source #ifdef USE_IMAGE && !image_source #endif ) { tmpf = tmpfname(TMPF_DFL, NULL)->ptr; src = fopen(tmpf, "w"); if (src) newBuf->header_source = tmpf; } while ((tmp = StrmyUFgets(uf))->length) { #ifdef USE_NNTP if (uf->scheme == SCM_NEWS && tmp->ptr[0] == '.') Strshrinkfirst(tmp, 1); #endif if(w3m_reqlog){ FILE *ff; ff = fopen(w3m_reqlog, "a"); Strfputs(tmp, ff); fclose(ff); } if (src) Strfputs(tmp, src); cleanup_line(tmp, HEADER_MODE); if (tmp->ptr[0] == '\n' || tmp->ptr[0] == '\r' || tmp->ptr[0] == '\0') { if (!lineBuf2) /* there is no header */ break; /* last header */ } else if (!(w3m_dump & DUMP_HEAD)) { if (lineBuf2) { Strcat(lineBuf2, tmp); } else { lineBuf2 = tmp; } c = UFgetc(uf); UFundogetc(uf); if (c == ' ' || c == '\t') /* header line is continued */ continue; lineBuf2 = decodeMIME(lineBuf2, &mime_charset); lineBuf2 = convertLine(NULL, lineBuf2, RAW_MODE, mime_charset ? &mime_charset : &charset, mime_charset ? mime_charset : DocumentCharset); /* separated with line and stored */ tmp = Strnew_size(lineBuf2->length); for (p = lineBuf2->ptr; *p; p = q) { for (q = p; *q && *q != '\r' && *q != '\n'; q++) ; lineBuf2 = checkType(Strnew_charp_n(p, q - p), &propBuffer, NULL); Strcat(tmp, lineBuf2); if (thru) addnewline(newBuf, lineBuf2->ptr, propBuffer, NULL, lineBuf2->length, FOLD_BUFFER_WIDTH, -1); for (; *q && (*q == '\r' || *q == '\n'); q++) ; } #ifdef USE_IMAGE if (thru && activeImage && displayImage) { Str src = NULL; if (!strncasecmp(tmp->ptr, "X-Image-URL:", 12)) { tmpf = &tmp->ptr[12]; SKIP_BLANKS(tmpf); src = Strnew_m_charp("<img src=\"", html_quote(tmpf), "\" alt=\"X-Image-URL\">", NULL); } #ifdef USE_XFACE else if (!strncasecmp(tmp->ptr, "X-Face:", 7)) { tmpf = xface2xpm(&tmp->ptr[7]); if (tmpf) src = Strnew_m_charp("<img src=\"file:", html_quote(tmpf), "\" alt=\"X-Face\"", " width=48 height=48>", NULL); } #endif if (src) { URLFile f; Line *l; #ifdef USE_M17N wc_ces old_charset = newBuf->document_charset; #endif init_stream(&f, SCM_LOCAL, newStrStream(src)); loadHTMLstream(&f, newBuf, NULL, TRUE); UFclose(&f); for (l = newBuf->lastLine; l && l->real_linenumber; l = l->prev) l->real_linenumber = 0; #ifdef USE_M17N newBuf->document_charset = old_charset; #endif } } #endif lineBuf2 = tmp; } else { lineBuf2 = tmp; } if ((uf->scheme == SCM_HTTP #ifdef USE_SSL || uf->scheme == SCM_HTTPS #endif /* USE_SSL */ ) && http_response_code == -1) { p = lineBuf2->ptr; while (*p && !IS_SPACE(*p)) p++; while (*p && IS_SPACE(*p)) p++; http_response_code = atoi(p); if (fmInitialized) { message(lineBuf2->ptr, 0, 0); refresh(); } } if (!strncasecmp(lineBuf2->ptr, "content-transfer-encoding:", 26)) { p = lineBuf2->ptr + 26; while (IS_SPACE(*p)) p++; if (!strncasecmp(p, "base64", 6)) uf->encoding = ENC_BASE64; else if (!strncasecmp(p, "quoted-printable", 16)) uf->encoding = ENC_QUOTE; else if (!strncasecmp(p, "uuencode", 8) || !strncasecmp(p, "x-uuencode", 10)) uf->encoding = ENC_UUENCODE; else uf->encoding = ENC_7BIT; } else if (!strncasecmp(lineBuf2->ptr, "content-encoding:", 17)) { struct compression_decoder *d; p = lineBuf2->ptr + 17; while (IS_SPACE(*p)) p++; uf->compression = CMP_NOCOMPRESS; for (d = compression_decoders; d->type != CMP_NOCOMPRESS; d++) { char **e; for (e = d->encodings; *e != NULL; e++) { if (strncasecmp(p, *e, strlen(*e)) == 0) { uf->compression = d->type; break; } } if (uf->compression != CMP_NOCOMPRESS) break; } uf->content_encoding = uf->compression; } #ifdef USE_COOKIE else if (use_cookie && accept_cookie && pu && check_cookie_accept_domain(pu->host) && (!strncasecmp(lineBuf2->ptr, "Set-Cookie:", 11) || !strncasecmp(lineBuf2->ptr, "Set-Cookie2:", 12))) { Str name = Strnew(), value = Strnew(), domain = NULL, path = NULL, comment = NULL, commentURL = NULL, port = NULL, tmp2; int version, quoted, flag = 0; time_t expires = (time_t) - 1; q = NULL; if (lineBuf2->ptr[10] == '2') { p = lineBuf2->ptr + 12; version = 1; } else { p = lineBuf2->ptr + 11; version = 0; } #ifdef DEBUG fprintf(stderr, "Set-Cookie: [%s]\n", p); #endif /* DEBUG */ SKIP_BLANKS(p); while (*p != '=' && !IS_ENDT(*p)) Strcat_char(name, *(p++)); Strremovetrailingspaces(name); if (*p == '=') { p++; SKIP_BLANKS(p); quoted = 0; while (!IS_ENDL(*p) && (quoted || *p != ';')) { if (!IS_SPACE(*p)) q = p; if (*p == '"') quoted = (quoted) ? 0 : 1; Strcat_char(value, *(p++)); } if (q) Strshrink(value, p - q - 1); } while (*p == ';') { p++; SKIP_BLANKS(p); if (matchattr(p, "expires", 7, &tmp2)) { /* version 0 */ expires = mymktime(tmp2->ptr); } else if (matchattr(p, "max-age", 7, &tmp2)) { /* XXX Is there any problem with max-age=0? (RFC 2109 ss. 4.2.1, 4.2.2 */ expires = time(NULL) + atol(tmp2->ptr); } else if (matchattr(p, "domain", 6, &tmp2)) { domain = tmp2; } else if (matchattr(p, "path", 4, &tmp2)) { path = tmp2; } else if (matchattr(p, "secure", 6, NULL)) { flag |= COO_SECURE; } else if (matchattr(p, "comment", 7, &tmp2)) { comment = tmp2; } else if (matchattr(p, "version", 7, &tmp2)) { version = atoi(tmp2->ptr); } else if (matchattr(p, "port", 4, &tmp2)) { /* version 1, Set-Cookie2 */ port = tmp2; } else if (matchattr(p, "commentURL", 10, &tmp2)) { /* version 1, Set-Cookie2 */ commentURL = tmp2; } else if (matchattr(p, "discard", 7, NULL)) { /* version 1, Set-Cookie2 */ flag |= COO_DISCARD; } quoted = 0; while (!IS_ENDL(*p) && (quoted || *p != ';')) { if (*p == '"') quoted = (quoted) ? 0 : 1; p++; } } if (pu && name->length > 0) { int err; if (show_cookie) { if (flag & COO_SECURE) disp_message_nsec("Received a secured cookie", FALSE, 1, TRUE, FALSE); else disp_message_nsec(Sprintf("Received cookie: %s=%s", name->ptr, value->ptr)->ptr, FALSE, 1, TRUE, FALSE); } err = add_cookie(pu, name, value, expires, domain, path, flag, comment, version, port, commentURL); if (err) { char *ans = (accept_bad_cookie == ACCEPT_BAD_COOKIE_ACCEPT) ? "y" : NULL; if (fmInitialized && (err & COO_OVERRIDE_OK) && accept_bad_cookie == ACCEPT_BAD_COOKIE_ASK) { Str msg = Sprintf("Accept bad cookie from %s for %s?", pu->host, ((domain && domain->ptr) ? domain->ptr : "<localdomain>")); if (msg->length > COLS - 10) Strshrink(msg, msg->length - (COLS - 10)); Strcat_charp(msg, " (y/n)"); ans = inputAnswer(msg->ptr); } if (ans == NULL || TOLOWER(*ans) != 'y' || (err = add_cookie(pu, name, value, expires, domain, path, flag | COO_OVERRIDE, comment, version, port, commentURL))) { err = (err & ~COO_OVERRIDE_OK) - 1; if (err >= 0 && err < COO_EMAX) emsg = Sprintf("This cookie was rejected " "to prevent security violation. [%s]", violations[err])->ptr; else emsg = "This cookie was rejected to prevent security violation."; record_err_message(emsg); if (show_cookie) disp_message_nsec(emsg, FALSE, 1, TRUE, FALSE); } else if (show_cookie) disp_message_nsec(Sprintf ("Accepting invalid cookie: %s=%s", name->ptr, value->ptr)->ptr, FALSE, 1, TRUE, FALSE); } } } #endif /* USE_COOKIE */ else if (!strncasecmp(lineBuf2->ptr, "w3m-control:", 12) && uf->scheme == SCM_LOCAL_CGI) { Str funcname = Strnew(); int f; p = lineBuf2->ptr + 12; SKIP_BLANKS(p); while (*p && !IS_SPACE(*p)) Strcat_char(funcname, *(p++)); SKIP_BLANKS(p); f = getFuncList(funcname->ptr); if (f >= 0) { tmp = Strnew_charp(p); Strchop(tmp); pushEvent(f, tmp->ptr); } } if (headerlist) pushText(headerlist, lineBuf2->ptr); Strfree(lineBuf2); lineBuf2 = NULL; } if (thru) addnewline(newBuf, "", propBuffer, NULL, 0, -1, -1); if (src) fclose(src); } char * checkHeader(Buffer *buf, char *field) { int len; TextListItem *i; char *p; if (buf == NULL || field == NULL || buf->document_header == NULL) return NULL; len = strlen(field); for (i = buf->document_header->first; i != NULL; i = i->next) { if (!strncasecmp(i->ptr, field, len)) { p = i->ptr + len; return remove_space(p); } } return NULL; } char * checkContentType(Buffer *buf) { char *p; Str r; p = checkHeader(buf, "Content-Type:"); if (p == NULL) return NULL; r = Strnew(); while (*p && *p != ';' && !IS_SPACE(*p)) Strcat_char(r, *p++); #ifdef USE_M17N if ((p = strcasestr(p, "charset")) != NULL) { p += 7; SKIP_BLANKS(p); if (*p == '=') { p++; SKIP_BLANKS(p); if (*p == '"') p++; content_charset = wc_guess_charset(p, 0); } } #endif return r->ptr; } struct auth_param { char *name; Str val; }; struct http_auth { int pri; char *scheme; struct auth_param *param; Str (*cred) (struct http_auth * ha, Str uname, Str pw, ParsedURL *pu, HRequest *hr, FormList *request); }; enum { AUTHCHR_NUL, AUTHCHR_SEP, AUTHCHR_TOKEN, }; static int skip_auth_token(char **pp) { char *p; int first = AUTHCHR_NUL, typ; for (p = *pp ;; ++p) { switch (*p) { case '\0': goto endoftoken; default: if ((unsigned char)*p > 037) { typ = AUTHCHR_TOKEN; break; } /* thru */ case '\177': case '[': case ']': case '(': case ')': case '<': case '>': case '@': case ';': case ':': case '\\': case '"': case '/': case '?': case '=': case ' ': case '\t': case ',': typ = AUTHCHR_SEP; break; } if (!first) first = typ; else if (first != typ) break; } endoftoken: *pp = p; return first; } static Str extract_auth_val(char **q) { unsigned char *qq = *(unsigned char **)q; int quoted = 0; Str val = Strnew(); SKIP_BLANKS(qq); if (*qq == '"') { quoted = TRUE; Strcat_char(val, *qq++); } while (*qq != '\0') { if (quoted && *qq == '"') { Strcat_char(val, *qq++); break; } if (!quoted) { switch (*qq) { case '[': case ']': case '(': case ')': case '<': case '>': case '@': case ';': case ':': case '\\': case '"': case '/': case '?': case '=': case ' ': case '\t': qq++; case ',': goto end_token; default: if (*qq <= 037 || *qq == 0177) { qq++; goto end_token; } } } else if (quoted && *qq == '\\') Strcat_char(val, *qq++); Strcat_char(val, *qq++); } end_token: *q = (char *)qq; return val; } static Str qstr_unquote(Str s) { char *p; if (s == NULL) return NULL; p = s->ptr; if (*p == '"') { Str tmp = Strnew(); for (p++; *p != '\0'; p++) { if (*p == '\\') p++; Strcat_char(tmp, *p); } if (Strlastchar(tmp) == '"') Strshrink(tmp, 1); return tmp; } else return s; } static char * extract_auth_param(char *q, struct auth_param *auth) { struct auth_param *ap; char *p; for (ap = auth; ap->name != NULL; ap++) { ap->val = NULL; } while (*q != '\0') { SKIP_BLANKS(q); for (ap = auth; ap->name != NULL; ap++) { size_t len; len = strlen(ap->name); if (strncasecmp(q, ap->name, len) == 0 && (IS_SPACE(q[len]) || q[len] == '=')) { p = q + len; SKIP_BLANKS(p); if (*p != '=') return q; q = p + 1; ap->val = extract_auth_val(&q); break; } } if (ap->name == NULL) { /* skip unknown param */ int token_type; p = q; if ((token_type = skip_auth_token(&q)) == AUTHCHR_TOKEN && (IS_SPACE(*q) || *q == '=')) { SKIP_BLANKS(q); if (*q != '=') return p; q++; extract_auth_val(&q); } else return p; } if (*q != '\0') { SKIP_BLANKS(q); if (*q == ',') q++; else break; } } return q; } static Str get_auth_param(struct auth_param *auth, char *name) { struct auth_param *ap; for (ap = auth; ap->name != NULL; ap++) { if (strcasecmp(name, ap->name) == 0) return ap->val; } return NULL; } static Str AuthBasicCred(struct http_auth *ha, Str uname, Str pw, ParsedURL *pu, HRequest *hr, FormList *request) { Str s = Strdup(uname); Strcat_char(s, ':'); Strcat(s, pw); return Strnew_m_charp("Basic ", encodeB(s->ptr)->ptr, NULL); } #ifdef USE_DIGEST_AUTH #include <openssl/md5.h> /* RFC2617: 3.2.2 The Authorization Request Header * * credentials = "Digest" digest-response * digest-response = 1#( username | realm | nonce | digest-uri * | response | [ algorithm ] | [cnonce] | * [opaque] | [message-qop] | * [nonce-count] | [auth-param] ) * * username = "username" "=" username-value * username-value = quoted-string * digest-uri = "uri" "=" digest-uri-value * digest-uri-value = request-uri ; As specified by HTTP/1.1 * message-qop = "qop" "=" qop-value * cnonce = "cnonce" "=" cnonce-value * cnonce-value = nonce-value * nonce-count = "nc" "=" nc-value * nc-value = 8LHEX * response = "response" "=" request-digest * request-digest = <"> 32LHEX <"> * LHEX = "0" | "1" | "2" | "3" | * "4" | "5" | "6" | "7" | * "8" | "9" | "a" | "b" | * "c" | "d" | "e" | "f" */ static Str digest_hex(unsigned char *p) { char *h = "0123456789abcdef"; Str tmp = Strnew_size(MD5_DIGEST_LENGTH * 2 + 1); int i; for (i = 0; i < MD5_DIGEST_LENGTH; i++, p++) { Strcat_char(tmp, h[(*p >> 4) & 0x0f]); Strcat_char(tmp, h[*p & 0x0f]); } return tmp; } enum { QOP_NONE, QOP_AUTH, QOP_AUTH_INT, }; static Str AuthDigestCred(struct http_auth *ha, Str uname, Str pw, ParsedURL *pu, HRequest *hr, FormList *request) { Str tmp, a1buf, a2buf, rd, s; unsigned char md5[MD5_DIGEST_LENGTH + 1]; Str uri = HTTPrequestURI(pu, hr); char nc[] = "00000001"; FILE *fp; Str algorithm = qstr_unquote(get_auth_param(ha->param, "algorithm")); Str nonce = qstr_unquote(get_auth_param(ha->param, "nonce")); Str cnonce /* = qstr_unquote(get_auth_param(ha->param, "cnonce")) */; /* cnonce is what client should generate. */ Str qop = qstr_unquote(get_auth_param(ha->param, "qop")); static union { int r[4]; unsigned char s[sizeof(int) * 4]; } cnonce_seed; int qop_i = QOP_NONE; cnonce_seed.r[0] = rand(); cnonce_seed.r[1] = rand(); cnonce_seed.r[2] = rand(); MD5(cnonce_seed.s, sizeof(cnonce_seed.s), md5); cnonce = digest_hex(md5); cnonce_seed.r[3]++; if (qop) { char *p; size_t i; p = qop->ptr; SKIP_BLANKS(p); for (;;) { if ((i = strcspn(p, " \t,")) > 0) { if (i == sizeof("auth-int") - sizeof("") && !strncasecmp(p, "auth-int", i)) { if (qop_i < QOP_AUTH_INT) qop_i = QOP_AUTH_INT; } else if (i == sizeof("auth") - sizeof("") && !strncasecmp(p, "auth", i)) { if (qop_i < QOP_AUTH) qop_i = QOP_AUTH; } } if (p[i]) { p += i + 1; SKIP_BLANKS(p); } else break; } } /* A1 = unq(username-value) ":" unq(realm-value) ":" passwd */ tmp = Strnew_m_charp(uname->ptr, ":", qstr_unquote(get_auth_param(ha->param, "realm"))->ptr, ":", pw->ptr, NULL); MD5(tmp->ptr, strlen(tmp->ptr), md5); a1buf = digest_hex(md5); if (algorithm) { if (strcasecmp(algorithm->ptr, "MD5-sess") == 0) { /* A1 = H(unq(username-value) ":" unq(realm-value) ":" passwd) * ":" unq(nonce-value) ":" unq(cnonce-value) */ if (nonce == NULL) return NULL; tmp = Strnew_m_charp(a1buf->ptr, ":", qstr_unquote(nonce)->ptr, ":", qstr_unquote(cnonce)->ptr, NULL); MD5(tmp->ptr, strlen(tmp->ptr), md5); a1buf = digest_hex(md5); } else if (strcasecmp(algorithm->ptr, "MD5") == 0) /* ok default */ ; else /* unknown algorithm */ return NULL; } /* A2 = Method ":" digest-uri-value */ tmp = Strnew_m_charp(HTTPrequestMethod(hr)->ptr, ":", uri->ptr, NULL); if (qop_i == QOP_AUTH_INT) { /* A2 = Method ":" digest-uri-value ":" H(entity-body) */ if (request && request->body) { if (request->method == FORM_METHOD_POST && request->enctype == FORM_ENCTYPE_MULTIPART) { fp = fopen(request->body, "r"); if (fp != NULL) { Str ebody; ebody = Strfgetall(fp); fclose(fp); MD5(ebody->ptr, strlen(ebody->ptr), md5); } else { MD5("", 0, md5); } } else { MD5(request->body, request->length, md5); } } else { MD5("", 0, md5); } Strcat_char(tmp, ':'); Strcat(tmp, digest_hex(md5)); } MD5(tmp->ptr, strlen(tmp->ptr), md5); a2buf = digest_hex(md5); if (qop_i >= QOP_AUTH) { /* request-digest = <"> < KD ( H(A1), unq(nonce-value) * ":" nc-value * ":" unq(cnonce-value) * ":" unq(qop-value) * ":" H(A2) * ) <"> */ if (nonce == NULL) return NULL; tmp = Strnew_m_charp(a1buf->ptr, ":", qstr_unquote(nonce)->ptr, ":", nc, ":", qstr_unquote(cnonce)->ptr, ":", qop_i == QOP_AUTH ? "auth" : "auth-int", ":", a2buf->ptr, NULL); MD5(tmp->ptr, strlen(tmp->ptr), md5); rd = digest_hex(md5); } else { /* compatibility with RFC 2069 * request_digest = KD(H(A1), unq(nonce), H(A2)) */ tmp = Strnew_m_charp(a1buf->ptr, ":", qstr_unquote(get_auth_param(ha->param, "nonce"))-> ptr, ":", a2buf->ptr, NULL); MD5(tmp->ptr, strlen(tmp->ptr), md5); rd = digest_hex(md5); } /* * digest-response = 1#( username | realm | nonce | digest-uri * | response | [ algorithm ] | [cnonce] | * [opaque] | [message-qop] | * [nonce-count] | [auth-param] ) */ tmp = Strnew_m_charp("Digest username=\"", uname->ptr, "\"", NULL); Strcat_m_charp(tmp, ", realm=", get_auth_param(ha->param, "realm")->ptr, NULL); Strcat_m_charp(tmp, ", nonce=", get_auth_param(ha->param, "nonce")->ptr, NULL); Strcat_m_charp(tmp, ", uri=\"", uri->ptr, "\"", NULL); Strcat_m_charp(tmp, ", response=\"", rd->ptr, "\"", NULL); if (algorithm) Strcat_m_charp(tmp, ", algorithm=", get_auth_param(ha->param, "algorithm")->ptr, NULL); if (cnonce) Strcat_m_charp(tmp, ", cnonce=\"", cnonce->ptr, "\"", NULL); if ((s = get_auth_param(ha->param, "opaque")) != NULL) Strcat_m_charp(tmp, ", opaque=", s->ptr, NULL); if (qop_i >= QOP_AUTH) { Strcat_m_charp(tmp, ", qop=", qop_i == QOP_AUTH ? "auth" : "auth-int", NULL); /* XXX how to count? */ /* Since nonce is unique up to each *-Authenticate and w3m does not re-use *-Authenticate: headers, nonce-count should be always "00000001". */ Strcat_m_charp(tmp, ", nc=", nc, NULL); } return tmp; } #endif /* *INDENT-OFF* */ struct auth_param none_auth_param[] = { {NULL, NULL} }; struct auth_param basic_auth_param[] = { {"realm", NULL}, {NULL, NULL} }; #ifdef USE_DIGEST_AUTH /* RFC2617: 3.2.1 The WWW-Authenticate Response Header * challenge = "Digest" digest-challenge * * digest-challenge = 1#( realm | [ domain ] | nonce | * [ opaque ] |[ stale ] | [ algorithm ] | * [ qop-options ] | [auth-param] ) * * domain = "domain" "=" <"> URI ( 1*SP URI ) <"> * URI = absoluteURI | abs_path * nonce = "nonce" "=" nonce-value * nonce-value = quoted-string * opaque = "opaque" "=" quoted-string * stale = "stale" "=" ( "true" | "false" ) * algorithm = "algorithm" "=" ( "MD5" | "MD5-sess" | * token ) * qop-options = "qop" "=" <"> 1#qop-value <"> * qop-value = "auth" | "auth-int" | token */ struct auth_param digest_auth_param[] = { {"realm", NULL}, {"domain", NULL}, {"nonce", NULL}, {"opaque", NULL}, {"stale", NULL}, {"algorithm", NULL}, {"qop", NULL}, {NULL, NULL} }; #endif /* for RFC2617: HTTP Authentication */ struct http_auth www_auth[] = { { 1, "Basic ", basic_auth_param, AuthBasicCred }, #ifdef USE_DIGEST_AUTH { 10, "Digest ", digest_auth_param, AuthDigestCred }, #endif { 0, NULL, NULL, NULL,} }; /* *INDENT-ON* */ static struct http_auth * findAuthentication(struct http_auth *hauth, Buffer *buf, char *auth_field) { struct http_auth *ha; int len = strlen(auth_field), slen; TextListItem *i; char *p0, *p; bzero(hauth, sizeof(struct http_auth)); for (i = buf->document_header->first; i != NULL; i = i->next) { if (strncasecmp(i->ptr, auth_field, len) == 0) { for (p = i->ptr + len; p != NULL && *p != '\0';) { SKIP_BLANKS(p); p0 = p; for (ha = &www_auth[0]; ha->scheme != NULL; ha++) { slen = strlen(ha->scheme); if (strncasecmp(p, ha->scheme, slen) == 0) { p += slen; SKIP_BLANKS(p); if (hauth->pri < ha->pri) { *hauth = *ha; p = extract_auth_param(p, hauth->param); break; } else { /* weak auth */ p = extract_auth_param(p, none_auth_param); } } } if (p0 == p) { /* all unknown auth failed */ int token_type; if ((token_type = skip_auth_token(&p)) == AUTHCHR_TOKEN && IS_SPACE(*p)) { SKIP_BLANKS(p); p = extract_auth_param(p, none_auth_param); } else break; } } } } return hauth->scheme ? hauth : NULL; } static void getAuthCookie(struct http_auth *hauth, char *auth_header, TextList *extra_header, ParsedURL *pu, HRequest *hr, FormList *request, volatile Str *uname, volatile Str *pwd) { Str ss = NULL; Str tmp; TextListItem *i; int a_found; int auth_header_len = strlen(auth_header); char *realm = NULL; int proxy; if (hauth) realm = qstr_unquote(get_auth_param(hauth->param, "realm"))->ptr; if (!realm) return; a_found = FALSE; for (i = extra_header->first; i != NULL; i = i->next) { if (!strncasecmp(i->ptr, auth_header, auth_header_len)) { a_found = TRUE; break; } } proxy = !strncasecmp("Proxy-Authorization:", auth_header, auth_header_len); if (a_found) { /* This means that *-Authenticate: header is received after * Authorization: header is sent to the server. */ if (fmInitialized) { message("Wrong username or password", 0, 0); refresh(); } else fprintf(stderr, "Wrong username or password\n"); sleep(1); /* delete Authenticate: header from extra_header */ delText(extra_header, i); invalidate_auth_user_passwd(pu, realm, *uname, *pwd, proxy); } *uname = NULL; *pwd = NULL; if (!a_found && find_auth_user_passwd(pu, realm, (Str*)uname, (Str*)pwd, proxy)) { /* found username & password in passwd file */ ; } else { if (QuietMessage) return; /* input username and password */ sleep(2); if (fmInitialized) { char *pp; term_raw(); /* FIXME: gettextize? */ if ((pp = inputStr(Sprintf("Username for %s: ", realm)->ptr, NULL)) == NULL) return; *uname = Str_conv_to_system(Strnew_charp(pp)); if ((pp = inputLine(Sprintf("Password for %s: ", realm)->ptr, NULL, IN_PASSWORD)) == NULL) { *uname = NULL; return; } *pwd = Str_conv_to_system(Strnew_charp(pp)); term_cbreak(); } else { /* * If post file is specified as '-', stdin is closed at this * point. * In this case, w3m cannot read username from stdin. * So exit with error message. * (This is same behavior as lwp-request.) */ if (feof(stdin) || ferror(stdin)) { /* FIXME: gettextize? */ fprintf(stderr, "w3m: Authorization required for %s\n", realm); exit(1); } /* FIXME: gettextize? */ printf(proxy ? "Proxy Username for %s: " : "Username for %s: ", realm); fflush(stdout); *uname = Strfgets(stdin); Strchop(*uname); #ifdef HAVE_GETPASSPHRASE *pwd = Strnew_charp((char *) getpassphrase(proxy ? "Proxy Password: " : "Password: ")); #else #ifndef __MINGW32_VERSION *pwd = Strnew_charp((char *) getpass(proxy ? "Proxy Password: " : "Password: ")); #else term_raw(); *pwd = Strnew_charp((char *) inputLine(proxy ? "Proxy Password: " : "Password: ", NULL, IN_PASSWORD)); term_cbreak(); #endif /* __MINGW32_VERSION */ #endif } } ss = hauth->cred(hauth, *uname, *pwd, pu, hr, request); if (ss) { tmp = Strnew_charp(auth_header); Strcat_m_charp(tmp, " ", ss->ptr, "\r\n", NULL); pushText(extra_header, tmp->ptr); } else { *uname = NULL; *pwd = NULL; } return; } static int same_url_p(ParsedURL *pu1, ParsedURL *pu2) { return (pu1->scheme == pu2->scheme && pu1->port == pu2->port && (pu1->host ? pu2->host ? !strcasecmp(pu1->host, pu2->host) : 0 : 1) && (pu1->file ? pu2-> file ? !strcmp(pu1->file, pu2->file) : 0 : 1)); } static int checkRedirection(ParsedURL *pu) { static ParsedURL *puv = NULL; static int nredir = 0; static int nredir_size = 0; Str tmp; if (pu == NULL) { nredir = 0; nredir_size = 0; puv = NULL; return TRUE; } if (nredir >= FollowRedirection) { /* FIXME: gettextize? */ tmp = Sprintf("Number of redirections exceeded %d at %s", FollowRedirection, parsedURL2Str(pu)->ptr); disp_err_message(tmp->ptr, FALSE); return FALSE; } else if (nredir_size > 0 && (same_url_p(pu, &puv[(nredir - 1) % nredir_size]) || (!(nredir % 2) && same_url_p(pu, &puv[(nredir / 2) % nredir_size])))) { /* FIXME: gettextize? */ tmp = Sprintf("Redirection loop detected (%s)", parsedURL2Str(pu)->ptr); disp_err_message(tmp->ptr, FALSE); return FALSE; } if (!puv) { nredir_size = FollowRedirection / 2 + 1; puv = New_N(ParsedURL, nredir_size); memset(puv, 0, sizeof(ParsedURL) * nredir_size); } copyParsedURL(&puv[nredir % nredir_size], pu); nredir++; return TRUE; } Str getLinkNumberStr(int correction) { return Sprintf("[%d]", cur_hseq + correction); } /* * loadGeneralFile: load file to buffer */ #define DO_EXTERNAL ((Buffer *(*)(URLFile *, Buffer *))doExternal) Buffer * loadGeneralFile(char *path, ParsedURL *volatile current, char *referer, int flag, FormList *volatile request) { URLFile f, *volatile of = NULL; ParsedURL pu; Buffer *b = NULL; Buffer *(*volatile proc)(URLFile *, Buffer *) = loadBuffer; char *volatile tpath; char *volatile t = "text/plain", *p, *volatile real_type = NULL; Buffer *volatile t_buf = NULL; int volatile searchHeader = SearchHeader; int volatile searchHeader_through = TRUE; MySignalHandler(*volatile prevtrap) (SIGNAL_ARG) = NULL; TextList *extra_header = newTextList(); volatile Str uname = NULL; volatile Str pwd = NULL; volatile Str realm = NULL; int volatile add_auth_cookie_flag; unsigned char status = HTST_NORMAL; URLOption url_option; Str tmp; Str volatile page = NULL; #ifdef USE_M17N wc_ces charset = WC_CES_US_ASCII; #endif HRequest hr; ParsedURL *volatile auth_pu; tpath = path; prevtrap = NULL; add_auth_cookie_flag = 0; checkRedirection(NULL); load_doc: { const char *sc_redirect; parseURL2(tpath, &pu, current); sc_redirect = query_SCONF_SUBSTITUTE_URL(&pu); if (sc_redirect && *sc_redirect && checkRedirection(&pu)) { tpath = (char *)sc_redirect; request = NULL; add_auth_cookie_flag = 0; current = New(ParsedURL); *current = pu; status = HTST_NORMAL; goto load_doc; } } TRAP_OFF; url_option.referer = referer; url_option.flag = flag; f = openURL(tpath, &pu, current, &url_option, request, extra_header, of, &hr, &status); of = NULL; #ifdef USE_M17N content_charset = 0; #endif if (f.stream == NULL) { switch (f.scheme) { case SCM_LOCAL: { struct stat st; if (stat(pu.real_file, &st) < 0) return NULL; if (S_ISDIR(st.st_mode)) { if (UseExternalDirBuffer) { Str cmd = Sprintf("%s?dir=%s#current", DirBufferCommand, pu.file); b = loadGeneralFile(cmd->ptr, NULL, NO_REFERER, 0, NULL); if (b != NULL && b != NO_BUFFER) { copyParsedURL(&b->currentURL, &pu); b->filename = b->currentURL.real_file; } return b; } else { page = loadLocalDir(pu.real_file); t = "local:directory"; #ifdef USE_M17N charset = SystemCharset; #endif } } } break; case SCM_FTPDIR: page = loadFTPDir(&pu, &charset); t = "ftp:directory"; break; #ifdef USE_NNTP case SCM_NEWS_GROUP: page = loadNewsgroup(&pu, &charset); t = "news:group"; break; #endif case SCM_UNKNOWN: #ifdef USE_EXTERNAL_URI_LOADER tmp = searchURIMethods(&pu); if (tmp != NULL) { b = loadGeneralFile(tmp->ptr, current, referer, flag, request); if (b != NULL && b != NO_BUFFER) copyParsedURL(&b->currentURL, &pu); return b; } #endif /* FIXME: gettextize? */ disp_err_message(Sprintf("Unknown URI: %s", parsedURL2Str(&pu)->ptr)->ptr, FALSE); break; } if (page && page->length > 0) goto page_loaded; return NULL; } if (status == HTST_MISSING) { TRAP_OFF; UFclose(&f); return NULL; } /* openURL() succeeded */ if (SETJMP(AbortLoading) != 0) { /* transfer interrupted */ TRAP_OFF; if (b) discardBuffer(b); UFclose(&f); return NULL; } b = NULL; if (f.is_cgi) { /* local CGI */ searchHeader = TRUE; searchHeader_through = FALSE; } if (header_string) header_string = NULL; TRAP_ON; if (pu.scheme == SCM_HTTP || #ifdef USE_SSL pu.scheme == SCM_HTTPS || #endif /* USE_SSL */ (( #ifdef USE_GOPHER (pu.scheme == SCM_GOPHER && non_null(GOPHER_proxy)) || #endif /* USE_GOPHER */ (pu.scheme == SCM_FTP && non_null(FTP_proxy)) ) && !Do_not_use_proxy && !check_no_proxy(pu.host))) { if (fmInitialized) { term_cbreak(); /* FIXME: gettextize? */ message(Sprintf("%s contacted. Waiting for reply...", pu.host)-> ptr, 0, 0); refresh(); } if (t_buf == NULL) t_buf = newBuffer(INIT_BUFFER_WIDTH); #if 0 /* USE_SSL */ if (IStype(f.stream) == IST_SSL) { Str s = ssl_get_certificate(f.stream, pu.host); if (s == NULL) return NULL; else t_buf->ssl_certificate = s->ptr; } #endif readHeader(&f, t_buf, FALSE, &pu); if (((http_response_code >= 301 && http_response_code <= 303) || http_response_code == 307) && (p = checkHeader(t_buf, "Location:")) != NULL && checkRedirection(&pu)) { /* document moved */ /* 301: Moved Permanently */ /* 302: Found */ /* 303: See Other */ /* 307: Temporary Redirect (HTTP/1.1) */ tpath = url_encode(p, NULL, 0); request = NULL; UFclose(&f); current = New(ParsedURL); copyParsedURL(current, &pu); t_buf = newBuffer(INIT_BUFFER_WIDTH); t_buf->bufferprop |= BP_REDIRECTED; status = HTST_NORMAL; goto load_doc; } t = checkContentType(t_buf); if (t == NULL && pu.file != NULL) { if (!((http_response_code >= 400 && http_response_code <= 407) || (http_response_code >= 500 && http_response_code <= 505))) t = guessContentType(pu.file); } if (t == NULL) t = "text/plain"; if (add_auth_cookie_flag && realm && uname && pwd) { /* If authorization is required and passed */ add_auth_user_passwd(&pu, qstr_unquote(realm)->ptr, uname, pwd, 0); add_auth_cookie_flag = 0; } if ((p = checkHeader(t_buf, "WWW-Authenticate:")) != NULL && http_response_code == 401) { /* Authentication needed */ struct http_auth hauth; if (findAuthentication(&hauth, t_buf, "WWW-Authenticate:") != NULL && (realm = get_auth_param(hauth.param, "realm")) != NULL) { auth_pu = &pu; getAuthCookie(&hauth, "Authorization:", extra_header, auth_pu, &hr, request, &uname, &pwd); if (uname == NULL) { /* abort */ TRAP_OFF; goto page_loaded; } UFclose(&f); add_auth_cookie_flag = 1; status = HTST_NORMAL; goto load_doc; } } if ((p = checkHeader(t_buf, "Proxy-Authenticate:")) != NULL && http_response_code == 407) { /* Authentication needed */ struct http_auth hauth; if (findAuthentication(&hauth, t_buf, "Proxy-Authenticate:") != NULL && (realm = get_auth_param(hauth.param, "realm")) != NULL) { auth_pu = schemeToProxy(pu.scheme); getAuthCookie(&hauth, "Proxy-Authorization:", extra_header, auth_pu, &hr, request, &uname, &pwd); if (uname == NULL) { /* abort */ TRAP_OFF; goto page_loaded; } UFclose(&f); add_auth_cookie_flag = 1; status = HTST_NORMAL; add_auth_user_passwd(auth_pu, qstr_unquote(realm)->ptr, uname, pwd, 1); goto load_doc; } } /* XXX: RFC2617 3.2.3 Authentication-Info: ? */ if (status == HTST_CONNECT) { of = &f; goto load_doc; } f.modtime = mymktime(checkHeader(t_buf, "Last-Modified:")); } #ifdef USE_NNTP else if (pu.scheme == SCM_NEWS || pu.scheme == SCM_NNTP) { if (t_buf == NULL) t_buf = newBuffer(INIT_BUFFER_WIDTH); readHeader(&f, t_buf, TRUE, &pu); t = checkContentType(t_buf); if (t == NULL) t = "text/plain"; } #endif /* USE_NNTP */ #ifdef USE_GOPHER else if (pu.scheme == SCM_GOPHER) { switch (*pu.file) { case '0': t = "text/plain"; break; case '1': case 'm': page = loadGopherDir(&f, &pu, &charset); t = "gopher:directory"; TRAP_OFF; goto page_loaded; case 's': t = "audio/basic"; break; case 'g': t = "image/gif"; break; case 'h': t = "text/html"; break; } } #endif /* USE_GOPHER */ else if (pu.scheme == SCM_FTP) { check_compression(path, &f); if (f.compression != CMP_NOCOMPRESS) { char *t1 = uncompressed_file_type(pu.file, NULL); real_type = f.guess_type; #if 0 if (t1 && strncasecmp(t1, "application/", 12) == 0) { f.compression = CMP_NOCOMPRESS; t = real_type; } else #endif if (t1) t = t1; else t = real_type; } else { real_type = guessContentType(pu.file); if (real_type == NULL) real_type = "text/plain"; t = real_type; } #if 0 if (!strncasecmp(t, "application/", 12)) { char *tmpf = tmpfname(TMPF_DFL, NULL)->ptr; current_content_length = 0; if (save2tmp(f, tmpf) < 0) UFclose(&f); else { UFclose(&f); TRAP_OFF; doFileMove(tmpf, guess_save_name(t_buf, pu.file)); } return NO_BUFFER; } #endif } else if (pu.scheme == SCM_DATA) { t = f.guess_type; } else if (searchHeader) { searchHeader = SearchHeader = FALSE; if (t_buf == NULL) t_buf = newBuffer(INIT_BUFFER_WIDTH); readHeader(&f, t_buf, searchHeader_through, &pu); if (f.is_cgi && (p = checkHeader(t_buf, "Location:")) != NULL && checkRedirection(&pu)) { /* document moved */ tpath = url_encode(remove_space(p), NULL, 0); request = NULL; UFclose(&f); add_auth_cookie_flag = 0; current = New(ParsedURL); copyParsedURL(current, &pu); t_buf = newBuffer(INIT_BUFFER_WIDTH); t_buf->bufferprop |= BP_REDIRECTED; status = HTST_NORMAL; goto load_doc; } #ifdef AUTH_DEBUG if ((p = checkHeader(t_buf, "WWW-Authenticate:")) != NULL) { /* Authentication needed */ struct http_auth hauth; if (findAuthentication(&hauth, t_buf, "WWW-Authenticate:") != NULL && (realm = get_auth_param(hauth.param, "realm")) != NULL) { auth_pu = &pu; getAuthCookie(&hauth, "Authorization:", extra_header, auth_pu, &hr, request, &uname, &pwd); if (uname == NULL) { /* abort */ TRAP_OFF; goto page_loaded; } UFclose(&f); add_auth_cookie_flag = 1; status = HTST_NORMAL; goto load_doc; } } #endif /* defined(AUTH_DEBUG) */ t = checkContentType(t_buf); if (t == NULL) t = "text/plain"; } else if (DefaultType) { t = DefaultType; DefaultType = NULL; } else { t = guessContentType(pu.file); if (t == NULL) t = "text/plain"; real_type = t; if (f.guess_type) t = f.guess_type; } /* XXX: can we use guess_type to give the type to loadHTMLstream * to support default utf8 encoding for XHTML here? */ f.guess_type = t; page_loaded: if (page) { FILE *src; #ifdef USE_IMAGE if (image_source) return NULL; #endif tmp = tmpfname(TMPF_SRC, ".html"); src = fopen(tmp->ptr, "w"); if (src) { Str s; s = wc_Str_conv_strict(page, InnerCharset, charset); Strfputs(s, src); fclose(src); } if (do_download) { char *file; if (!src) return NULL; file = guess_filename(pu.file); #ifdef USE_GOPHER if (f.scheme == SCM_GOPHER) file = Sprintf("%s.html", file)->ptr; #endif #ifdef USE_NNTP if (f.scheme == SCM_NEWS_GROUP) file = Sprintf("%s.html", file)->ptr; #endif doFileMove(tmp->ptr, file); return NO_BUFFER; } b = loadHTMLString(page); if (b) { copyParsedURL(&b->currentURL, &pu); b->real_scheme = pu.scheme; b->real_type = t; if (src) b->sourcefile = tmp->ptr; #ifdef USE_M17N b->document_charset = charset; #endif } return b; } if (real_type == NULL) real_type = t; proc = loadBuffer; current_content_length = 0; if ((p = checkHeader(t_buf, "Content-Length:")) != NULL) current_content_length = strtoclen(p); if (do_download) { /* download only */ char *file; TRAP_OFF; if (DecodeCTE && IStype(f.stream) != IST_ENCODED) f.stream = newEncodedStream(f.stream, f.encoding); if (pu.scheme == SCM_LOCAL) { struct stat st; if (PreserveTimestamp && !stat(pu.real_file, &st)) f.modtime = st.st_mtime; file = conv_from_system(guess_save_name(NULL, pu.real_file)); } else file = guess_save_name(t_buf, pu.file); if (doFileSave(f, file) == 0) UFhalfclose(&f); else UFclose(&f); return NO_BUFFER; } if ((f.content_encoding != CMP_NOCOMPRESS) && AutoUncompress && !(w3m_dump & DUMP_EXTRA)) { uncompress_stream(&f, &pu.real_file); } else if (f.compression != CMP_NOCOMPRESS) { if (!(w3m_dump & DUMP_SOURCE) && (w3m_dump & ~DUMP_FRAME || is_text_type(t) || searchExtViewer(t))) { if (t_buf == NULL) t_buf = newBuffer(INIT_BUFFER_WIDTH); uncompress_stream(&f, &t_buf->sourcefile); uncompressed_file_type(pu.file, &f.ext); } else { t = compress_application_type(f.compression); f.compression = CMP_NOCOMPRESS; } } #ifdef USE_IMAGE if (image_source) { Buffer *b = NULL; if (IStype(f.stream) != IST_ENCODED) f.stream = newEncodedStream(f.stream, f.encoding); if (save2tmp(f, image_source) == 0) { b = newBuffer(INIT_BUFFER_WIDTH); b->sourcefile = image_source; b->real_type = t; } UFclose(&f); TRAP_OFF; return b; } #endif if (is_html_type(t)) proc = loadHTMLBuffer; else if (is_plain_text_type(t)) proc = loadBuffer; #ifdef USE_IMAGE else if (activeImage && displayImage && !useExtImageViewer && !(w3m_dump & ~DUMP_FRAME) && !strncasecmp(t, "image/", 6)) proc = loadImageBuffer; #endif else if (w3m_backend) ; else if (!(w3m_dump & ~DUMP_FRAME) || is_dump_text_type(t)) { if (!do_download && searchExtViewer(t) != NULL) { proc = DO_EXTERNAL; } else { TRAP_OFF; if (pu.scheme == SCM_LOCAL) { UFclose(&f); _doFileCopy(pu.real_file, conv_from_system(guess_save_name (NULL, pu.real_file)), TRUE); } else { if (DecodeCTE && IStype(f.stream) != IST_ENCODED) f.stream = newEncodedStream(f.stream, f.encoding); if (doFileSave(f, guess_save_name(t_buf, pu.file)) == 0) UFhalfclose(&f); else UFclose(&f); } return NO_BUFFER; } } else if (w3m_dump & DUMP_FRAME) return NULL; if (t_buf == NULL) t_buf = newBuffer(INIT_BUFFER_WIDTH); copyParsedURL(&t_buf->currentURL, &pu); t_buf->filename = pu.real_file ? pu.real_file : pu.file ? conv_to_system(pu.file) : NULL; if (flag & RG_FRAME) { t_buf->bufferprop |= BP_FRAME; } #ifdef USE_SSL t_buf->ssl_certificate = f.ssl_certificate; #endif frame_source = flag & RG_FRAME_SRC; if (proc == DO_EXTERNAL) { b = doExternal(f, t, t_buf); } else { b = loadSomething(&f, proc, t_buf); } UFclose(&f); frame_source = 0; if (b && b != NO_BUFFER) { b->real_scheme = f.scheme; b->real_type = real_type; if (w3m_backend) b->type = allocStr(t, -1); if (pu.label) { if (proc == loadHTMLBuffer) { Anchor *a; a = searchURLLabel(b, pu.label); if (a != NULL) { gotoLine(b, a->start.line); if (label_topline) b->topLine = lineSkip(b, b->topLine, b->currentLine->linenumber - b->topLine->linenumber, FALSE); b->pos = a->start.pos; arrangeCursor(b); } } else { /* plain text */ int l = atoi(pu.label); gotoRealLine(b, l); b->pos = 0; arrangeCursor(b); } } } if (header_string) header_string = NULL; #ifdef USE_NNTP if (b && b != NO_BUFFER && (f.scheme == SCM_NNTP || f.scheme == SCM_NEWS)) reAnchorNewsheader(b); #endif if (b && b != NO_BUFFER) preFormUpdateBuffer(b); TRAP_OFF; return b; } #define TAG_IS(s,tag,len)\ (strncasecmp(s,tag,len)==0&&(s[len] == '>' || IS_SPACE((int)s[len]))) static char * has_hidden_link(struct readbuffer *obuf, int cmd) { Str line = obuf->line; struct link_stack *p; if (Strlastchar(line) != '>') return NULL; for (p = link_stack; p; p = p->next) if (p->cmd == cmd) break; if (!p) return NULL; if (obuf->pos == p->pos) return line->ptr + p->offset; return NULL; } static void push_link(int cmd, int offset, int pos) { struct link_stack *p; p = New(struct link_stack); p->cmd = cmd; p->offset = offset; p->pos = pos; p->next = link_stack; link_stack = p; } static int is_period_char(unsigned char *ch) { switch (*ch) { case ',': case '.': case ':': case ';': case '?': case '!': case ')': case ']': case '}': case '>': return 1; default: return 0; } } static int is_beginning_char(unsigned char *ch) { switch (*ch) { case '(': case '[': case '{': case '`': case '<': return 1; default: return 0; } } static int is_word_char(unsigned char *ch) { Lineprop ctype = get_mctype(ch); #ifdef USE_M17N if (ctype & (PC_CTRL | PC_KANJI | PC_UNKNOWN)) return 0; if (ctype & (PC_WCHAR1 | PC_WCHAR2)) return 1; #else if (ctype == PC_CTRL) return 0; #endif if (IS_ALNUM(*ch)) return 1; switch (*ch) { case ',': case '.': case ':': case '\"': /* " */ case '\'': case '$': case '%': case '*': case '+': case '-': case '@': case '~': case '_': return 1; } #ifdef USE_M17N if (*ch == NBSP_CODE) return 1; #else if (*ch == TIMES_CODE || *ch == DIVIDE_CODE || *ch == ANSP_CODE) return 0; if (*ch >= AGRAVE_CODE || *ch == NBSP_CODE) return 1; #endif return 0; } #ifdef USE_M17N static int is_combining_char(unsigned char *ch) { Lineprop ctype = get_mctype(ch); if (ctype & PC_WCHAR2) return 1; return 0; } #endif int is_boundary(unsigned char *ch1, unsigned char *ch2) { if (!*ch1 || !*ch2) return 1; if (*ch1 == ' ' && *ch2 == ' ') return 0; if (*ch1 != ' ' && is_period_char(ch2)) return 0; if (*ch2 != ' ' && is_beginning_char(ch1)) return 0; #ifdef USE_M17N if (is_combining_char(ch2)) return 0; #endif if (is_word_char(ch1) && is_word_char(ch2)) return 0; return 1; } static void set_breakpoint(struct readbuffer *obuf, int tag_length) { obuf->bp.len = obuf->line->length; obuf->bp.pos = obuf->pos; obuf->bp.tlen = tag_length; obuf->bp.flag = obuf->flag; #ifdef FORMAT_NICE obuf->bp.flag &= ~RB_FILL; #endif /* FORMAT_NICE */ obuf->bp.top_margin = obuf->top_margin; obuf->bp.bottom_margin = obuf->bottom_margin; if (!obuf->bp.init_flag) return; bcopy((void *)&obuf->anchor, (void *)&obuf->bp.anchor, sizeof(obuf->anchor)); obuf->bp.img_alt = obuf->img_alt; obuf->bp.input_alt = obuf->input_alt; obuf->bp.in_bold = obuf->in_bold; obuf->bp.in_italic = obuf->in_italic; obuf->bp.in_under = obuf->in_under; obuf->bp.in_strike = obuf->in_strike; obuf->bp.in_ins = obuf->in_ins; obuf->bp.nobr_level = obuf->nobr_level; obuf->bp.prev_ctype = obuf->prev_ctype; obuf->bp.init_flag = 0; } static void back_to_breakpoint(struct readbuffer *obuf) { obuf->flag = obuf->bp.flag; bcopy((void *)&obuf->bp.anchor, (void *)&obuf->anchor, sizeof(obuf->anchor)); obuf->img_alt = obuf->bp.img_alt; obuf->input_alt = obuf->bp.input_alt; obuf->in_bold = obuf->bp.in_bold; obuf->in_italic = obuf->bp.in_italic; obuf->in_under = obuf->bp.in_under; obuf->in_strike = obuf->bp.in_strike; obuf->in_ins = obuf->bp.in_ins; obuf->prev_ctype = obuf->bp.prev_ctype; obuf->pos = obuf->bp.pos; obuf->top_margin = obuf->bp.top_margin; obuf->bottom_margin = obuf->bp.bottom_margin; if (obuf->flag & RB_NOBR) obuf->nobr_level = obuf->bp.nobr_level; } static void append_tags(struct readbuffer *obuf) { int i; int len = obuf->line->length; int set_bp = 0; for (i = 0; i < obuf->tag_sp; i++) { switch (obuf->tag_stack[i]->cmd) { case HTML_A: case HTML_IMG_ALT: case HTML_B: case HTML_U: case HTML_I: case HTML_S: push_link(obuf->tag_stack[i]->cmd, obuf->line->length, obuf->pos); break; } Strcat_charp(obuf->line, obuf->tag_stack[i]->cmdname); switch (obuf->tag_stack[i]->cmd) { case HTML_NOBR: if (obuf->nobr_level > 1) break; case HTML_WBR: set_bp = 1; break; } } obuf->tag_sp = 0; if (set_bp) set_breakpoint(obuf, obuf->line->length - len); } static void push_tag(struct readbuffer *obuf, char *cmdname, int cmd) { obuf->tag_stack[obuf->tag_sp] = New(struct cmdtable); obuf->tag_stack[obuf->tag_sp]->cmdname = allocStr(cmdname, -1); obuf->tag_stack[obuf->tag_sp]->cmd = cmd; obuf->tag_sp++; if (obuf->tag_sp >= TAG_STACK_SIZE || obuf->flag & (RB_SPECIAL & ~RB_NOBR)) append_tags(obuf); } static void push_nchars(struct readbuffer *obuf, int width, char *str, int len, Lineprop mode) { append_tags(obuf); Strcat_charp_n(obuf->line, str, len); obuf->pos += width; if (width > 0) { set_prevchar(obuf->prevchar, str, len); obuf->prev_ctype = mode; } obuf->flag |= RB_NFLUSHED; } #define push_charp(obuf, width, str, mode)\ push_nchars(obuf, width, str, strlen(str), mode) #define push_str(obuf, width, str, mode)\ push_nchars(obuf, width, str->ptr, str->length, mode) static void check_breakpoint(struct readbuffer *obuf, int pre_mode, char *ch) { int tlen, len = obuf->line->length; append_tags(obuf); if (pre_mode) return; tlen = obuf->line->length - len; if (tlen > 0 || is_boundary((unsigned char *)obuf->prevchar->ptr, (unsigned char *)ch)) set_breakpoint(obuf, tlen); } static void push_char(struct readbuffer *obuf, int pre_mode, char ch) { check_breakpoint(obuf, pre_mode, &ch); Strcat_char(obuf->line, ch); obuf->pos++; set_prevchar(obuf->prevchar, &ch, 1); if (ch != ' ') obuf->prev_ctype = PC_ASCII; obuf->flag |= RB_NFLUSHED; } #define PUSH(c) push_char(obuf, obuf->flag & RB_SPECIAL, c) static void push_spaces(struct readbuffer *obuf, int pre_mode, int width) { int i; if (width <= 0) return; check_breakpoint(obuf, pre_mode, " "); for (i = 0; i < width; i++) Strcat_char(obuf->line, ' '); obuf->pos += width; set_space_to_prevchar(obuf->prevchar); obuf->flag |= RB_NFLUSHED; } static void proc_mchar(struct readbuffer *obuf, int pre_mode, int width, char **str, Lineprop mode) { check_breakpoint(obuf, pre_mode, *str); obuf->pos += width; Strcat_charp_n(obuf->line, *str, get_mclen(*str)); if (width > 0) { set_prevchar(obuf->prevchar, *str, 1); if (**str != ' ') obuf->prev_ctype = mode; } (*str) += get_mclen(*str); obuf->flag |= RB_NFLUSHED; } void push_render_image(Str str, int width, int limit, struct html_feed_environ *h_env) { struct readbuffer *obuf = h_env->obuf; int indent = h_env->envs[h_env->envc].indent; push_spaces(obuf, 1, (limit - width) / 2); push_str(obuf, width, str, PC_ASCII); push_spaces(obuf, 1, (limit - width + 1) / 2); if (width > 0) flushline(h_env, obuf, indent, 0, h_env->limit); } static int sloppy_parse_line(char **str) { if (**str == '<') { while (**str && **str != '>') (*str)++; if (**str == '>') (*str)++; return 1; } else { while (**str && **str != '<') (*str)++; return 0; } } static void passthrough(struct readbuffer *obuf, char *str, int back) { int cmd; Str tok = Strnew(); char *str_bak; if (back) { Str str_save = Strnew_charp(str); Strshrink(obuf->line, obuf->line->ptr + obuf->line->length - str); str = str_save->ptr; } while (*str) { str_bak = str; if (sloppy_parse_line(&str)) { char *q = str_bak; cmd = gethtmlcmd(&q); if (back) { struct link_stack *p; for (p = link_stack; p; p = p->next) { if (p->cmd == cmd) { link_stack = p->next; break; } } back = 0; } else { Strcat_charp_n(tok, str_bak, str - str_bak); push_tag(obuf, tok->ptr, cmd); Strclear(tok); } } else { push_nchars(obuf, 0, str_bak, str - str_bak, obuf->prev_ctype); } } } #if 0 int is_blank_line(char *line, int indent) { int i, is_blank = 0; for (i = 0; i < indent; i++) { if (line[i] == '\0') { is_blank = 1; } else if (line[i] != ' ') { break; } } if (i == indent && line[i] == '\0') is_blank = 1; return is_blank; } #endif void fillline(struct readbuffer *obuf, int indent) { push_spaces(obuf, 1, indent - obuf->pos); obuf->flag &= ~RB_NFLUSHED; } void flushline(struct html_feed_environ *h_env, struct readbuffer *obuf, int indent, int force, int width) { TextLineList *buf = h_env->buf; FILE *f = h_env->f; Str line = obuf->line, pass = NULL; char *hidden_anchor = NULL, *hidden_img = NULL, *hidden_bold = NULL, *hidden_under = NULL, *hidden_italic = NULL, *hidden_strike = NULL, *hidden_ins = NULL, *hidden_input = NULL, *hidden = NULL; #ifdef DEBUG if (w3m_debug) { FILE *df = fopen("zzzproc1", "a"); fprintf(df, "flushline(%s,%d,%d,%d)\n", obuf->line->ptr, indent, force, width); if (buf) { TextLineListItem *p; for (p = buf->first; p; p = p->next) { fprintf(df, "buf=\"%s\"\n", p->ptr->line->ptr); } } fclose(df); } #endif if (!(obuf->flag & (RB_SPECIAL & ~RB_NOBR)) && Strlastchar(line) == ' ') { Strshrink(line, 1); obuf->pos--; } append_tags(obuf); if (obuf->anchor.url) hidden = hidden_anchor = has_hidden_link(obuf, HTML_A); if (obuf->img_alt) { if ((hidden_img = has_hidden_link(obuf, HTML_IMG_ALT)) != NULL) { if (!hidden || hidden_img < hidden) hidden = hidden_img; } } if (obuf->input_alt.in) { if ((hidden_input = has_hidden_link(obuf, HTML_INPUT_ALT)) != NULL) { if (!hidden || hidden_input < hidden) hidden = hidden_input; } } if (obuf->in_bold) { if ((hidden_bold = has_hidden_link(obuf, HTML_B)) != NULL) { if (!hidden || hidden_bold < hidden) hidden = hidden_bold; } } if (obuf->in_italic) { if ((hidden_italic = has_hidden_link(obuf, HTML_I)) != NULL) { if (!hidden || hidden_italic < hidden) hidden = hidden_italic; } } if (obuf->in_under) { if ((hidden_under = has_hidden_link(obuf, HTML_U)) != NULL) { if (!hidden || hidden_under < hidden) hidden = hidden_under; } } if (obuf->in_strike) { if ((hidden_strike = has_hidden_link(obuf, HTML_S)) != NULL) { if (!hidden || hidden_strike < hidden) hidden = hidden_strike; } } if (obuf->in_ins) { if ((hidden_ins = has_hidden_link(obuf, HTML_INS)) != NULL) { if (!hidden || hidden_ins < hidden) hidden = hidden_ins; } } if (hidden) { pass = Strnew_charp(hidden); Strshrink(line, line->ptr + line->length - hidden); } if (!(obuf->flag & (RB_SPECIAL & ~RB_NOBR)) && obuf->pos > width) { char *tp = &line->ptr[obuf->bp.len - obuf->bp.tlen]; char *ep = &line->ptr[line->length]; if (obuf->bp.pos == obuf->pos && tp <= ep && tp > line->ptr && tp[-1] == ' ') { bcopy(tp, tp - 1, ep - tp + 1); line->length--; obuf->pos--; } } if (obuf->anchor.url && !hidden_anchor) Strcat_charp(line, "</a>"); if (obuf->img_alt && !hidden_img) Strcat_charp(line, "</img_alt>"); if (obuf->input_alt.in && !hidden_input) Strcat_charp(line, "</input_alt>"); if (obuf->in_bold && !hidden_bold) Strcat_charp(line, "</b>"); if (obuf->in_italic && !hidden_italic) Strcat_charp(line, "</i>"); if (obuf->in_under && !hidden_under) Strcat_charp(line, "</u>"); if (obuf->in_strike && !hidden_strike) Strcat_charp(line, "</s>"); if (obuf->in_ins && !hidden_ins) Strcat_charp(line, "</ins>"); if (obuf->top_margin > 0) { int i; struct html_feed_environ h; struct readbuffer o; struct environment e[1]; init_henv(&h, &o, e, 1, NULL, width, indent); o.line = Strnew_size(width + 20); o.pos = obuf->pos; o.flag = obuf->flag; o.top_margin = -1; o.bottom_margin = -1; Strcat_charp(o.line, "<pre_int>"); for (i = 0; i < o.pos; i++) Strcat_char(o.line, ' '); Strcat_charp(o.line, "</pre_int>"); for (i = 0; i < obuf->top_margin; i++) flushline(h_env, &o, indent, force, width); } if (force == 1 || obuf->flag & RB_NFLUSHED) { TextLine *lbuf = newTextLine(line, obuf->pos); if (RB_GET_ALIGN(obuf) == RB_CENTER) { align(lbuf, width, ALIGN_CENTER); } else if (RB_GET_ALIGN(obuf) == RB_RIGHT) { align(lbuf, width, ALIGN_RIGHT); } else if (RB_GET_ALIGN(obuf) == RB_LEFT && obuf->flag & RB_INTABLE) { align(lbuf, width, ALIGN_LEFT); } #ifdef FORMAT_NICE else if (obuf->flag & RB_FILL) { char *p; int rest, rrest; int nspace, d, i; rest = width - get_Str_strwidth(line); if (rest > 1) { nspace = 0; for (p = line->ptr + indent; *p; p++) { if (*p == ' ') nspace++; } if (nspace > 0) { int indent_here = 0; d = rest / nspace; p = line->ptr; while (IS_SPACE(*p)) { p++; indent_here++; } rrest = rest - d * nspace; line = Strnew_size(width + 1); for (i = 0; i < indent_here; i++) Strcat_char(line, ' '); for (; *p; p++) { Strcat_char(line, *p); if (*p == ' ') { for (i = 0; i < d; i++) Strcat_char(line, ' '); if (rrest > 0) { Strcat_char(line, ' '); rrest--; } } } lbuf = newTextLine(line, width); } } } #endif /* FORMAT_NICE */ #ifdef TABLE_DEBUG if (w3m_debug) { FILE *f = fopen("zzzproc1", "a"); fprintf(f, "pos=%d,%d, maxlimit=%d\n", visible_length(lbuf->line->ptr), lbuf->pos, h_env->maxlimit); fclose(f); } #endif if (lbuf->pos > h_env->maxlimit) h_env->maxlimit = lbuf->pos; if (buf) pushTextLine(buf, lbuf); else if (f) { Strfputs(Str_conv_to_halfdump(lbuf->line), f); fputc('\n', f); } if (obuf->flag & RB_SPECIAL || obuf->flag & RB_NFLUSHED) h_env->blank_lines = 0; else h_env->blank_lines++; } else { char *p = line->ptr, *q; Str tmp = Strnew(), tmp2 = Strnew(); #define APPEND(str) \ if (buf) \ appendTextLine(buf,(str),0); \ else if (f) \ Strfputs((str),f) while (*p) { q = p; if (sloppy_parse_line(&p)) { Strcat_charp_n(tmp, q, p - q); if (force == 2) { APPEND(tmp); } else Strcat(tmp2, tmp); Strclear(tmp); } } if (force == 2) { if (pass) { APPEND(pass); } pass = NULL; } else { if (pass) Strcat(tmp2, pass); pass = tmp2; } } if (obuf->bottom_margin > 0) { int i; struct html_feed_environ h; struct readbuffer o; struct environment e[1]; init_henv(&h, &o, e, 1, NULL, width, indent); o.line = Strnew_size(width + 20); o.pos = obuf->pos; o.flag = obuf->flag; o.top_margin = -1; o.bottom_margin = -1; Strcat_charp(o.line, "<pre_int>"); for (i = 0; i < o.pos; i++) Strcat_char(o.line, ' '); Strcat_charp(o.line, "</pre_int>"); for (i = 0; i < obuf->bottom_margin; i++) flushline(h_env, &o, indent, force, width); } if (obuf->top_margin < 0 || obuf->bottom_margin < 0) return; obuf->line = Strnew_size(256); obuf->pos = 0; obuf->top_margin = 0; obuf->bottom_margin = 0; set_space_to_prevchar(obuf->prevchar); obuf->bp.init_flag = 1; obuf->flag &= ~RB_NFLUSHED; set_breakpoint(obuf, 0); obuf->prev_ctype = PC_ASCII; link_stack = NULL; fillline(obuf, indent); if (pass) passthrough(obuf, pass->ptr, 0); if (!hidden_anchor && obuf->anchor.url) { Str tmp; if (obuf->anchor.hseq > 0) obuf->anchor.hseq = -obuf->anchor.hseq; tmp = Sprintf("<A HSEQ=\"%d\" HREF=\"", obuf->anchor.hseq); Strcat_charp(tmp, html_quote(obuf->anchor.url)); if (obuf->anchor.target) { Strcat_charp(tmp, "\" TARGET=\""); Strcat_charp(tmp, html_quote(obuf->anchor.target)); } if (obuf->anchor.referer) { Strcat_charp(tmp, "\" REFERER=\""); Strcat_charp(tmp, html_quote(obuf->anchor.referer)); } if (obuf->anchor.title) { Strcat_charp(tmp, "\" TITLE=\""); Strcat_charp(tmp, html_quote(obuf->anchor.title)); } if (obuf->anchor.accesskey) { char *c = html_quote_char(obuf->anchor.accesskey); Strcat_charp(tmp, "\" ACCESSKEY=\""); if (c) Strcat_charp(tmp, c); else Strcat_char(tmp, obuf->anchor.accesskey); } Strcat_charp(tmp, "\">"); push_tag(obuf, tmp->ptr, HTML_A); } if (!hidden_img && obuf->img_alt) { Str tmp = Strnew_charp("<IMG_ALT SRC=\""); Strcat_charp(tmp, html_quote(obuf->img_alt->ptr)); Strcat_charp(tmp, "\">"); push_tag(obuf, tmp->ptr, HTML_IMG_ALT); } if (!hidden_input && obuf->input_alt.in) { Str tmp; if (obuf->input_alt.hseq > 0) obuf->input_alt.hseq = - obuf->input_alt.hseq; tmp = Sprintf("<INPUT_ALT hseq=\"%d\" fid=\"%d\" name=\"%s\" type=\"%s\" value=\"%s\">", obuf->input_alt.hseq, obuf->input_alt.fid, obuf->input_alt.name ? obuf->input_alt.name->ptr : "", obuf->input_alt.type ? obuf->input_alt.type->ptr : "", obuf->input_alt.value ? obuf->input_alt.value->ptr : ""); push_tag(obuf, tmp->ptr, HTML_INPUT_ALT); } if (!hidden_bold && obuf->in_bold) push_tag(obuf, "<B>", HTML_B); if (!hidden_italic && obuf->in_italic) push_tag(obuf, "<I>", HTML_I); if (!hidden_under && obuf->in_under) push_tag(obuf, "<U>", HTML_U); if (!hidden_strike && obuf->in_strike) push_tag(obuf, "<S>", HTML_S); if (!hidden_ins && obuf->in_ins) push_tag(obuf, "<INS>", HTML_INS); } void do_blankline(struct html_feed_environ *h_env, struct readbuffer *obuf, int indent, int indent_incr, int width) { if (h_env->blank_lines == 0) flushline(h_env, obuf, indent, 1, width); } void purgeline(struct html_feed_environ *h_env) { char *p, *q; Str tmp; if (h_env->buf == NULL || h_env->blank_lines == 0) return; p = rpopTextLine(h_env->buf)->line->ptr; tmp = Strnew(); while (*p) { q = p; if (sloppy_parse_line(&p)) { Strcat_charp_n(tmp, q, p - q); } } appendTextLine(h_env->buf, tmp, 0); h_env->blank_lines--; } static int close_effect0(struct readbuffer *obuf, int cmd) { int i; char *p; for (i = obuf->tag_sp - 1; i >= 0; i--) { if (obuf->tag_stack[i]->cmd == cmd) break; } if (i >= 0) { obuf->tag_sp--; bcopy(&obuf->tag_stack[i + 1], &obuf->tag_stack[i], (obuf->tag_sp - i) * sizeof(struct cmdtable *)); return 1; } else if ((p = has_hidden_link(obuf, cmd)) != NULL) { passthrough(obuf, p, 1); return 1; } return 0; } static void close_anchor(struct html_feed_environ *h_env, struct readbuffer *obuf) { if (obuf->anchor.url) { int i; char *p = NULL; int is_erased = 0; for (i = obuf->tag_sp - 1; i >= 0; i--) { if (obuf->tag_stack[i]->cmd == HTML_A) break; } if (i < 0 && obuf->anchor.hseq > 0 && Strlastchar(obuf->line) == ' ') { Strshrink(obuf->line, 1); obuf->pos--; is_erased = 1; } if (i >= 0 || (p = has_hidden_link(obuf, HTML_A))) { if (obuf->anchor.hseq > 0) { HTMLlineproc1(ANSP, h_env); set_space_to_prevchar(obuf->prevchar); } else { if (i >= 0) { obuf->tag_sp--; bcopy(&obuf->tag_stack[i + 1], &obuf->tag_stack[i], (obuf->tag_sp - i) * sizeof(struct cmdtable *)); } else { passthrough(obuf, p, 1); } bzero((void *)&obuf->anchor, sizeof(obuf->anchor)); return; } is_erased = 0; } if (is_erased) { Strcat_char(obuf->line, ' '); obuf->pos++; } push_tag(obuf, "</a>", HTML_N_A); } bzero((void *)&obuf->anchor, sizeof(obuf->anchor)); } void save_fonteffect(struct html_feed_environ *h_env, struct readbuffer *obuf) { if (obuf->fontstat_sp < FONT_STACK_SIZE) bcopy(obuf->fontstat, obuf->fontstat_stack[obuf->fontstat_sp], FONTSTAT_SIZE); obuf->fontstat_sp++; if (obuf->in_bold) push_tag(obuf, "</b>", HTML_N_B); if (obuf->in_italic) push_tag(obuf, "</i>", HTML_N_I); if (obuf->in_under) push_tag(obuf, "</u>", HTML_N_U); if (obuf->in_strike) push_tag(obuf, "</s>", HTML_N_S); if (obuf->in_ins) push_tag(obuf, "</ins>", HTML_N_INS); bzero(obuf->fontstat, FONTSTAT_SIZE); } void restore_fonteffect(struct html_feed_environ *h_env, struct readbuffer *obuf) { if (obuf->fontstat_sp > 0) obuf->fontstat_sp--; if (obuf->fontstat_sp < FONT_STACK_SIZE) bcopy(obuf->fontstat_stack[obuf->fontstat_sp], obuf->fontstat, FONTSTAT_SIZE); if (obuf->in_bold) push_tag(obuf, "<b>", HTML_B); if (obuf->in_italic) push_tag(obuf, "<i>", HTML_I); if (obuf->in_under) push_tag(obuf, "<u>", HTML_U); if (obuf->in_strike) push_tag(obuf, "<s>", HTML_S); if (obuf->in_ins) push_tag(obuf, "<ins>", HTML_INS); } static Str process_title(struct parsed_tag *tag) { cur_title = Strnew(); return NULL; } static Str process_n_title(struct parsed_tag *tag) { Str tmp; if (!cur_title) return NULL; Strremovefirstspaces(cur_title); Strremovetrailingspaces(cur_title); tmp = Strnew_m_charp("<title_alt title=\"", html_quote(cur_title->ptr), "\">", NULL); cur_title = NULL; return tmp; } static void feed_title(char *str) { if (!cur_title) return; while (*str) { if (*str == '&') Strcat_charp(cur_title, getescapecmd(&str)); else if (*str == '\n' || *str == '\r') { Strcat_char(cur_title, ' '); str++; } else Strcat_char(cur_title, *(str++)); } } Str process_img(struct parsed_tag *tag, int width) { char *p, *q, *r, *r2 = NULL, *s, *t; #ifdef USE_IMAGE int w, i, nw, ni = 1, n, w0 = -1, i0 = -1; int align, xoffset, yoffset, top, bottom, ismap = 0; int use_image = activeImage && displayImage; #else int w, i, nw, n; #endif int pre_int = FALSE, ext_pre_int = FALSE; Str tmp = Strnew(); if (!parsedtag_get_value(tag, ATTR_SRC, &p)) return tmp; p = url_encode(remove_space(p), cur_baseURL, cur_document_charset); q = NULL; parsedtag_get_value(tag, ATTR_ALT, &q); if (!pseudoInlines && (q == NULL || (*q == '\0' && ignore_null_img_alt))) return tmp; t = q; parsedtag_get_value(tag, ATTR_TITLE, &t); w = -1; if (parsedtag_get_value(tag, ATTR_WIDTH, &w)) { if (w < 0) { if (width > 0) w = (int)(-width * pixel_per_char * w / 100 + 0.5); else w = -1; } #ifdef USE_IMAGE if (use_image) { if (w > 0) { w = (int)(w * image_scale / 100 + 0.5); if (w == 0) w = 1; else if (w > MAX_IMAGE_SIZE) w = MAX_IMAGE_SIZE; } } #endif } #ifdef USE_IMAGE if (use_image) { i = -1; if (parsedtag_get_value(tag, ATTR_HEIGHT, &i)) { if (i > 0) { i = (int)(i * image_scale / 100 + 0.5); if (i == 0) i = 1; else if (i > MAX_IMAGE_SIZE) i = MAX_IMAGE_SIZE; } else { i = -1; } } align = -1; parsedtag_get_value(tag, ATTR_ALIGN, &align); ismap = 0; if (parsedtag_exists(tag, ATTR_ISMAP)) ismap = 1; } else #endif parsedtag_get_value(tag, ATTR_HEIGHT, &i); r = NULL; parsedtag_get_value(tag, ATTR_USEMAP, &r); if (parsedtag_exists(tag, ATTR_PRE_INT)) ext_pre_int = TRUE; tmp = Strnew_size(128); #ifdef USE_IMAGE if (use_image) { switch (align) { case ALIGN_LEFT: Strcat_charp(tmp, "<div_int align=left>"); break; case ALIGN_CENTER: Strcat_charp(tmp, "<div_int align=center>"); break; case ALIGN_RIGHT: Strcat_charp(tmp, "<div_int align=right>"); break; } } #endif if (r) { Str tmp2; r2 = strchr(r, '#'); s = "<form_int method=internal action=map>"; tmp2 = process_form(parse_tag(&s, TRUE)); if (tmp2) Strcat(tmp, tmp2); Strcat(tmp, Sprintf("<input_alt fid=\"%d\" " "type=hidden name=link value=\"", cur_form_id)); Strcat_charp(tmp, html_quote((r2) ? r2 + 1 : r)); Strcat(tmp, Sprintf("\"><input_alt hseq=\"%d\" fid=\"%d\" " "type=submit no_effect=true>", cur_hseq++, cur_form_id)); } #ifdef USE_IMAGE if (use_image) { w0 = w; i0 = i; if (w < 0 || i < 0) { Image image; ParsedURL u; parseURL2(p, &u, cur_baseURL); image.url = parsedURL2Str(&u)->ptr; if (!uncompressed_file_type(u.file, &image.ext)) image.ext = filename_extension(u.file, TRUE); image.cache = NULL; image.width = w; image.height = i; image.cache = getImage(&image, cur_baseURL, IMG_FLAG_SKIP); if (image.cache && image.cache->width > 0 && image.cache->height > 0) { w = w0 = image.cache->width; i = i0 = image.cache->height; } if (w < 0) w = 8 * pixel_per_char; if (i < 0) i = pixel_per_line; } if (enable_inline_image) { nw = (w > 1) ? ((w - 1) / pixel_per_char_i + 1) : 1 ; ni = (i > 1) ? ((i - 1) / pixel_per_line_i + 1) : 1 ; } else { nw = (w > 3) ? (int)((w - 3) / pixel_per_char + 1) : 1; ni = (i > 3) ? (int)((i - 3) / pixel_per_line + 1) : 1; } Strcat(tmp, Sprintf("<pre_int><img_alt hseq=\"%d\" src=\"", cur_iseq++)); pre_int = TRUE; } else #endif { if (w < 0) w = 12 * pixel_per_char; nw = w ? (int)((w - 1) / pixel_per_char + 1) : 1; if (r) { Strcat_charp(tmp, "<pre_int>"); pre_int = TRUE; } Strcat_charp(tmp, "<img_alt src=\""); } Strcat_charp(tmp, html_quote(p)); Strcat_charp(tmp, "\""); if (t) { Strcat_charp(tmp, " title=\""); Strcat_charp(tmp, html_quote(t)); Strcat_charp(tmp, "\""); } #ifdef USE_IMAGE if (use_image) { if (w0 >= 0) Strcat(tmp, Sprintf(" width=%d", w0)); if (i0 >= 0) Strcat(tmp, Sprintf(" height=%d", i0)); switch (align) { case ALIGN_MIDDLE: if (!enable_inline_image) { top = ni / 2; bottom = top; if (top * 2 == ni) yoffset = (int)(((ni + 1) * pixel_per_line - i) / 2); else yoffset = (int)((ni * pixel_per_line - i) / 2); break; } case ALIGN_TOP: top = 0; bottom = ni - 1; yoffset = 0; break; case ALIGN_BOTTOM: top = ni - 1; bottom = 0; yoffset = (int)(ni * pixel_per_line - i); break; default: top = ni - 1; bottom = 0; if (ni == 1 && ni * pixel_per_line > i) yoffset = 0; else { yoffset = (int)(ni * pixel_per_line - i); if (yoffset <= -2) yoffset++; } break; } if (enable_inline_image) xoffset = 0; else xoffset = (int)((nw * pixel_per_char - w) / 2); if (xoffset) Strcat(tmp, Sprintf(" xoffset=%d", xoffset)); if (yoffset) Strcat(tmp, Sprintf(" yoffset=%d", yoffset)); if (top) Strcat(tmp, Sprintf(" top_margin=%d", top)); if (bottom) Strcat(tmp, Sprintf(" bottom_margin=%d", bottom)); if (r) { Strcat_charp(tmp, " usemap=\""); Strcat_charp(tmp, html_quote((r2) ? r2 + 1 : r)); Strcat_charp(tmp, "\""); } if (ismap) Strcat_charp(tmp, " ismap"); } #endif Strcat_charp(tmp, ">"); if (q != NULL && *q == '\0' && ignore_null_img_alt) q = NULL; if (q != NULL) { n = get_strwidth(q); #ifdef USE_IMAGE if (use_image) { if (n > nw) { char *r; for (r = q, n = 0; r; r += get_mclen(r), n += get_mcwidth(r)) { if (n + get_mcwidth(r) > nw) break; } Strcat_charp(tmp, html_quote(Strnew_charp_n(q, r - q)->ptr)); } else Strcat_charp(tmp, html_quote(q)); } else #endif Strcat_charp(tmp, html_quote(q)); goto img_end; } if (w > 0 && i > 0) { /* guess what the image is! */ if (w < 32 && i < 48) { /* must be an icon or space */ n = 1; if (strcasestr(p, "space") || strcasestr(p, "blank")) Strcat_charp(tmp, "_"); else { if (w * i < 8 * 16) Strcat_charp(tmp, "*"); else { if (!pre_int) { Strcat_charp(tmp, "<pre_int>"); pre_int = TRUE; } push_symbol(tmp, IMG_SYMBOL, symbol_width, 1); n = symbol_width; } } goto img_end; } if (w > 200 && i < 13) { /* must be a horizontal line */ if (!pre_int) { Strcat_charp(tmp, "<pre_int>"); pre_int = TRUE; } w = w / pixel_per_char / symbol_width; if (w <= 0) w = 1; push_symbol(tmp, HR_SYMBOL, symbol_width, w); n = w * symbol_width; goto img_end; } } for (q = p; *q; q++) ; while (q > p && *q != '/') q--; if (*q == '/') q++; Strcat_char(tmp, '['); n = 1; p = q; for (; *q; q++) { if (!IS_ALNUM(*q) && *q != '_' && *q != '-') { break; } Strcat_char(tmp, *q); n++; if (n + 1 >= nw) break; } Strcat_char(tmp, ']'); n++; img_end: #ifdef USE_IMAGE if (use_image) { for (; n < nw; n++) Strcat_char(tmp, ' '); } #endif Strcat_charp(tmp, "</img_alt>"); if (pre_int && !ext_pre_int) Strcat_charp(tmp, "</pre_int>"); if (r) { Strcat_charp(tmp, "</input_alt>"); process_n_form(); } #ifdef USE_IMAGE if (use_image) { switch (align) { case ALIGN_RIGHT: case ALIGN_CENTER: case ALIGN_LEFT: Strcat_charp(tmp, "</div_int>"); break; } } #endif return tmp; } Str process_anchor(struct parsed_tag *tag, char *tagbuf) { if (parsedtag_need_reconstruct(tag)) { parsedtag_set_value(tag, ATTR_HSEQ, Sprintf("%d", cur_hseq++)->ptr); return parsedtag2str(tag); } else { Str tmp = Sprintf("<a hseq=\"%d\"", cur_hseq++); Strcat_charp(tmp, tagbuf + 2); return tmp; } } Str process_input(struct parsed_tag *tag) { int i = 20, v, x, y, z, iw, ih, size = 20; char *q, *p, *r, *p2, *s; Str tmp = NULL; char *qq = ""; int qlen = 0; if (cur_form_id < 0) { char *s = "<form_int method=internal action=none>"; tmp = process_form(parse_tag(&s, TRUE)); } if (tmp == NULL) tmp = Strnew(); p = "text"; parsedtag_get_value(tag, ATTR_TYPE, &p); q = NULL; parsedtag_get_value(tag, ATTR_VALUE, &q); r = ""; parsedtag_get_value(tag, ATTR_NAME, &r); parsedtag_get_value(tag, ATTR_SIZE, &size); if (size > MAX_INPUT_SIZE) size = MAX_INPUT_SIZE; parsedtag_get_value(tag, ATTR_MAXLENGTH, &i); p2 = NULL; parsedtag_get_value(tag, ATTR_ALT, &p2); x = parsedtag_exists(tag, ATTR_CHECKED); y = parsedtag_exists(tag, ATTR_ACCEPT); z = parsedtag_exists(tag, ATTR_READONLY); v = formtype(p); if (v == FORM_UNKNOWN) return NULL; if (!q) { switch (v) { case FORM_INPUT_IMAGE: case FORM_INPUT_SUBMIT: case FORM_INPUT_BUTTON: q = "SUBMIT"; break; case FORM_INPUT_RESET: q = "RESET"; break; /* if no VALUE attribute is specified in * <INPUT TYPE=CHECKBOX> tag, then the value "on" is used * as a default value. It is not a part of HTML4.0 * specification, but an imitation of Netscape behaviour. */ case FORM_INPUT_CHECKBOX: q = "on"; } } /* VALUE attribute is not allowed in <INPUT TYPE=FILE> tag. */ if (v == FORM_INPUT_FILE) q = NULL; if (q) { qq = html_quote(q); qlen = get_strwidth(q); } Strcat_charp(tmp, "<pre_int>"); switch (v) { case FORM_INPUT_PASSWORD: case FORM_INPUT_TEXT: case FORM_INPUT_FILE: case FORM_INPUT_CHECKBOX: if (displayLinkNumber) Strcat(tmp, getLinkNumberStr(0)); Strcat_char(tmp, '['); break; case FORM_INPUT_RADIO: if (displayLinkNumber) Strcat(tmp, getLinkNumberStr(0)); Strcat_char(tmp, '('); } Strcat(tmp, Sprintf("<input_alt hseq=\"%d\" fid=\"%d\" type=\"%s\" " "name=\"%s\" width=%d maxlength=%d value=\"%s\"", cur_hseq++, cur_form_id, html_quote(p), html_quote(r), size, i, qq)); if (x) Strcat_charp(tmp, " checked"); if (y) Strcat_charp(tmp, " accept"); if (z) Strcat_charp(tmp, " readonly"); Strcat_char(tmp, '>'); if (v == FORM_INPUT_HIDDEN) Strcat_charp(tmp, "</input_alt></pre_int>"); else { switch (v) { case FORM_INPUT_PASSWORD: case FORM_INPUT_TEXT: case FORM_INPUT_FILE: Strcat_charp(tmp, "<u>"); break; case FORM_INPUT_IMAGE: s = NULL; parsedtag_get_value(tag, ATTR_SRC, &s); if (s) { Strcat(tmp, Sprintf("<img src=\"%s\"", html_quote(s))); if (p2) Strcat(tmp, Sprintf(" alt=\"%s\"", html_quote(p2))); if (parsedtag_get_value(tag, ATTR_WIDTH, &iw)) Strcat(tmp, Sprintf(" width=\"%d\"", iw)); if (parsedtag_get_value(tag, ATTR_HEIGHT, &ih)) Strcat(tmp, Sprintf(" height=\"%d\"", ih)); Strcat_charp(tmp, " pre_int>"); Strcat_charp(tmp, "</input_alt></pre_int>"); return tmp; } case FORM_INPUT_SUBMIT: case FORM_INPUT_BUTTON: case FORM_INPUT_RESET: if (displayLinkNumber) Strcat(tmp, getLinkNumberStr(-1)); Strcat_charp(tmp, "["); break; } switch (v) { case FORM_INPUT_PASSWORD: i = 0; if (q) { for (; i < qlen && i < size; i++) Strcat_char(tmp, '*'); } for (; i < size; i++) Strcat_char(tmp, ' '); break; case FORM_INPUT_TEXT: case FORM_INPUT_FILE: if (q) Strcat(tmp, textfieldrep(Strnew_charp(q), size)); else { for (i = 0; i < size; i++) Strcat_char(tmp, ' '); } break; case FORM_INPUT_SUBMIT: case FORM_INPUT_BUTTON: if (p2) Strcat_charp(tmp, html_quote(p2)); else Strcat_charp(tmp, qq); break; case FORM_INPUT_RESET: Strcat_charp(tmp, qq); break; case FORM_INPUT_RADIO: case FORM_INPUT_CHECKBOX: if (x) Strcat_char(tmp, '*'); else Strcat_char(tmp, ' '); break; } switch (v) { case FORM_INPUT_PASSWORD: case FORM_INPUT_TEXT: case FORM_INPUT_FILE: Strcat_charp(tmp, "</u>"); break; case FORM_INPUT_IMAGE: case FORM_INPUT_SUBMIT: case FORM_INPUT_BUTTON: case FORM_INPUT_RESET: Strcat_charp(tmp, "]"); } Strcat_charp(tmp, "</input_alt>"); switch (v) { case FORM_INPUT_PASSWORD: case FORM_INPUT_TEXT: case FORM_INPUT_FILE: case FORM_INPUT_CHECKBOX: Strcat_char(tmp, ']'); break; case FORM_INPUT_RADIO: Strcat_char(tmp, ')'); } Strcat_charp(tmp, "</pre_int>"); } return tmp; } Str process_button(struct parsed_tag *tag) { Str tmp = NULL; char *p, *q, *r, *qq = ""; int qlen, v; if (cur_form_id < 0) { char *s = "<form_int method=internal action=none>"; tmp = process_form(parse_tag(&s, TRUE)); } if (tmp == NULL) tmp = Strnew(); p = "submit"; parsedtag_get_value(tag, ATTR_TYPE, &p); q = NULL; parsedtag_get_value(tag, ATTR_VALUE, &q); r = ""; parsedtag_get_value(tag, ATTR_NAME, &r); v = formtype(p); if (v == FORM_UNKNOWN) return NULL; switch (v) { case FORM_INPUT_SUBMIT: case FORM_INPUT_BUTTON: case FORM_INPUT_RESET: break; default: p = "submit"; v = FORM_INPUT_SUBMIT; break; } if (!q) { switch (v) { case FORM_INPUT_SUBMIT: case FORM_INPUT_BUTTON: q = "SUBMIT"; break; case FORM_INPUT_RESET: q = "RESET"; break; } } if (q) { qq = html_quote(q); qlen = strlen(q); } /* Strcat_charp(tmp, "<pre_int>"); */ Strcat(tmp, Sprintf("<input_alt hseq=\"%d\" fid=\"%d\" type=\"%s\" " "name=\"%s\" value=\"%s\">", cur_hseq++, cur_form_id, html_quote(p), html_quote(r), qq)); return tmp; } Str process_n_button(void) { Str tmp = Strnew(); Strcat_charp(tmp, "</input_alt>"); /* Strcat_charp(tmp, "</pre_int>"); */ return tmp; } Str process_select(struct parsed_tag *tag) { Str tmp = NULL; char *p; if (cur_form_id < 0) { char *s = "<form_int method=internal action=none>"; tmp = process_form(parse_tag(&s, TRUE)); } p = ""; parsedtag_get_value(tag, ATTR_NAME, &p); cur_select = Strnew_charp(p); select_is_multiple = parsedtag_exists(tag, ATTR_MULTIPLE); #ifdef MENU_SELECT if (!select_is_multiple) { select_str = Strnew_charp("<pre_int>"); if (displayLinkNumber) Strcat(select_str, getLinkNumberStr(0)); Strcat(select_str, Sprintf("[<input_alt hseq=\"%d\" " "fid=\"%d\" type=select name=\"%s\" selectnumber=%d", cur_hseq++, cur_form_id, html_quote(p), n_select)); Strcat_charp(select_str, ">"); if (n_select == max_select) { max_select *= 2; select_option = New_Reuse(FormSelectOption, select_option, max_select); } select_option[n_select].first = NULL; select_option[n_select].last = NULL; cur_option_maxwidth = 0; } else #endif /* MENU_SELECT */ select_str = Strnew(); cur_option = NULL; cur_status = R_ST_NORMAL; n_selectitem = 0; return tmp; } Str process_n_select(void) { if (cur_select == NULL) return NULL; process_option(); #ifdef MENU_SELECT if (!select_is_multiple) { if (select_option[n_select].first) { FormItemList sitem; chooseSelectOption(&sitem, select_option[n_select].first); Strcat(select_str, textfieldrep(sitem.label, cur_option_maxwidth)); } Strcat_charp(select_str, "</input_alt>]</pre_int>"); n_select++; } else #endif /* MENU_SELECT */ Strcat_charp(select_str, "<br>"); cur_select = NULL; n_selectitem = 0; return select_str; } void feed_select(char *str) { Str tmp = Strnew(); int prev_status = cur_status; static int prev_spaces = -1; char *p; if (cur_select == NULL) return; while (read_token(tmp, &str, &cur_status, 0, 0)) { if (cur_status != R_ST_NORMAL || prev_status != R_ST_NORMAL) continue; p = tmp->ptr; if (tmp->ptr[0] == '<' && Strlastchar(tmp) == '>') { struct parsed_tag *tag; char *q; if (!(tag = parse_tag(&p, FALSE))) continue; switch (tag->tagid) { case HTML_OPTION: process_option(); cur_option = Strnew(); if (parsedtag_get_value(tag, ATTR_VALUE, &q)) cur_option_value = Strnew_charp(q); else cur_option_value = NULL; if (parsedtag_get_value(tag, ATTR_LABEL, &q)) cur_option_label = Strnew_charp(q); else cur_option_label = NULL; cur_option_selected = parsedtag_exists(tag, ATTR_SELECTED); prev_spaces = -1; break; case HTML_N_OPTION: /* do nothing */ break; default: /* never happen */ break; } } else if (cur_option) { while (*p) { if (IS_SPACE(*p) && prev_spaces != 0) { p++; if (prev_spaces > 0) prev_spaces++; } else { if (IS_SPACE(*p)) prev_spaces = 1; else prev_spaces = 0; if (*p == '&') Strcat_charp(cur_option, getescapecmd(&p)); else Strcat_char(cur_option, *(p++)); } } } } } void process_option(void) { char begin_char = '[', end_char = ']'; int len; if (cur_select == NULL || cur_option == NULL) return; while (cur_option->length > 0 && IS_SPACE(Strlastchar(cur_option))) Strshrink(cur_option, 1); if (cur_option_value == NULL) cur_option_value = cur_option; if (cur_option_label == NULL) cur_option_label = cur_option; #ifdef MENU_SELECT if (!select_is_multiple) { len = get_Str_strwidth(cur_option_label); if (len > cur_option_maxwidth) cur_option_maxwidth = len; addSelectOption(&select_option[n_select], cur_option_value, cur_option_label, cur_option_selected); return; } #endif /* MENU_SELECT */ if (!select_is_multiple) { begin_char = '('; end_char = ')'; } Strcat(select_str, Sprintf("<br><pre_int>%c<input_alt hseq=\"%d\" " "fid=\"%d\" type=%s name=\"%s\" value=\"%s\"", begin_char, cur_hseq++, cur_form_id, select_is_multiple ? "checkbox" : "radio", html_quote(cur_select->ptr), html_quote(cur_option_value->ptr))); if (cur_option_selected) Strcat_charp(select_str, " checked>*</input_alt>"); else Strcat_charp(select_str, "> </input_alt>"); Strcat_char(select_str, end_char); Strcat_charp(select_str, html_quote(cur_option_label->ptr)); Strcat_charp(select_str, "</pre_int>"); n_selectitem++; } Str process_textarea(struct parsed_tag *tag, int width) { Str tmp = NULL; char *p; #define TEXTAREA_ATTR_COL_MAX 4096 #define TEXTAREA_ATTR_ROWS_MAX 4096 if (cur_form_id < 0) { char *s = "<form_int method=internal action=none>"; tmp = process_form(parse_tag(&s, TRUE)); } p = ""; parsedtag_get_value(tag, ATTR_NAME, &p); cur_textarea = Strnew_charp(p); cur_textarea_size = 20; if (parsedtag_get_value(tag, ATTR_COLS, &p)) { cur_textarea_size = atoi(p); if (p[strlen(p) - 1] == '%') cur_textarea_size = width * cur_textarea_size / 100 - 2; if (cur_textarea_size <= 0) { cur_textarea_size = 20; } else if (cur_textarea_size > TEXTAREA_ATTR_COL_MAX) { cur_textarea_size = TEXTAREA_ATTR_COL_MAX; } } cur_textarea_rows = 1; if (parsedtag_get_value(tag, ATTR_ROWS, &p)) { cur_textarea_rows = atoi(p); if (cur_textarea_rows <= 0) { cur_textarea_rows = 1; } else if (cur_textarea_rows > TEXTAREA_ATTR_ROWS_MAX) { cur_textarea_rows = TEXTAREA_ATTR_ROWS_MAX; } } cur_textarea_readonly = parsedtag_exists(tag, ATTR_READONLY); if (n_textarea >= max_textarea) { max_textarea *= 2; textarea_str = New_Reuse(Str, textarea_str, max_textarea); } textarea_str[n_textarea] = Strnew(); ignore_nl_textarea = TRUE; return tmp; } Str process_n_textarea(void) { Str tmp; int i; if (cur_textarea == NULL) return NULL; tmp = Strnew(); Strcat(tmp, Sprintf("<pre_int>[<input_alt hseq=\"%d\" fid=\"%d\" " "type=textarea name=\"%s\" size=%d rows=%d " "top_margin=%d textareanumber=%d", cur_hseq, cur_form_id, html_quote(cur_textarea->ptr), cur_textarea_size, cur_textarea_rows, cur_textarea_rows - 1, n_textarea)); if (cur_textarea_readonly) Strcat_charp(tmp, " readonly"); Strcat_charp(tmp, "><u>"); for (i = 0; i < cur_textarea_size; i++) Strcat_char(tmp, ' '); Strcat_charp(tmp, "</u></input_alt>]</pre_int>\n"); cur_hseq++; n_textarea++; cur_textarea = NULL; return tmp; } void feed_textarea(char *str) { if (cur_textarea == NULL) return; if (ignore_nl_textarea) { if (*str == '\r') str++; if (*str == '\n') str++; } ignore_nl_textarea = FALSE; while (*str) { if (*str == '&') Strcat_charp(textarea_str[n_textarea], getescapecmd(&str)); else if (*str == '\n') { Strcat_charp(textarea_str[n_textarea], "\r\n"); str++; } else if (*str != '\r') Strcat_char(textarea_str[n_textarea], *(str++)); } } Str process_hr(struct parsed_tag *tag, int width, int indent_width) { Str tmp = Strnew_charp("<nobr>"); int w = 0; int x = ALIGN_CENTER; #define HR_ATTR_WIDTH_MAX 65535 if (width > indent_width) width -= indent_width; if (parsedtag_get_value(tag, ATTR_WIDTH, &w)) { if (w > HR_ATTR_WIDTH_MAX) { w = HR_ATTR_WIDTH_MAX; } w = REAL_WIDTH(w, width); } else { w = width; } parsedtag_get_value(tag, ATTR_ALIGN, &x); switch (x) { case ALIGN_CENTER: Strcat_charp(tmp, "<div_int align=center>"); break; case ALIGN_RIGHT: Strcat_charp(tmp, "<div_int align=right>"); break; case ALIGN_LEFT: Strcat_charp(tmp, "<div_int align=left>"); break; } w /= symbol_width; if (w <= 0) w = 1; push_symbol(tmp, HR_SYMBOL, symbol_width, w); Strcat_charp(tmp, "</div_int></nobr>"); return tmp; } #ifdef USE_M17N static char * check_charset(char *p) { return wc_guess_charset(p, 0) ? p : NULL; } static char * check_accept_charset(char *ac) { char *s = ac, *e; while (*s) { while (*s && (IS_SPACE(*s) || *s == ',')) s++; if (!*s) break; e = s; while (*e && !(IS_SPACE(*e) || *e == ',')) e++; if (wc_guess_charset(Strnew_charp_n(s, e - s)->ptr, 0)) return ac; s = e; } return NULL; } #endif static Str process_form_int(struct parsed_tag *tag, int fid) { char *p, *q, *r, *s, *tg, *n; p = "get"; parsedtag_get_value(tag, ATTR_METHOD, &p); q = "!CURRENT_URL!"; parsedtag_get_value(tag, ATTR_ACTION, &q); q = url_encode(remove_space(q), cur_baseURL, cur_document_charset); r = NULL; #ifdef USE_M17N if (parsedtag_get_value(tag, ATTR_ACCEPT_CHARSET, &r)) r = check_accept_charset(r); if (!r && parsedtag_get_value(tag, ATTR_CHARSET, &r)) r = check_charset(r); #endif s = NULL; parsedtag_get_value(tag, ATTR_ENCTYPE, &s); tg = NULL; parsedtag_get_value(tag, ATTR_TARGET, &tg); n = NULL; parsedtag_get_value(tag, ATTR_NAME, &n); if (fid < 0) { form_max++; form_sp++; fid = form_max; } else { /* <form_int> */ if (form_max < fid) form_max = fid; form_sp = fid; } if (forms_size == 0) { forms_size = INITIAL_FORM_SIZE; forms = New_N(FormList *, forms_size); form_stack = NewAtom_N(int, forms_size); } if (forms_size <= form_max) { forms_size += form_max; forms = New_Reuse(FormList *, forms, forms_size); form_stack = New_Reuse(int, form_stack, forms_size); } form_stack[form_sp] = fid; if (w3m_halfdump) { Str tmp = Sprintf("<form_int fid=\"%d\" action=\"%s\" method=\"%s\"", fid, html_quote(q), html_quote(p)); if (s) Strcat(tmp, Sprintf(" enctype=\"%s\"", html_quote(s))); if (tg) Strcat(tmp, Sprintf(" target=\"%s\"", html_quote(tg))); if (n) Strcat(tmp, Sprintf(" name=\"%s\"", html_quote(n))); #ifdef USE_M17N if (r) Strcat(tmp, Sprintf(" accept-charset=\"%s\"", html_quote(r))); #endif Strcat_charp(tmp, ">"); return tmp; } forms[fid] = newFormList(q, p, r, s, tg, n, NULL); return NULL; } Str process_form(struct parsed_tag *tag) { return process_form_int(tag, -1); } Str process_n_form(void) { if (form_sp >= 0) form_sp--; return NULL; } static void clear_ignore_p_flag(int cmd, struct readbuffer *obuf) { static int clear_flag_cmd[] = { HTML_HR, HTML_UNKNOWN }; int i; for (i = 0; clear_flag_cmd[i] != HTML_UNKNOWN; i++) { if (cmd == clear_flag_cmd[i]) { obuf->flag &= ~RB_IGNORE_P; return; } } } static void set_alignment(struct readbuffer *obuf, struct parsed_tag *tag) { long flag = -1; int align; if (parsedtag_get_value(tag, ATTR_ALIGN, &align)) { switch (align) { case ALIGN_CENTER: flag = RB_CENTER; break; case ALIGN_RIGHT: flag = RB_RIGHT; break; case ALIGN_LEFT: flag = RB_LEFT; } } RB_SAVE_FLAG(obuf); if (flag != -1) { RB_SET_ALIGN(obuf, flag); } } #ifdef ID_EXT static void process_idattr(struct readbuffer *obuf, int cmd, struct parsed_tag *tag) { char *id = NULL, *framename = NULL; Str idtag = NULL; /* * HTML_TABLE is handled by the other process. */ if (cmd == HTML_TABLE) return; parsedtag_get_value(tag, ATTR_ID, &id); parsedtag_get_value(tag, ATTR_FRAMENAME, &framename); if (id == NULL) return; if (framename) idtag = Sprintf("<_id id=\"%s\" framename=\"%s\">", html_quote(id), html_quote(framename)); else idtag = Sprintf("<_id id=\"%s\">", html_quote(id)); push_tag(obuf, idtag->ptr, HTML_NOP); } #endif /* ID_EXT */ #define CLOSE_P if (obuf->flag & RB_P) { \ flushline(h_env, obuf, envs[h_env->envc].indent,0,h_env->limit);\ RB_RESTORE_FLAG(obuf);\ obuf->flag &= ~RB_P;\ } #define CLOSE_A \ CLOSE_P; \ close_anchor(h_env, obuf); #define CLOSE_DT \ if (obuf->flag & RB_IN_DT) { \ obuf->flag &= ~RB_IN_DT; \ HTMLlineproc1("</b>", h_env); \ } #define PUSH_ENV(cmd) \ if (++h_env->envc_real < h_env->nenv) { \ ++h_env->envc; \ envs[h_env->envc].env = cmd; \ envs[h_env->envc].count = 0; \ if (h_env->envc <= MAX_INDENT_LEVEL) \ envs[h_env->envc].indent = envs[h_env->envc - 1].indent + INDENT_INCR; \ else \ envs[h_env->envc].indent = envs[h_env->envc - 1].indent; \ } #define POP_ENV \ if (h_env->envc_real-- < h_env->nenv) \ h_env->envc--; static int ul_type(struct parsed_tag *tag, int default_type) { char *p; if (parsedtag_get_value(tag, ATTR_TYPE, &p)) { if (!strcasecmp(p, "disc")) return (int)'d'; else if (!strcasecmp(p, "circle")) return (int)'c'; else if (!strcasecmp(p, "square")) return (int)'s'; } return default_type; } int getMetaRefreshParam(char *q, Str *refresh_uri) { int refresh_interval; char *r; Str s_tmp = NULL; if (q == NULL || refresh_uri == NULL) return 0; refresh_interval = atoi(q); if (refresh_interval < 0) return 0; while (*q) { if (!strncasecmp(q, "url=", 4)) { q += 4; if (*q == '\"' || *q == '\'') /* " or ' */ q++; r = q; while (*r && !IS_SPACE(*r) && *r != ';') r++; s_tmp = Strnew_charp_n(q, r - q); if (s_tmp->ptr[s_tmp->length - 1] == '\"' /* " */ || s_tmp->ptr[s_tmp->length - 1] == '\'') { /* ' */ s_tmp->length--; s_tmp->ptr[s_tmp->length] = '\0'; } q = r; } while (*q && *q != ';') q++; if (*q == ';') q++; while (*q && *q == ' ') q++; } *refresh_uri = s_tmp; return refresh_interval; } int HTMLtagproc1(struct parsed_tag *tag, struct html_feed_environ *h_env) { char *p, *q, *r; int i, w, x, y, z, count, width; struct readbuffer *obuf = h_env->obuf; struct environment *envs = h_env->envs; Str tmp; int hseq; int cmd; #ifdef ID_EXT char *id = NULL; #endif /* ID_EXT */ cmd = tag->tagid; if (obuf->flag & RB_PRE) { switch (cmd) { case HTML_NOBR: case HTML_N_NOBR: case HTML_PRE_INT: case HTML_N_PRE_INT: return 1; } } switch (cmd) { case HTML_B: obuf->in_bold++; if (obuf->in_bold > 1) return 1; return 0; case HTML_N_B: if (obuf->in_bold == 1 && close_effect0(obuf, HTML_B)) obuf->in_bold = 0; if (obuf->in_bold > 0) { obuf->in_bold--; if (obuf->in_bold == 0) return 0; } return 1; case HTML_I: obuf->in_italic++; if (obuf->in_italic > 1) return 1; return 0; case HTML_N_I: if (obuf->in_italic == 1 && close_effect0(obuf, HTML_I)) obuf->in_italic = 0; if (obuf->in_italic > 0) { obuf->in_italic--; if (obuf->in_italic == 0) return 0; } return 1; case HTML_U: obuf->in_under++; if (obuf->in_under > 1) return 1; return 0; case HTML_N_U: if (obuf->in_under == 1 && close_effect0(obuf, HTML_U)) obuf->in_under = 0; if (obuf->in_under > 0) { obuf->in_under--; if (obuf->in_under == 0) return 0; } return 1; case HTML_EM: HTMLlineproc1("<i>", h_env); return 1; case HTML_N_EM: HTMLlineproc1("</i>", h_env); return 1; case HTML_STRONG: HTMLlineproc1("<b>", h_env); return 1; case HTML_N_STRONG: HTMLlineproc1("</b>", h_env); return 1; case HTML_Q: HTMLlineproc1("`", h_env); return 1; case HTML_N_Q: HTMLlineproc1("'", h_env); return 1; case HTML_P: case HTML_N_P: CLOSE_A; if (!(obuf->flag & RB_IGNORE_P)) { flushline(h_env, obuf, envs[h_env->envc].indent, 1, h_env->limit); do_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); } obuf->flag |= RB_IGNORE_P; if (cmd == HTML_P) { set_alignment(obuf, tag); obuf->flag |= RB_P; } return 1; case HTML_BR: flushline(h_env, obuf, envs[h_env->envc].indent, 1, h_env->limit); h_env->blank_lines = 0; return 1; case HTML_H: if (!(obuf->flag & (RB_PREMODE | RB_IGNORE_P))) { flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); do_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); } HTMLlineproc1("<b>", h_env); set_alignment(obuf, tag); return 1; case HTML_N_H: HTMLlineproc1("</b>", h_env); if (!(obuf->flag & RB_PREMODE)) { flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); } do_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); RB_RESTORE_FLAG(obuf); close_anchor(h_env, obuf); obuf->flag |= RB_IGNORE_P; return 1; case HTML_UL: case HTML_OL: case HTML_BLQ: CLOSE_A; if (!(obuf->flag & RB_IGNORE_P)) { flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); if (!(obuf->flag & RB_PREMODE) && (h_env->envc == 0 || cmd == HTML_BLQ)) do_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); } PUSH_ENV(cmd); if (cmd == HTML_UL || cmd == HTML_OL) { if (parsedtag_get_value(tag, ATTR_START, &count)) { envs[h_env->envc].count = count - 1; } } if (cmd == HTML_OL) { envs[h_env->envc].type = '1'; if (parsedtag_get_value(tag, ATTR_TYPE, &p)) { envs[h_env->envc].type = (int)*p; } } if (cmd == HTML_UL) envs[h_env->envc].type = ul_type(tag, 0); flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); return 1; case HTML_N_UL: case HTML_N_OL: case HTML_N_DL: case HTML_N_BLQ: CLOSE_DT; CLOSE_A; if (h_env->envc > 0) { flushline(h_env, obuf, envs[h_env->envc - 1].indent, 0, h_env->limit); POP_ENV; if (!(obuf->flag & RB_PREMODE) && (h_env->envc == 0 || cmd == HTML_N_DL || cmd == HTML_N_BLQ)) { do_blankline(h_env, obuf, envs[h_env->envc].indent, INDENT_INCR, h_env->limit); obuf->flag |= RB_IGNORE_P; } } close_anchor(h_env, obuf); return 1; case HTML_DL: CLOSE_A; if (!(obuf->flag & RB_IGNORE_P)) { flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); if (!(obuf->flag & RB_PREMODE)) do_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); } PUSH_ENV(cmd); if (parsedtag_exists(tag, ATTR_COMPACT)) envs[h_env->envc].env = HTML_DL_COMPACT; obuf->flag |= RB_IGNORE_P; return 1; case HTML_LI: CLOSE_A; CLOSE_DT; if (h_env->envc > 0) { Str num; flushline(h_env, obuf, envs[h_env->envc - 1].indent, 0, h_env->limit); envs[h_env->envc].count++; if (parsedtag_get_value(tag, ATTR_VALUE, &p)) { count = atoi(p); if (count > 0) envs[h_env->envc].count = count; else envs[h_env->envc].count = 0; } switch (envs[h_env->envc].env) { case HTML_UL: envs[h_env->envc].type = ul_type(tag, envs[h_env->envc].type); for (i = 0; i < INDENT_INCR - 3; i++) push_charp(obuf, 1, NBSP, PC_ASCII); tmp = Strnew(); switch (envs[h_env->envc].type) { case 'd': push_symbol(tmp, UL_SYMBOL_DISC, symbol_width, 1); break; case 'c': push_symbol(tmp, UL_SYMBOL_CIRCLE, symbol_width, 1); break; case 's': push_symbol(tmp, UL_SYMBOL_SQUARE, symbol_width, 1); break; default: push_symbol(tmp, UL_SYMBOL((h_env->envc_real - 1) % MAX_UL_LEVEL), symbol_width, 1); break; } if (symbol_width == 1) push_charp(obuf, 1, NBSP, PC_ASCII); push_str(obuf, symbol_width, tmp, PC_ASCII); push_charp(obuf, 1, NBSP, PC_ASCII); set_space_to_prevchar(obuf->prevchar); break; case HTML_OL: if (parsedtag_get_value(tag, ATTR_TYPE, &p)) envs[h_env->envc].type = (int)*p; switch ((envs[h_env->envc].count > 0)? envs[h_env->envc].type: '1') { case 'i': num = romanNumeral(envs[h_env->envc].count); break; case 'I': num = romanNumeral(envs[h_env->envc].count); Strupper(num); break; case 'a': num = romanAlphabet(envs[h_env->envc].count); break; case 'A': num = romanAlphabet(envs[h_env->envc].count); Strupper(num); break; default: num = Sprintf("%d", envs[h_env->envc].count); break; } if (INDENT_INCR >= 4) Strcat_charp(num, ". "); else Strcat_char(num, '.'); push_spaces(obuf, 1, INDENT_INCR - num->length); push_str(obuf, num->length, num, PC_ASCII); if (INDENT_INCR >= 4) set_space_to_prevchar(obuf->prevchar); break; default: push_spaces(obuf, 1, INDENT_INCR); break; } } else { flushline(h_env, obuf, 0, 0, h_env->limit); } obuf->flag |= RB_IGNORE_P; return 1; case HTML_DT: CLOSE_A; if (h_env->envc == 0 || (h_env->envc_real < h_env->nenv && envs[h_env->envc].env != HTML_DL && envs[h_env->envc].env != HTML_DL_COMPACT)) { PUSH_ENV(HTML_DL); } if (h_env->envc > 0) { flushline(h_env, obuf, envs[h_env->envc - 1].indent, 0, h_env->limit); } if (!(obuf->flag & RB_IN_DT)) { HTMLlineproc1("<b>", h_env); obuf->flag |= RB_IN_DT; } obuf->flag |= RB_IGNORE_P; return 1; case HTML_DD: CLOSE_A; CLOSE_DT; if (h_env->envc == 0 || (h_env->envc_real < h_env->nenv && envs[h_env->envc].env != HTML_DL && envs[h_env->envc].env != HTML_DL_COMPACT)) { PUSH_ENV(HTML_DL); } if (envs[h_env->envc].env == HTML_DL_COMPACT) { if (obuf->pos > envs[h_env->envc].indent) flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); else push_spaces(obuf, 1, envs[h_env->envc].indent - obuf->pos); } else flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); /* obuf->flag |= RB_IGNORE_P; */ return 1; case HTML_TITLE: close_anchor(h_env, obuf); process_title(tag); obuf->flag |= RB_TITLE; obuf->end_tag = HTML_N_TITLE; return 1; case HTML_N_TITLE: if (!(obuf->flag & RB_TITLE)) return 1; obuf->flag &= ~RB_TITLE; obuf->end_tag = 0; tmp = process_n_title(tag); if (tmp) HTMLlineproc1(tmp->ptr, h_env); return 1; case HTML_TITLE_ALT: if (parsedtag_get_value(tag, ATTR_TITLE, &p)) h_env->title = html_unquote(p); return 0; case HTML_FRAMESET: PUSH_ENV(cmd); push_charp(obuf, 9, "--FRAME--", PC_ASCII); flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); return 0; case HTML_N_FRAMESET: if (h_env->envc > 0) { POP_ENV; flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); } return 0; case HTML_NOFRAMES: CLOSE_A; flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); obuf->flag |= (RB_NOFRAMES | RB_IGNORE_P); /* istr = str; */ return 1; case HTML_N_NOFRAMES: CLOSE_A; flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); obuf->flag &= ~RB_NOFRAMES; return 1; case HTML_FRAME: q = r = NULL; parsedtag_get_value(tag, ATTR_SRC, &q); parsedtag_get_value(tag, ATTR_NAME, &r); if (q) { q = html_quote(q); push_tag(obuf, Sprintf("<a hseq=\"%d\" href=\"%s\">", cur_hseq++, q)->ptr, HTML_A); if (r) q = html_quote(r); push_charp(obuf, get_strwidth(q), q, PC_ASCII); push_tag(obuf, "</a>", HTML_N_A); } flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); return 0; case HTML_HR: close_anchor(h_env, obuf); tmp = process_hr(tag, h_env->limit, envs[h_env->envc].indent); HTMLlineproc1(tmp->ptr, h_env); set_space_to_prevchar(obuf->prevchar); return 1; case HTML_PRE: x = parsedtag_exists(tag, ATTR_FOR_TABLE); CLOSE_A; if (!(obuf->flag & RB_IGNORE_P)) { flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); if (!x) do_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); } else fillline(obuf, envs[h_env->envc].indent); obuf->flag |= (RB_PRE | RB_IGNORE_P); /* istr = str; */ return 1; case HTML_N_PRE: flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); if (!(obuf->flag & RB_IGNORE_P)) { do_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); obuf->flag |= RB_IGNORE_P; h_env->blank_lines++; } obuf->flag &= ~RB_PRE; close_anchor(h_env, obuf); return 1; case HTML_PRE_INT: i = obuf->line->length; append_tags(obuf); if (!(obuf->flag & RB_SPECIAL)) { set_breakpoint(obuf, obuf->line->length - i); } obuf->flag |= RB_PRE_INT; return 0; case HTML_N_PRE_INT: push_tag(obuf, "</pre_int>", HTML_N_PRE_INT); obuf->flag &= ~RB_PRE_INT; if (!(obuf->flag & RB_SPECIAL) && obuf->pos > obuf->bp.pos) { set_prevchar(obuf->prevchar, "", 0); obuf->prev_ctype = PC_CTRL; } return 1; case HTML_NOBR: obuf->flag |= RB_NOBR; obuf->nobr_level++; return 0; case HTML_N_NOBR: if (obuf->nobr_level > 0) obuf->nobr_level--; if (obuf->nobr_level == 0) obuf->flag &= ~RB_NOBR; return 0; case HTML_PRE_PLAIN: CLOSE_A; if (!(obuf->flag & RB_IGNORE_P)) { flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); do_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); } obuf->flag |= (RB_PRE | RB_IGNORE_P); return 1; case HTML_N_PRE_PLAIN: CLOSE_A; if (!(obuf->flag & RB_IGNORE_P)) { flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); do_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); obuf->flag |= RB_IGNORE_P; } obuf->flag &= ~RB_PRE; return 1; case HTML_LISTING: case HTML_XMP: case HTML_PLAINTEXT: CLOSE_A; if (!(obuf->flag & RB_IGNORE_P)) { flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); do_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); } obuf->flag |= (RB_PLAIN | RB_IGNORE_P); switch (cmd) { case HTML_LISTING: obuf->end_tag = HTML_N_LISTING; break; case HTML_XMP: obuf->end_tag = HTML_N_XMP; break; case HTML_PLAINTEXT: obuf->end_tag = MAX_HTMLTAG; break; } return 1; case HTML_N_LISTING: case HTML_N_XMP: CLOSE_A; if (!(obuf->flag & RB_IGNORE_P)) { flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); do_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); obuf->flag |= RB_IGNORE_P; } obuf->flag &= ~RB_PLAIN; obuf->end_tag = 0; return 1; case HTML_SCRIPT: obuf->flag |= RB_SCRIPT; obuf->end_tag = HTML_N_SCRIPT; return 1; case HTML_STYLE: obuf->flag |= RB_STYLE; obuf->end_tag = HTML_N_STYLE; return 1; case HTML_N_SCRIPT: obuf->flag &= ~RB_SCRIPT; obuf->end_tag = 0; return 1; case HTML_N_STYLE: obuf->flag &= ~RB_STYLE; obuf->end_tag = 0; return 1; case HTML_A: if (obuf->anchor.url) close_anchor(h_env, obuf); hseq = 0; if (parsedtag_get_value(tag, ATTR_HREF, &p)) obuf->anchor.url = Strnew_charp(p)->ptr; if (parsedtag_get_value(tag, ATTR_TARGET, &p)) obuf->anchor.target = Strnew_charp(p)->ptr; if (parsedtag_get_value(tag, ATTR_REFERER, &p)) obuf->anchor.referer = Strnew_charp(p)->ptr; if (parsedtag_get_value(tag, ATTR_TITLE, &p)) obuf->anchor.title = Strnew_charp(p)->ptr; if (parsedtag_get_value(tag, ATTR_ACCESSKEY, &p)) obuf->anchor.accesskey = (unsigned char)*p; if (parsedtag_get_value(tag, ATTR_HSEQ, &hseq)) obuf->anchor.hseq = hseq; if (hseq == 0 && obuf->anchor.url) { obuf->anchor.hseq = cur_hseq; tmp = process_anchor(tag, h_env->tagbuf->ptr); push_tag(obuf, tmp->ptr, HTML_A); if (displayLinkNumber) HTMLlineproc1(getLinkNumberStr(-1)->ptr, h_env); return 1; } return 0; case HTML_N_A: close_anchor(h_env, obuf); return 1; case HTML_IMG: tmp = process_img(tag, h_env->limit); HTMLlineproc1(tmp->ptr, h_env); return 1; case HTML_IMG_ALT: if (parsedtag_get_value(tag, ATTR_SRC, &p)) obuf->img_alt = Strnew_charp(p); #ifdef USE_IMAGE i = 0; if (parsedtag_get_value(tag, ATTR_TOP_MARGIN, &i)) { if (i > obuf->top_margin) obuf->top_margin = i; } i = 0; if (parsedtag_get_value(tag, ATTR_BOTTOM_MARGIN, &i)) { if (i > obuf->bottom_margin) obuf->bottom_margin = i; } #endif return 0; case HTML_N_IMG_ALT: if (obuf->img_alt) { if (!close_effect0(obuf, HTML_IMG_ALT)) push_tag(obuf, "</img_alt>", HTML_N_IMG_ALT); obuf->img_alt = NULL; } return 1; case HTML_INPUT_ALT: i = 0; if (parsedtag_get_value(tag, ATTR_TOP_MARGIN, &i)) { if (i > obuf->top_margin) obuf->top_margin = i; } i = 0; if (parsedtag_get_value(tag, ATTR_BOTTOM_MARGIN, &i)) { if (i > obuf->bottom_margin) obuf->bottom_margin = i; } if (parsedtag_get_value(tag, ATTR_HSEQ, &hseq)) { obuf->input_alt.hseq = hseq; } if (parsedtag_get_value(tag, ATTR_FID, &i)) { obuf->input_alt.fid = i; } if (parsedtag_get_value(tag, ATTR_TYPE, &p)) { obuf->input_alt.type = Strnew_charp(p); } if (parsedtag_get_value(tag, ATTR_VALUE, &p)) { obuf->input_alt.value = Strnew_charp(p); } if (parsedtag_get_value(tag, ATTR_NAME, &p)) { obuf->input_alt.name = Strnew_charp(p); } obuf->input_alt.in = 1; return 0; case HTML_N_INPUT_ALT: if (obuf->input_alt.in) { if (!close_effect0(obuf, HTML_INPUT_ALT)) push_tag(obuf, "</input_alt>", HTML_N_INPUT_ALT); obuf->input_alt.hseq = 0; obuf->input_alt.fid = -1; obuf->input_alt.in = 0; obuf->input_alt.type = NULL; obuf->input_alt.name = NULL; obuf->input_alt.value = NULL; } return 1; case HTML_TABLE: close_anchor(h_env, obuf); obuf->table_level++; if (obuf->table_level >= MAX_TABLE) break; w = BORDER_NONE; /* x: cellspacing, y: cellpadding */ x = 2; y = 1; z = 0; width = 0; if (parsedtag_exists(tag, ATTR_BORDER)) { if (parsedtag_get_value(tag, ATTR_BORDER, &w)) { if (w > 2) w = BORDER_THICK; else if (w < 0) { /* weird */ w = BORDER_THIN; } } else w = BORDER_THIN; } if (DisplayBorders && w == BORDER_NONE) w = BORDER_THIN; if (parsedtag_get_value(tag, ATTR_WIDTH, &i)) { if (obuf->table_level == 0) width = REAL_WIDTH(i, h_env->limit - envs[h_env->envc].indent); else width = RELATIVE_WIDTH(i); } if (parsedtag_exists(tag, ATTR_HBORDER)) w = BORDER_NOWIN; #define MAX_CELLSPACING 1000 #define MAX_CELLPADDING 1000 #define MAX_VSPACE 1000 parsedtag_get_value(tag, ATTR_CELLSPACING, &x); parsedtag_get_value(tag, ATTR_CELLPADDING, &y); parsedtag_get_value(tag, ATTR_VSPACE, &z); if (x > MAX_CELLSPACING) x = MAX_CELLSPACING; if (y > MAX_CELLPADDING) y = MAX_CELLPADDING; if (z > MAX_VSPACE) z = MAX_VSPACE; #ifdef ID_EXT parsedtag_get_value(tag, ATTR_ID, &id); #endif /* ID_EXT */ tables[obuf->table_level] = begin_table(w, x, y, z); #ifdef ID_EXT if (id != NULL) tables[obuf->table_level]->id = Strnew_charp(id); #endif /* ID_EXT */ table_mode[obuf->table_level].pre_mode = 0; table_mode[obuf->table_level].indent_level = 0; table_mode[obuf->table_level].nobr_level = 0; table_mode[obuf->table_level].caption = 0; table_mode[obuf->table_level].end_tag = 0; /* HTML_UNKNOWN */ #ifndef TABLE_EXPAND tables[obuf->table_level]->total_width = width; #else tables[obuf->table_level]->real_width = width; tables[obuf->table_level]->total_width = 0; #endif return 1; case HTML_N_TABLE: /* should be processed in HTMLlineproc() */ return 1; case HTML_CENTER: CLOSE_A; if (!(obuf->flag & (RB_PREMODE | RB_IGNORE_P))) flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); RB_SAVE_FLAG(obuf); RB_SET_ALIGN(obuf, RB_CENTER); return 1; case HTML_N_CENTER: CLOSE_A; if (!(obuf->flag & RB_PREMODE)) flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); RB_RESTORE_FLAG(obuf); return 1; case HTML_DIV: CLOSE_A; if (!(obuf->flag & RB_IGNORE_P)) flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); set_alignment(obuf, tag); return 1; case HTML_N_DIV: CLOSE_A; flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); RB_RESTORE_FLAG(obuf); return 1; case HTML_DIV_INT: CLOSE_P; if (!(obuf->flag & RB_IGNORE_P)) flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); set_alignment(obuf, tag); return 1; case HTML_N_DIV_INT: CLOSE_P; flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); RB_RESTORE_FLAG(obuf); return 1; case HTML_FORM: CLOSE_A; if (!(obuf->flag & RB_IGNORE_P)) flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); tmp = process_form(tag); if (tmp) HTMLlineproc1(tmp->ptr, h_env); return 1; case HTML_N_FORM: CLOSE_A; flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); obuf->flag |= RB_IGNORE_P; process_n_form(); return 1; case HTML_INPUT: close_anchor(h_env, obuf); tmp = process_input(tag); if (tmp) HTMLlineproc1(tmp->ptr, h_env); return 1; case HTML_BUTTON: tmp = process_button(tag); if (tmp) HTMLlineproc1(tmp->ptr, h_env); return 1; case HTML_N_BUTTON: tmp = process_n_button(); if (tmp) HTMLlineproc1(tmp->ptr, h_env); return 1; case HTML_SELECT: close_anchor(h_env, obuf); tmp = process_select(tag); if (tmp) HTMLlineproc1(tmp->ptr, h_env); obuf->flag |= RB_INSELECT; obuf->end_tag = HTML_N_SELECT; return 1; case HTML_N_SELECT: obuf->flag &= ~RB_INSELECT; obuf->end_tag = 0; tmp = process_n_select(); if (tmp) HTMLlineproc1(tmp->ptr, h_env); return 1; case HTML_OPTION: /* nothing */ return 1; case HTML_TEXTAREA: close_anchor(h_env, obuf); tmp = process_textarea(tag, h_env->limit); if (tmp) HTMLlineproc1(tmp->ptr, h_env); obuf->flag |= RB_INTXTA; obuf->end_tag = HTML_N_TEXTAREA; return 1; case HTML_N_TEXTAREA: obuf->flag &= ~RB_INTXTA; obuf->end_tag = 0; tmp = process_n_textarea(); if (tmp) HTMLlineproc1(tmp->ptr, h_env); return 1; case HTML_ISINDEX: p = ""; q = "!CURRENT_URL!"; parsedtag_get_value(tag, ATTR_PROMPT, &p); parsedtag_get_value(tag, ATTR_ACTION, &q); tmp = Strnew_m_charp("<form method=get action=\"", html_quote(q), "\">", html_quote(p), "<input type=text name=\"\" accept></form>", NULL); HTMLlineproc1(tmp->ptr, h_env); return 1; case HTML_META: p = q = r = NULL; parsedtag_get_value(tag, ATTR_HTTP_EQUIV, &p); parsedtag_get_value(tag, ATTR_CONTENT, &q); #ifdef USE_M17N parsedtag_get_value(tag, ATTR_CHARSET, &r); if (r) { /* <meta charset=""> */ SKIP_BLANKS(r); meta_charset = wc_guess_charset(r, 0); } else if (p && q && !strcasecmp(p, "Content-Type") && (q = strcasestr(q, "charset")) != NULL) { q += 7; SKIP_BLANKS(q); if (*q == '=') { q++; SKIP_BLANKS(q); meta_charset = wc_guess_charset(q, 0); } } else #endif if (p && q && !strcasecmp(p, "refresh")) { int refresh_interval; tmp = NULL; refresh_interval = getMetaRefreshParam(q, &tmp); if (tmp) { q = html_quote(tmp->ptr); tmp = Sprintf("Refresh (%d sec) <a href=\"%s\">%s</a>", refresh_interval, q, q); } else if (refresh_interval > 0) tmp = Sprintf("Refresh (%d sec)", refresh_interval); if (tmp) { HTMLlineproc1(tmp->ptr, h_env); do_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); if (!is_redisplay && !((obuf->flag & RB_NOFRAMES) && RenderFrame)) { tag->need_reconstruct = TRUE; return 0; } } } return 1; case HTML_BASE: #if defined(USE_M17N) || defined(USE_IMAGE) p = NULL; if (parsedtag_get_value(tag, ATTR_HREF, &p)) { cur_baseURL = New(ParsedURL); parseURL(p, cur_baseURL, NULL); } #endif case HTML_MAP: case HTML_N_MAP: case HTML_AREA: return 0; case HTML_DEL: switch (displayInsDel) { case DISPLAY_INS_DEL_SIMPLE: obuf->flag |= RB_DEL; break; case DISPLAY_INS_DEL_NORMAL: HTMLlineproc1("<U>[DEL:</U>", h_env); break; case DISPLAY_INS_DEL_FONTIFY: obuf->in_strike++; if (obuf->in_strike == 1) { push_tag(obuf, "<s>", HTML_S); } break; } return 1; case HTML_N_DEL: switch (displayInsDel) { case DISPLAY_INS_DEL_SIMPLE: obuf->flag &= ~RB_DEL; break; case DISPLAY_INS_DEL_NORMAL: HTMLlineproc1("<U>:DEL]</U>", h_env); case DISPLAY_INS_DEL_FONTIFY: if (obuf->in_strike == 0) return 1; if (obuf->in_strike == 1 && close_effect0(obuf, HTML_S)) obuf->in_strike = 0; if (obuf->in_strike > 0) { obuf->in_strike--; if (obuf->in_strike == 0) { push_tag(obuf, "</s>", HTML_N_S); } } break; } return 1; case HTML_S: switch (displayInsDel) { case DISPLAY_INS_DEL_SIMPLE: obuf->flag |= RB_S; break; case DISPLAY_INS_DEL_NORMAL: HTMLlineproc1("<U>[S:</U>", h_env); break; case DISPLAY_INS_DEL_FONTIFY: obuf->in_strike++; if (obuf->in_strike == 1) { push_tag(obuf, "<s>", HTML_S); } break; } return 1; case HTML_N_S: switch (displayInsDel) { case DISPLAY_INS_DEL_SIMPLE: obuf->flag &= ~RB_S; break; case DISPLAY_INS_DEL_NORMAL: HTMLlineproc1("<U>:S]</U>", h_env); break; case DISPLAY_INS_DEL_FONTIFY: if (obuf->in_strike == 0) return 1; if (obuf->in_strike == 1 && close_effect0(obuf, HTML_S)) obuf->in_strike = 0; if (obuf->in_strike > 0) { obuf->in_strike--; if (obuf->in_strike == 0) { push_tag(obuf, "</s>", HTML_N_S); } } } return 1; case HTML_INS: switch (displayInsDel) { case DISPLAY_INS_DEL_SIMPLE: break; case DISPLAY_INS_DEL_NORMAL: HTMLlineproc1("<U>[INS:</U>", h_env); break; case DISPLAY_INS_DEL_FONTIFY: obuf->in_ins++; if (obuf->in_ins == 1) { push_tag(obuf, "<ins>", HTML_INS); } break; } return 1; case HTML_N_INS: switch (displayInsDel) { case DISPLAY_INS_DEL_SIMPLE: break; case DISPLAY_INS_DEL_NORMAL: HTMLlineproc1("<U>:INS]</U>", h_env); break; case DISPLAY_INS_DEL_FONTIFY: if (obuf->in_ins == 0) return 1; if (obuf->in_ins == 1 && close_effect0(obuf, HTML_INS)) obuf->in_ins = 0; if (obuf->in_ins > 0) { obuf->in_ins--; if (obuf->in_ins == 0) { push_tag(obuf, "</ins>", HTML_N_INS); } } break; } return 1; case HTML_SUP: if (!(obuf->flag & (RB_DEL | RB_S))) HTMLlineproc1("^", h_env); return 1; case HTML_N_SUP: return 1; case HTML_SUB: if (!(obuf->flag & (RB_DEL | RB_S))) HTMLlineproc1("[", h_env); return 1; case HTML_N_SUB: if (!(obuf->flag & (RB_DEL | RB_S))) HTMLlineproc1("]", h_env); return 1; case HTML_FONT: case HTML_N_FONT: case HTML_NOP: return 1; case HTML_BGSOUND: if (view_unseenobject) { if (parsedtag_get_value(tag, ATTR_SRC, &p)) { Str s; q = html_quote(p); s = Sprintf("<A HREF=\"%s\">bgsound(%s)</A>", q, q); HTMLlineproc1(s->ptr, h_env); } } return 1; case HTML_EMBED: if (view_unseenobject) { if (parsedtag_get_value(tag, ATTR_SRC, &p)) { Str s; q = html_quote(p); s = Sprintf("<A HREF=\"%s\">embed(%s)</A>", q, q); HTMLlineproc1(s->ptr, h_env); } } return 1; case HTML_APPLET: if (view_unseenobject) { if (parsedtag_get_value(tag, ATTR_ARCHIVE, &p)) { Str s; q = html_quote(p); s = Sprintf("<A HREF=\"%s\">applet archive(%s)</A>", q, q); HTMLlineproc1(s->ptr, h_env); } } return 1; case HTML_BODY: if (view_unseenobject) { if (parsedtag_get_value(tag, ATTR_BACKGROUND, &p)) { Str s; q = html_quote(p); s = Sprintf("<IMG SRC=\"%s\" ALT=\"bg image(%s)\"><BR>", q, q); HTMLlineproc1(s->ptr, h_env); } } case HTML_N_HEAD: if (obuf->flag & RB_TITLE) HTMLlineproc1("</title>", h_env); case HTML_HEAD: case HTML_N_BODY: return 1; default: /* obuf->prevchar = '\0'; */ return 0; } /* not reached */ return 0; } #define PPUSH(p,c) {outp[pos]=(p);outc[pos]=(c);pos++;} #define PSIZE \ if (out_size <= pos + 1) { \ out_size = pos * 3 / 2; \ outc = New_Reuse(char, outc, out_size); \ outp = New_Reuse(Lineprop, outp, out_size); \ } static TextLineListItem *_tl_lp2; static Str textlist_feed() { TextLine *p; if (_tl_lp2 != NULL) { p = _tl_lp2->ptr; _tl_lp2 = _tl_lp2->next; return p->line; } return NULL; } static int ex_efct(int ex) { int effect = 0; if (! ex) return 0; if (ex & PE_EX_ITALIC) effect |= PE_EX_ITALIC_E; if (ex & PE_EX_INSERT) effect |= PE_EX_INSERT_E; if (ex & PE_EX_STRIKE) effect |= PE_EX_STRIKE_E; return effect; } static void HTMLlineproc2body(Buffer *buf, Str (*feed) (), int llimit) { static char *outc = NULL; static Lineprop *outp = NULL; static int out_size = 0; Anchor *a_href = NULL, *a_img = NULL, *a_form = NULL; char *p, *q, *r, *s, *t, *str; Lineprop mode, effect, ex_effect; int pos; int nlines; #ifdef DEBUG FILE *debug = NULL; #endif struct frameset *frameset_s[FRAMESTACK_SIZE]; int frameset_sp = -1; union frameset_element *idFrame = NULL; char *id = NULL; int hseq, form_id; Str line; char *endp; char symbol = '\0'; int internal = 0; Anchor **a_textarea = NULL; #ifdef MENU_SELECT Anchor **a_select = NULL; #endif #if defined(USE_M17N) || defined(USE_IMAGE) ParsedURL *base = baseURL(buf); #endif #ifdef USE_M17N wc_ces name_charset = url_to_charset(NULL, &buf->currentURL, buf->document_charset); #endif if (out_size == 0) { out_size = LINELEN; outc = NewAtom_N(char, out_size); outp = NewAtom_N(Lineprop, out_size); } n_textarea = -1; if (!max_textarea) { /* halfload */ max_textarea = MAX_TEXTAREA; textarea_str = New_N(Str, max_textarea); a_textarea = New_N(Anchor *, max_textarea); } #ifdef MENU_SELECT n_select = -1; if (!max_select) { /* halfload */ max_select = MAX_SELECT; select_option = New_N(FormSelectOption, max_select); a_select = New_N(Anchor *, max_select); } #endif #ifdef DEBUG if (w3m_debug) debug = fopen("zzzerr", "a"); #endif effect = 0; ex_effect = 0; nlines = 0; while ((line = feed()) != NULL) { #ifdef DEBUG if (w3m_debug) { Strfputs(line, debug); fputc('\n', debug); } #endif if (n_textarea >= 0 && *(line->ptr) != '<') { /* halfload */ Strcat(textarea_str[n_textarea], line); continue; } proc_again: if (++nlines == llimit) break; pos = 0; #ifdef ENABLE_REMOVE_TRAILINGSPACES Strremovetrailingspaces(line); #endif str = line->ptr; endp = str + line->length; while (str < endp) { PSIZE; mode = get_mctype(str); if ((effect | ex_efct(ex_effect)) & PC_SYMBOL && *str != '<') { #ifdef USE_M17N char **buf = set_symbol(symbol_width0); int len; p = buf[(int)symbol]; len = get_mclen(p); mode = get_mctype(p); PPUSH(mode | effect | ex_efct(ex_effect), *(p++)); if (--len) { mode = (mode & ~PC_WCHAR1) | PC_WCHAR2; while (len--) { PSIZE; PPUSH(mode | effect | ex_efct(ex_effect), *(p++)); } } #else PPUSH(PC_ASCII | effect | ex_efct(ex_effect), SYMBOL_BASE + symbol); #endif str += symbol_width; } #ifdef USE_M17N else if (mode == PC_CTRL || mode == PC_UNDEF) { #else else if (mode == PC_CTRL || IS_INTSPACE(*str)) { #endif PPUSH(PC_ASCII | effect | ex_efct(ex_effect), ' '); str++; } #ifdef USE_M17N else if (mode & PC_UNKNOWN) { PPUSH(PC_ASCII | effect | ex_efct(ex_effect), ' '); str += get_mclen(str); } #endif else if (*str != '<' && *str != '&') { #ifdef USE_M17N int len = get_mclen(str); #endif PPUSH(mode | effect | ex_efct(ex_effect), *(str++)); #ifdef USE_M17N if (--len) { mode = (mode & ~PC_WCHAR1) | PC_WCHAR2; while (len--) { PSIZE; PPUSH(mode | effect | ex_efct(ex_effect), *(str++)); } } #endif } else if (*str == '&') { /* * & escape processing */ p = getescapecmd(&str); while (*p) { PSIZE; mode = get_mctype((unsigned char *)p); #ifdef USE_M17N if (mode == PC_CTRL || mode == PC_UNDEF) { #else if (mode == PC_CTRL || IS_INTSPACE(*str)) { #endif PPUSH(PC_ASCII | effect | ex_efct(ex_effect), ' '); p++; } #ifdef USE_M17N else if (mode & PC_UNKNOWN) { PPUSH(PC_ASCII | effect | ex_efct(ex_effect), ' '); p += get_mclen(p); } #endif else { #ifdef USE_M17N int len = get_mclen(p); #endif PPUSH(mode | effect | ex_efct(ex_effect), *(p++)); #ifdef USE_M17N if (--len) { mode = (mode & ~PC_WCHAR1) | PC_WCHAR2; while (len--) { PSIZE; PPUSH(mode | effect | ex_efct(ex_effect), *(p++)); } } #endif } } } else { /* tag processing */ struct parsed_tag *tag; if (!(tag = parse_tag(&str, TRUE))) continue; switch (tag->tagid) { case HTML_B: effect |= PE_BOLD; break; case HTML_N_B: effect &= ~PE_BOLD; break; case HTML_I: ex_effect |= PE_EX_ITALIC; break; case HTML_N_I: ex_effect &= ~PE_EX_ITALIC; break; case HTML_INS: ex_effect |= PE_EX_INSERT; break; case HTML_N_INS: ex_effect &= ~PE_EX_INSERT; break; case HTML_U: effect |= PE_UNDER; break; case HTML_N_U: effect &= ~PE_UNDER; break; case HTML_S: ex_effect |= PE_EX_STRIKE; break; case HTML_N_S: ex_effect &= ~PE_EX_STRIKE; break; case HTML_A: if (renderFrameSet && parsedtag_get_value(tag, ATTR_FRAMENAME, &p)) { p = url_quote_conv(p, buf->document_charset); if (!idFrame || strcmp(idFrame->body->name, p)) { idFrame = search_frame(renderFrameSet, p); if (idFrame && idFrame->body->attr != F_BODY) idFrame = NULL; } } p = r = s = NULL; q = buf->baseTarget; t = ""; hseq = 0; id = NULL; if (parsedtag_get_value(tag, ATTR_NAME, &id)) { id = url_quote_conv(id, name_charset); registerName(buf, id, currentLn(buf), pos); } if (parsedtag_get_value(tag, ATTR_HREF, &p)) p = url_encode(remove_space(p), base, buf->document_charset); if (parsedtag_get_value(tag, ATTR_TARGET, &q)) q = url_quote_conv(q, buf->document_charset); if (parsedtag_get_value(tag, ATTR_REFERER, &r)) r = url_encode(r, base, buf->document_charset); parsedtag_get_value(tag, ATTR_TITLE, &s); parsedtag_get_value(tag, ATTR_ACCESSKEY, &t); parsedtag_get_value(tag, ATTR_HSEQ, &hseq); if (hseq > 0) buf->hmarklist = putHmarker(buf->hmarklist, currentLn(buf), pos, hseq - 1); else if (hseq < 0) { int h = -hseq - 1; if (buf->hmarklist && h < buf->hmarklist->nmark && buf->hmarklist->marks[h].invalid) { buf->hmarklist->marks[h].pos = pos; buf->hmarklist->marks[h].line = currentLn(buf); buf->hmarklist->marks[h].invalid = 0; hseq = -hseq; } } if (id && idFrame) idFrame->body->nameList = putAnchor(idFrame->body->nameList, id, NULL, (Anchor **)NULL, NULL, NULL, '\0', currentLn(buf), pos); if (p) { effect |= PE_ANCHOR; a_href = registerHref(buf, p, q, r, s, *t, currentLn(buf), pos); a_href->hseq = ((hseq > 0) ? hseq : -hseq) - 1; a_href->slave = (hseq > 0) ? FALSE : TRUE; } break; case HTML_N_A: effect &= ~PE_ANCHOR; if (a_href) { a_href->end.line = currentLn(buf); a_href->end.pos = pos; if (a_href->start.line == a_href->end.line && a_href->start.pos == a_href->end.pos) { if (buf->hmarklist && a_href->hseq < buf->hmarklist->nmark) buf->hmarklist->marks[a_href->hseq].invalid = 1; a_href->hseq = -1; } a_href = NULL; } break; case HTML_LINK: addLink(buf, tag); break; case HTML_IMG_ALT: if (parsedtag_get_value(tag, ATTR_SRC, &p)) { #ifdef USE_IMAGE int w = -1, h = -1, iseq = 0, ismap = 0; int xoffset = 0, yoffset = 0, top = 0, bottom = 0; parsedtag_get_value(tag, ATTR_HSEQ, &iseq); parsedtag_get_value(tag, ATTR_WIDTH, &w); parsedtag_get_value(tag, ATTR_HEIGHT, &h); parsedtag_get_value(tag, ATTR_XOFFSET, &xoffset); parsedtag_get_value(tag, ATTR_YOFFSET, &yoffset); parsedtag_get_value(tag, ATTR_TOP_MARGIN, &top); parsedtag_get_value(tag, ATTR_BOTTOM_MARGIN, &bottom); if (parsedtag_exists(tag, ATTR_ISMAP)) ismap = 1; q = NULL; parsedtag_get_value(tag, ATTR_USEMAP, &q); if (iseq > 0) { buf->imarklist = putHmarker(buf->imarklist, currentLn(buf), pos, iseq - 1); } #endif s = NULL; parsedtag_get_value(tag, ATTR_TITLE, &s); p = url_quote_conv(remove_space(p), buf->document_charset); a_img = registerImg(buf, p, s, currentLn(buf), pos); #ifdef USE_IMAGE a_img->hseq = iseq; a_img->image = NULL; if (iseq > 0) { ParsedURL u; Image *image; parseURL2(a_img->url, &u, base); a_img->image = image = New(Image); image->url = parsedURL2Str(&u)->ptr; if (!uncompressed_file_type(u.file, &image->ext)) image->ext = filename_extension(u.file, TRUE); image->cache = NULL; image->width = (w > MAX_IMAGE_SIZE) ? MAX_IMAGE_SIZE : w; image->height = (h > MAX_IMAGE_SIZE) ? MAX_IMAGE_SIZE : h; image->xoffset = xoffset; image->yoffset = yoffset; image->y = currentLn(buf) - top; if (image->xoffset < 0 && pos == 0) image->xoffset = 0; if (image->yoffset < 0 && image->y == 1) image->yoffset = 0; image->rows = 1 + top + bottom; image->map = q; image->ismap = ismap; image->touch = 0; image->cache = getImage(image, base, IMG_FLAG_SKIP); } else if (iseq < 0) { BufferPoint *po = buf->imarklist->marks - iseq - 1; Anchor *a = retrieveAnchor(buf->img, po->line, po->pos); if (a) { a_img->url = a->url; a_img->image = a->image; } } #endif } effect |= PE_IMAGE; break; case HTML_N_IMG_ALT: effect &= ~PE_IMAGE; if (a_img) { a_img->end.line = currentLn(buf); a_img->end.pos = pos; } a_img = NULL; break; case HTML_INPUT_ALT: { FormList *form; int top = 0, bottom = 0; int textareanumber = -1; #ifdef MENU_SELECT int selectnumber = -1; #endif hseq = 0; form_id = -1; parsedtag_get_value(tag, ATTR_HSEQ, &hseq); parsedtag_get_value(tag, ATTR_FID, &form_id); parsedtag_get_value(tag, ATTR_TOP_MARGIN, &top); parsedtag_get_value(tag, ATTR_BOTTOM_MARGIN, &bottom); if (form_id < 0 || form_id > form_max || forms == NULL) break; /* outside of <form>..</form> */ form = forms[form_id]; if (hseq > 0) { int hpos = pos; if (*str == '[') hpos++; buf->hmarklist = putHmarker(buf->hmarklist, currentLn(buf), hpos, hseq - 1); } else if (hseq < 0) { int h = -hseq - 1; int hpos = pos; if (*str == '[') hpos++; if (buf->hmarklist && h < buf->hmarklist->nmark && buf->hmarklist->marks[h].invalid) { buf->hmarklist->marks[h].pos = hpos; buf->hmarklist->marks[h].line = currentLn(buf); buf->hmarklist->marks[h].invalid = 0; hseq = -hseq; } } if (!form->target) form->target = buf->baseTarget; if (a_textarea && parsedtag_get_value(tag, ATTR_TEXTAREANUMBER, &textareanumber)) { if (textareanumber >= max_textarea) { max_textarea = 2 * textareanumber; textarea_str = New_Reuse(Str, textarea_str, max_textarea); a_textarea = New_Reuse(Anchor *, a_textarea, max_textarea); } } #ifdef MENU_SELECT if (a_select && parsedtag_get_value(tag, ATTR_SELECTNUMBER, &selectnumber)) { if (selectnumber >= max_select) { max_select = 2 * selectnumber; select_option = New_Reuse(FormSelectOption, select_option, max_select); a_select = New_Reuse(Anchor *, a_select, max_select); } } #endif a_form = registerForm(buf, form, tag, currentLn(buf), pos); if (a_textarea && textareanumber >= 0) a_textarea[textareanumber] = a_form; #ifdef MENU_SELECT if (a_select && selectnumber >= 0) a_select[selectnumber] = a_form; #endif if (a_form) { a_form->hseq = hseq - 1; a_form->y = currentLn(buf) - top; a_form->rows = 1 + top + bottom; if (!parsedtag_exists(tag, ATTR_NO_EFFECT)) effect |= PE_FORM; break; } } case HTML_N_INPUT_ALT: effect &= ~PE_FORM; if (a_form) { a_form->end.line = currentLn(buf); a_form->end.pos = pos; if (a_form->start.line == a_form->end.line && a_form->start.pos == a_form->end.pos) a_form->hseq = -1; } a_form = NULL; break; case HTML_MAP: if (parsedtag_get_value(tag, ATTR_NAME, &p)) { MapList *m = New(MapList); m->name = Strnew_charp(p); m->area = newGeneralList(); m->next = buf->maplist; buf->maplist = m; } break; case HTML_N_MAP: /* nothing to do */ break; case HTML_AREA: if (buf->maplist == NULL) /* outside of <map>..</map> */ break; if (parsedtag_get_value(tag, ATTR_HREF, &p)) { MapArea *a; p = url_encode(remove_space(p), base, buf->document_charset); t = NULL; parsedtag_get_value(tag, ATTR_TARGET, &t); q = ""; parsedtag_get_value(tag, ATTR_ALT, &q); r = NULL; s = NULL; #ifdef USE_IMAGE parsedtag_get_value(tag, ATTR_SHAPE, &r); parsedtag_get_value(tag, ATTR_COORDS, &s); #endif a = newMapArea(p, t, q, r, s); pushValue(buf->maplist->area, (void *)a); } break; case HTML_FRAMESET: frameset_sp++; if (frameset_sp >= FRAMESTACK_SIZE) break; frameset_s[frameset_sp] = newFrameSet(tag); if (frameset_s[frameset_sp] == NULL) break; if (frameset_sp == 0) { if (buf->frameset == NULL) { buf->frameset = frameset_s[frameset_sp]; } else pushFrameTree(&(buf->frameQ), frameset_s[frameset_sp], NULL); } else addFrameSetElement(frameset_s[frameset_sp - 1], *(union frameset_element *) &frameset_s[frameset_sp]); break; case HTML_N_FRAMESET: if (frameset_sp >= 0) frameset_sp--; break; case HTML_FRAME: if (frameset_sp >= 0 && frameset_sp < FRAMESTACK_SIZE) { union frameset_element element; element.body = newFrame(tag, buf); addFrameSetElement(frameset_s[frameset_sp], element); } break; case HTML_BASE: if (parsedtag_get_value(tag, ATTR_HREF, &p)) { p = url_encode(remove_space(p), NULL, buf->document_charset); if (!buf->baseURL) buf->baseURL = New(ParsedURL); parseURL(p, buf->baseURL, NULL); #if defined(USE_M17N) || defined(USE_IMAGE) base = buf->baseURL; #endif } if (parsedtag_get_value(tag, ATTR_TARGET, &p)) buf->baseTarget = url_quote_conv(p, buf->document_charset); break; case HTML_META: p = q = NULL; parsedtag_get_value(tag, ATTR_HTTP_EQUIV, &p); parsedtag_get_value(tag, ATTR_CONTENT, &q); if (p && q && !strcasecmp(p, "refresh") && MetaRefresh) { Str tmp = NULL; int refresh_interval = getMetaRefreshParam(q, &tmp); #ifdef USE_ALARM if (tmp) { p = url_encode(remove_space(tmp->ptr), base, buf->document_charset); buf->event = setAlarmEvent(buf->event, refresh_interval, AL_IMPLICIT_ONCE, FUNCNAME_gorURL, p); } else if (refresh_interval > 0) buf->event = setAlarmEvent(buf->event, refresh_interval, AL_IMPLICIT, FUNCNAME_reload, NULL); #else if (tmp && refresh_interval == 0) { p = url_encode(remove_space(tmp->ptr), base, buf->document_charset); pushEvent(FUNCNAME_gorURL, p); } #endif } break; case HTML_INTERNAL: internal = HTML_INTERNAL; break; case HTML_N_INTERNAL: internal = HTML_N_INTERNAL; break; case HTML_FORM_INT: if (parsedtag_get_value(tag, ATTR_FID, &form_id)) process_form_int(tag, form_id); break; case HTML_TEXTAREA_INT: if (parsedtag_get_value(tag, ATTR_TEXTAREANUMBER, &n_textarea) && n_textarea >= 0 && n_textarea < max_textarea) { textarea_str[n_textarea] = Strnew(); } else n_textarea = -1; break; case HTML_N_TEXTAREA_INT: if (n_textarea >= 0) { FormItemList *item = (FormItemList *)a_textarea[n_textarea]->url; item->init_value = item->value = textarea_str[n_textarea]; } break; #ifdef MENU_SELECT case HTML_SELECT_INT: if (parsedtag_get_value(tag, ATTR_SELECTNUMBER, &n_select) && n_select >= 0 && n_select < max_select) { select_option[n_select].first = NULL; select_option[n_select].last = NULL; } else n_select = -1; break; case HTML_N_SELECT_INT: if (n_select >= 0) { FormItemList *item = (FormItemList *)a_select[n_select]->url; item->select_option = select_option[n_select].first; chooseSelectOption(item, item->select_option); item->init_selected = item->selected; item->init_value = item->value; item->init_label = item->label; } break; case HTML_OPTION_INT: if (n_select >= 0) { int selected; q = ""; parsedtag_get_value(tag, ATTR_LABEL, &q); p = q; parsedtag_get_value(tag, ATTR_VALUE, &p); selected = parsedtag_exists(tag, ATTR_SELECTED); addSelectOption(&select_option[n_select], Strnew_charp(p), Strnew_charp(q), selected); } break; #endif case HTML_TITLE_ALT: if (parsedtag_get_value(tag, ATTR_TITLE, &p)) buf->buffername = html_unquote(p); break; case HTML_SYMBOL: effect |= PC_SYMBOL; if (parsedtag_get_value(tag, ATTR_TYPE, &p)) symbol = (char)atoi(p); break; case HTML_N_SYMBOL: effect &= ~PC_SYMBOL; break; } #ifdef ID_EXT id = NULL; if (parsedtag_get_value(tag, ATTR_ID, &id)) { id = url_quote_conv(id, name_charset); registerName(buf, id, currentLn(buf), pos); } if (renderFrameSet && parsedtag_get_value(tag, ATTR_FRAMENAME, &p)) { p = url_quote_conv(p, buf->document_charset); if (!idFrame || strcmp(idFrame->body->name, p)) { idFrame = search_frame(renderFrameSet, p); if (idFrame && idFrame->body->attr != F_BODY) idFrame = NULL; } } if (id && idFrame) idFrame->body->nameList = putAnchor(idFrame->body->nameList, id, NULL, (Anchor **)NULL, NULL, NULL, '\0', currentLn(buf), pos); #endif /* ID_EXT */ } } /* end of processing for one line */ if (!internal) addnewline(buf, outc, outp, NULL, pos, -1, nlines); if (internal == HTML_N_INTERNAL) internal = 0; if (str != endp) { line = Strsubstr(line, str - line->ptr, endp - str); goto proc_again; } } #ifdef DEBUG if (w3m_debug) fclose(debug); #endif for (form_id = 1; form_id <= form_max; form_id++) if (forms[form_id]) forms[form_id]->next = forms[form_id - 1]; buf->formlist = (form_max >= 0) ? forms[form_max] : NULL; if (n_textarea) addMultirowsForm(buf, buf->formitem); #ifdef USE_IMAGE addMultirowsImg(buf, buf->img); #endif } static void addLink(Buffer *buf, struct parsed_tag *tag) { char *href = NULL, *title = NULL, *ctype = NULL, *rel = NULL, *rev = NULL; char type = LINK_TYPE_NONE; LinkList *l; parsedtag_get_value(tag, ATTR_HREF, &href); if (href) href = url_encode(remove_space(href), baseURL(buf), buf->document_charset); parsedtag_get_value(tag, ATTR_TITLE, &title); parsedtag_get_value(tag, ATTR_TYPE, &ctype); parsedtag_get_value(tag, ATTR_REL, &rel); if (rel != NULL) { /* forward link type */ type = LINK_TYPE_REL; if (title == NULL) title = rel; } parsedtag_get_value(tag, ATTR_REV, &rev); if (rev != NULL) { /* reverse link type */ type = LINK_TYPE_REV; if (title == NULL) title = rev; } l = New(LinkList); l->url = href; l->title = title; l->ctype = ctype; l->type = type; l->next = NULL; if (buf->linklist) { LinkList *i; for (i = buf->linklist; i->next; i = i->next) ; i->next = l; } else buf->linklist = l; } void HTMLlineproc2(Buffer *buf, TextLineList *tl) { _tl_lp2 = tl->first; HTMLlineproc2body(buf, textlist_feed, -1); } static InputStream _file_lp2; static Str file_feed() { Str s; s = StrISgets(_file_lp2); if (s->length == 0) { ISclose(_file_lp2); return NULL; } return s; } void HTMLlineproc3(Buffer *buf, InputStream stream) { _file_lp2 = stream; HTMLlineproc2body(buf, file_feed, -1); } static void proc_escape(struct readbuffer *obuf, char **str_return) { char *str = *str_return, *estr; int ech = getescapechar(str_return); int width, n_add = *str_return - str; Lineprop mode = PC_ASCII; if (ech < 0) { *str_return = str; proc_mchar(obuf, obuf->flag & RB_SPECIAL, 1, str_return, PC_ASCII); return; } mode = IS_CNTRL(ech) ? PC_CTRL : PC_ASCII; estr = conv_entity(ech); check_breakpoint(obuf, obuf->flag & RB_SPECIAL, estr); width = get_strwidth(estr); if (width == 1 && ech == (unsigned char)*estr && ech != '&' && ech != '<' && ech != '>') { if (IS_CNTRL(ech)) mode = PC_CTRL; push_charp(obuf, width, estr, mode); } else push_nchars(obuf, width, str, n_add, mode); set_prevchar(obuf->prevchar, estr, strlen(estr)); obuf->prev_ctype = mode; } static int need_flushline(struct html_feed_environ *h_env, struct readbuffer *obuf, Lineprop mode) { char ch; if (obuf->flag & RB_PRE_INT) { if (obuf->pos > h_env->limit) return 1; else return 0; } ch = Strlastchar(obuf->line); /* if (ch == ' ' && obuf->tag_sp > 0) */ if (ch == ' ') return 0; if (obuf->pos > h_env->limit) return 1; return 0; } static int table_width(struct html_feed_environ *h_env, int table_level) { int width; if (table_level < 0) return 0; width = tables[table_level]->total_width; if (table_level > 0 || width > 0) return width; return h_env->limit - h_env->envs[h_env->envc].indent; } /* HTML processing first pass */ void HTMLlineproc0(char *line, struct html_feed_environ *h_env, int internal) { Lineprop mode; int cmd; struct readbuffer *obuf = h_env->obuf; int indent, delta; struct parsed_tag *tag; Str tokbuf; struct table *tbl = NULL; struct table_mode *tbl_mode = NULL; int tbl_width = 0; #ifdef USE_M17N int is_hangul, prev_is_hangul = 0; #endif #ifdef DEBUG if (w3m_debug) { FILE *f = fopen("zzzproc1", "a"); fprintf(f, "%c%c%c%c", (obuf->flag & RB_PREMODE) ? 'P' : ' ', (obuf->table_level >= 0) ? 'T' : ' ', (obuf->flag & RB_INTXTA) ? 'X' : ' ', (obuf->flag & (RB_SCRIPT | RB_STYLE)) ? 'S' : ' '); fprintf(f, "HTMLlineproc1(\"%s\",%d,%lx)\n", line, h_env->limit, (unsigned long)h_env); fclose(f); } #endif tokbuf = Strnew(); table_start: if (obuf->table_level >= 0) { int level = min(obuf->table_level, MAX_TABLE - 1); tbl = tables[level]; tbl_mode = &table_mode[level]; tbl_width = table_width(h_env, level); } while (*line != '\0') { char *str, *p; int is_tag = FALSE; int pre_mode = (obuf->table_level >= 0) ? tbl_mode->pre_mode : obuf->flag; int end_tag = (obuf->table_level >= 0) ? tbl_mode->end_tag : obuf->end_tag; if (*line == '<' || obuf->status != R_ST_NORMAL) { /* * Tag processing */ if (obuf->status == R_ST_EOL) obuf->status = R_ST_NORMAL; else { read_token(h_env->tagbuf, &line, &obuf->status, pre_mode & RB_PREMODE, obuf->status != R_ST_NORMAL); if (obuf->status != R_ST_NORMAL) return; } if (h_env->tagbuf->length == 0) continue; str = h_env->tagbuf->ptr; if (*str == '<') { if (str[1] && REALLY_THE_BEGINNING_OF_A_TAG(str)) is_tag = TRUE; else if (!(pre_mode & (RB_PLAIN | RB_INTXTA | RB_INSELECT | RB_SCRIPT | RB_STYLE | RB_TITLE))) { line = Strnew_m_charp(str + 1, line, NULL)->ptr; str = "&lt;"; } } } else { read_token(tokbuf, &line, &obuf->status, pre_mode & RB_PREMODE, 0); if (obuf->status != R_ST_NORMAL) /* R_ST_AMP ? */ obuf->status = R_ST_NORMAL; str = tokbuf->ptr; } if (pre_mode & (RB_PLAIN | RB_INTXTA | RB_INSELECT | RB_SCRIPT | RB_STYLE | RB_TITLE)) { if (is_tag) { p = str; if ((tag = parse_tag(&p, internal))) { if (tag->tagid == end_tag || (pre_mode & RB_INSELECT && tag->tagid == HTML_N_FORM) || (pre_mode & RB_TITLE && (tag->tagid == HTML_N_HEAD || tag->tagid == HTML_BODY))) goto proc_normal; } } /* title */ if (pre_mode & RB_TITLE) { feed_title(str); continue; } /* select */ if (pre_mode & RB_INSELECT) { if (obuf->table_level >= 0) goto proc_normal; feed_select(str); continue; } if (is_tag) { if (strncmp(str, "<!--", 4) && (p = strchr(str + 1, '<'))) { str = Strnew_charp_n(str, p - str)->ptr; line = Strnew_m_charp(p, line, NULL)->ptr; } is_tag = FALSE; } if (obuf->table_level >= 0) goto proc_normal; /* textarea */ if (pre_mode & RB_INTXTA) { feed_textarea(str); continue; } /* script */ if (pre_mode & RB_SCRIPT) continue; /* style */ if (pre_mode & RB_STYLE) continue; } proc_normal: if (obuf->table_level >= 0) { /* * within table: in <table>..</table>, all input tokens * are fed to the table renderer, and then the renderer * makes HTML output. */ switch (feed_table(tbl, str, tbl_mode, tbl_width, internal)) { case 0: /* </table> tag */ obuf->table_level--; if (obuf->table_level >= MAX_TABLE - 1) continue; end_table(tbl); if (obuf->table_level >= 0) { struct table *tbl0 = tables[obuf->table_level]; str = Sprintf("<table_alt tid=%d>", tbl0->ntable)->ptr; pushTable(tbl0, tbl); tbl = tbl0; tbl_mode = &table_mode[obuf->table_level]; tbl_width = table_width(h_env, obuf->table_level); feed_table(tbl, str, tbl_mode, tbl_width, TRUE); continue; /* continue to the next */ } if (obuf->flag & RB_DEL) continue; /* all tables have been read */ if (tbl->vspace > 0 && !(obuf->flag & RB_IGNORE_P)) { int indent = h_env->envs[h_env->envc].indent; flushline(h_env, obuf, indent, 0, h_env->limit); do_blankline(h_env, obuf, indent, 0, h_env->limit); } save_fonteffect(h_env, obuf); renderTable(tbl, tbl_width, h_env); restore_fonteffect(h_env, obuf); obuf->flag &= ~RB_IGNORE_P; if (tbl->vspace > 0) { int indent = h_env->envs[h_env->envc].indent; do_blankline(h_env, obuf, indent, 0, h_env->limit); obuf->flag |= RB_IGNORE_P; } set_space_to_prevchar(obuf->prevchar); continue; case 1: /* <table> tag */ break; default: continue; } } if (is_tag) { /*** Beginning of a new tag ***/ if ((tag = parse_tag(&str, internal))) cmd = tag->tagid; else continue; /* process tags */ if (HTMLtagproc1(tag, h_env) == 0) { /* preserve the tag for second-stage processing */ if (parsedtag_need_reconstruct(tag)) h_env->tagbuf = parsedtag2str(tag); push_tag(obuf, h_env->tagbuf->ptr, cmd); } #ifdef ID_EXT else { process_idattr(obuf, cmd, tag); } #endif /* ID_EXT */ obuf->bp.init_flag = 1; clear_ignore_p_flag(cmd, obuf); if (cmd == HTML_TABLE) goto table_start; else continue; } if (obuf->flag & (RB_DEL | RB_S)) continue; while (*str) { mode = get_mctype(str); delta = get_mcwidth(str); if (obuf->flag & (RB_SPECIAL & ~RB_NOBR)) { char ch = *str; if (!(obuf->flag & RB_PLAIN) && (*str == '&')) { char *p = str; int ech = getescapechar(&p); if (ech == '\n' || ech == '\r') { ch = '\n'; str = p - 1; } else if (ech == '\t') { ch = '\t'; str = p - 1; } } if (ch != '\n') obuf->flag &= ~RB_IGNORE_P; if (ch == '\n') { str++; if (obuf->flag & RB_IGNORE_P) { obuf->flag &= ~RB_IGNORE_P; continue; } if (obuf->flag & RB_PRE_INT) PUSH(' '); else flushline(h_env, obuf, h_env->envs[h_env->envc].indent, 1, h_env->limit); } else if (ch == '\t') { do { PUSH(' '); } while ((h_env->envs[h_env->envc].indent + obuf->pos) % Tabstop != 0); str++; } else if (obuf->flag & RB_PLAIN) { char *p = html_quote_char(*str); if (p) { push_charp(obuf, 1, p, PC_ASCII); str++; } else { proc_mchar(obuf, 1, delta, &str, mode); } } else { if (*str == '&') proc_escape(obuf, &str); else proc_mchar(obuf, 1, delta, &str, mode); } if (obuf->flag & (RB_SPECIAL & ~RB_PRE_INT)) continue; } else { if (!IS_SPACE(*str)) obuf->flag &= ~RB_IGNORE_P; if ((mode == PC_ASCII || mode == PC_CTRL) && IS_SPACE(*str)) { if (*obuf->prevchar->ptr != ' ') { PUSH(' '); } str++; } else { #ifdef USE_M17N if (mode == PC_KANJI1) is_hangul = wtf_is_hangul((wc_uchar *) str); else is_hangul = 0; if (!SimplePreserveSpace && mode == PC_KANJI1 && !is_hangul && !prev_is_hangul && obuf->pos > h_env->envs[h_env->envc].indent && Strlastchar(obuf->line) == ' ') { while (obuf->line->length >= 2 && !strncmp(obuf->line->ptr + obuf->line->length - 2, " ", 2) && obuf->pos >= h_env->envs[h_env->envc].indent) { Strshrink(obuf->line, 1); obuf->pos--; } if (obuf->line->length >= 3 && obuf->prev_ctype == PC_KANJI1 && Strlastchar(obuf->line) == ' ' && obuf->pos >= h_env->envs[h_env->envc].indent) { Strshrink(obuf->line, 1); obuf->pos--; } } prev_is_hangul = is_hangul; #endif if (*str == '&') proc_escape(obuf, &str); else proc_mchar(obuf, obuf->flag & RB_SPECIAL, delta, &str, mode); } } if (need_flushline(h_env, obuf, mode)) { char *bp = obuf->line->ptr + obuf->bp.len; char *tp = bp - obuf->bp.tlen; int i = 0; if (tp > obuf->line->ptr && tp[-1] == ' ') i = 1; indent = h_env->envs[h_env->envc].indent; if (obuf->bp.pos - i > indent) { Str line; append_tags(obuf); line = Strnew_charp(bp); Strshrink(obuf->line, obuf->line->length - obuf->bp.len); #ifdef FORMAT_NICE if (obuf->pos - i > h_env->limit) obuf->flag |= RB_FILL; #endif /* FORMAT_NICE */ back_to_breakpoint(obuf); flushline(h_env, obuf, indent, 0, h_env->limit); #ifdef FORMAT_NICE obuf->flag &= ~RB_FILL; #endif /* FORMAT_NICE */ HTMLlineproc1(line->ptr, h_env); } } } } if (!(obuf->flag & (RB_SPECIAL | RB_INTXTA | RB_INSELECT))) { char *tp; int i = 0; if (obuf->bp.pos == obuf->pos) { tp = &obuf->line->ptr[obuf->bp.len - obuf->bp.tlen]; } else { tp = &obuf->line->ptr[obuf->line->length]; } if (tp > obuf->line->ptr && tp[-1] == ' ') i = 1; indent = h_env->envs[h_env->envc].indent; if (obuf->pos - i > h_env->limit) { #ifdef FORMAT_NICE obuf->flag |= RB_FILL; #endif /* FORMAT_NICE */ flushline(h_env, obuf, indent, 0, h_env->limit); #ifdef FORMAT_NICE obuf->flag &= ~RB_FILL; #endif /* FORMAT_NICE */ } } } extern char *NullLine; extern Lineprop NullProp[]; #ifndef USE_ANSI_COLOR #define addnewline2(a,b,c,d,e,f) _addnewline2(a,b,c,e,f) #endif static void addnewline2(Buffer *buf, char *line, Lineprop *prop, Linecolor *color, int pos, int nlines) { Line *l; l = New(Line); l->next = NULL; l->lineBuf = line; l->propBuf = prop; #ifdef USE_ANSI_COLOR l->colorBuf = color; #endif l->len = pos; l->width = -1; l->size = pos; l->bpos = 0; l->bwidth = 0; l->prev = buf->currentLine; if (buf->currentLine) { l->next = buf->currentLine->next; buf->currentLine->next = l; } else l->next = NULL; if (buf->lastLine == NULL || buf->lastLine == buf->currentLine) buf->lastLine = l; buf->currentLine = l; if (buf->firstLine == NULL) buf->firstLine = l; l->linenumber = ++buf->allLine; if (nlines < 0) { /* l->real_linenumber = l->linenumber; */ l->real_linenumber = 0; } else { l->real_linenumber = nlines; } l = NULL; } static void addnewline(Buffer *buf, char *line, Lineprop *prop, Linecolor *color, int pos, int width, int nlines) { char *s; Lineprop *p; #ifdef USE_ANSI_COLOR Linecolor *c; #endif Line *l; int i, bpos, bwidth; if (pos > 0) { s = allocStr(line, pos); p = NewAtom_N(Lineprop, pos); bcopy((void *)prop, (void *)p, pos * sizeof(Lineprop)); } else { s = NullLine; p = NullProp; } #ifdef USE_ANSI_COLOR if (pos > 0 && color) { c = NewAtom_N(Linecolor, pos); bcopy((void *)color, (void *)c, pos * sizeof(Linecolor)); } else { c = NULL; } #endif addnewline2(buf, s, p, c, pos, nlines); if (pos <= 0 || width <= 0) return; bpos = 0; bwidth = 0; while (1) { l = buf->currentLine; l->bpos = bpos; l->bwidth = bwidth; i = columnLen(l, width); if (i == 0) { i++; #ifdef USE_M17N while (i < l->len && p[i] & PC_WCHAR2) i++; #endif } l->len = i; l->width = COLPOS(l, l->len); if (pos <= i) return; bpos += l->len; bwidth += l->width; s += i; p += i; #ifdef USE_ANSI_COLOR if (c) c += i; #endif pos -= i; addnewline2(buf, s, p, c, pos, nlines); } } /* * loadHTMLBuffer: read file and make new buffer */ Buffer * loadHTMLBuffer(URLFile *f, Buffer *newBuf) { FILE *src = NULL; Str tmp; if (newBuf == NULL) newBuf = newBuffer(INIT_BUFFER_WIDTH); if (newBuf->sourcefile == NULL && (f->scheme != SCM_LOCAL || newBuf->mailcap)) { tmp = tmpfname(TMPF_SRC, ".html"); src = fopen(tmp->ptr, "w"); if (src) newBuf->sourcefile = tmp->ptr; } loadHTMLstream(f, newBuf, src, newBuf->bufferprop & BP_FRAME); newBuf->topLine = newBuf->firstLine; newBuf->lastLine = newBuf->currentLine; newBuf->currentLine = newBuf->firstLine; if (n_textarea) formResetBuffer(newBuf, newBuf->formitem); if (src) fclose(src); return newBuf; } static char *_size_unit[] = { "b", "kb", "Mb", "Gb", "Tb", "Pb", "Eb", "Zb", "Bb", "Yb", NULL }; char * convert_size(clen_t size, int usefloat) { float csize; int sizepos = 0; char **sizes = _size_unit; csize = (float)size; while (csize >= 999.495 && sizes[sizepos + 1]) { csize = csize / 1024.0; sizepos++; } return Sprintf(usefloat ? "%.3g%s" : "%.0f%s", floor(csize * 100.0 + 0.5) / 100.0, sizes[sizepos])->ptr; } char * convert_size2(clen_t size1, clen_t size2, int usefloat) { char **sizes = _size_unit; float csize, factor = 1; int sizepos = 0; csize = (float)((size1 > size2) ? size1 : size2); while (csize / factor >= 999.495 && sizes[sizepos + 1]) { factor *= 1024.0; sizepos++; } return Sprintf(usefloat ? "%.3g/%.3g%s" : "%.0f/%.0f%s", floor(size1 / factor * 100.0 + 0.5) / 100.0, floor(size2 / factor * 100.0 + 0.5) / 100.0, sizes[sizepos])->ptr; } void showProgress(clen_t * linelen, clen_t * trbyte) { int i, j, rate, duration, eta, pos; static time_t last_time, start_time; time_t cur_time; Str messages; char *fmtrbyte, *fmrate; if (!fmInitialized) return; if (*linelen < 1024) return; if (current_content_length > 0) { double ratio; cur_time = time(0); if (*trbyte == 0) { move(LASTLINE, 0); clrtoeolx(); start_time = cur_time; } *trbyte += *linelen; *linelen = 0; if (cur_time == last_time) return; last_time = cur_time; move(LASTLINE, 0); ratio = 100.0 * (*trbyte) / current_content_length; fmtrbyte = convert_size2(*trbyte, current_content_length, 1); duration = cur_time - start_time; if (duration) { rate = *trbyte / duration; fmrate = convert_size(rate, 1); eta = rate ? (current_content_length - *trbyte) / rate : -1; messages = Sprintf("%11s %3.0f%% " "%7s/s " "eta %02d:%02d:%02d ", fmtrbyte, ratio, fmrate, eta / (60 * 60), (eta / 60) % 60, eta % 60); } else { messages = Sprintf("%11s %3.0f%% ", fmtrbyte, ratio); } addstr(messages->ptr); pos = 42; i = pos + (COLS - pos - 1) * (*trbyte) / current_content_length; move(LASTLINE, pos); standout(); addch(' '); for (j = pos + 1; j <= i; j++) addch('|'); standend(); /* no_clrtoeol(); */ refresh(); } else { cur_time = time(0); if (*trbyte == 0) { move(LASTLINE, 0); clrtoeolx(); start_time = cur_time; } *trbyte += *linelen; *linelen = 0; if (cur_time == last_time) return; last_time = cur_time; move(LASTLINE, 0); fmtrbyte = convert_size(*trbyte, 1); duration = cur_time - start_time; if (duration) { fmrate = convert_size(*trbyte / duration, 1); messages = Sprintf("%7s loaded %7s/s", fmtrbyte, fmrate); } else { messages = Sprintf("%7s loaded", fmtrbyte); } message(messages->ptr, 0, 0); refresh(); } } void init_henv(struct html_feed_environ *h_env, struct readbuffer *obuf, struct environment *envs, int nenv, TextLineList *buf, int limit, int indent) { envs[0].indent = indent; obuf->line = Strnew(); obuf->cprop = 0; obuf->pos = 0; obuf->prevchar = Strnew_size(8); set_space_to_prevchar(obuf->prevchar); obuf->flag = RB_IGNORE_P; obuf->flag_sp = 0; obuf->status = R_ST_NORMAL; obuf->table_level = -1; obuf->nobr_level = 0; bzero((void *)&obuf->anchor, sizeof(obuf->anchor)); obuf->img_alt = 0; obuf->input_alt.hseq = 0; obuf->input_alt.fid = -1; obuf->input_alt.in = 0; obuf->input_alt.type = NULL; obuf->input_alt.name = NULL; obuf->input_alt.value = NULL; obuf->in_bold = 0; obuf->in_italic = 0; obuf->in_under = 0; obuf->in_strike = 0; obuf->in_ins = 0; obuf->prev_ctype = PC_ASCII; obuf->tag_sp = 0; obuf->fontstat_sp = 0; obuf->top_margin = 0; obuf->bottom_margin = 0; obuf->bp.init_flag = 1; set_breakpoint(obuf, 0); h_env->buf = buf; h_env->f = NULL; h_env->obuf = obuf; h_env->tagbuf = Strnew(); h_env->limit = limit; h_env->maxlimit = 0; h_env->envs = envs; h_env->nenv = nenv; h_env->envc = 0; h_env->envc_real = 0; h_env->title = NULL; h_env->blank_lines = 0; } void completeHTMLstream(struct html_feed_environ *h_env, struct readbuffer *obuf) { close_anchor(h_env, obuf); if (obuf->img_alt) { push_tag(obuf, "</img_alt>", HTML_N_IMG_ALT); obuf->img_alt = NULL; } if (obuf->input_alt.in) { push_tag(obuf, "</input_alt>", HTML_N_INPUT_ALT); obuf->input_alt.hseq = 0; obuf->input_alt.fid = -1; obuf->input_alt.in = 0; obuf->input_alt.type = NULL; obuf->input_alt.name = NULL; obuf->input_alt.value = NULL; } if (obuf->in_bold) { push_tag(obuf, "</b>", HTML_N_B); obuf->in_bold = 0; } if (obuf->in_italic) { push_tag(obuf, "</i>", HTML_N_I); obuf->in_italic = 0; } if (obuf->in_under) { push_tag(obuf, "</u>", HTML_N_U); obuf->in_under = 0; } if (obuf->in_strike) { push_tag(obuf, "</s>", HTML_N_S); obuf->in_strike = 0; } if (obuf->in_ins) { push_tag(obuf, "</ins>", HTML_N_INS); obuf->in_ins = 0; } if (obuf->flag & RB_INTXTA) HTMLlineproc1("</textarea>", h_env); /* for unbalanced select tag */ if (obuf->flag & RB_INSELECT) HTMLlineproc1("</select>", h_env); if (obuf->flag & RB_TITLE) HTMLlineproc1("</title>", h_env); /* for unbalanced table tag */ if (obuf->table_level >= MAX_TABLE) obuf->table_level = MAX_TABLE - 1; while (obuf->table_level >= 0) { table_mode[obuf->table_level].pre_mode &= ~(TBLM_SCRIPT | TBLM_STYLE | TBLM_PLAIN); HTMLlineproc1("</table>", h_env); } } static void print_internal_information(struct html_feed_environ *henv) { int i; Str s; TextLineList *tl = newTextLineList(); s = Strnew_charp("<internal>"); pushTextLine(tl, newTextLine(s, 0)); if (henv->title) { s = Strnew_m_charp("<title_alt title=\"", html_quote(henv->title), "\">", NULL); pushTextLine(tl, newTextLine(s, 0)); } #if 0 if (form_max >= 0) { FormList *fp; for (i = 0; i <= form_max; i++) { fp = forms[i]; s = Sprintf("<form_int fid=\"%d\" action=\"%s\" method=\"%s\"", i, html_quote(fp->action->ptr), (fp->method == FORM_METHOD_POST) ? "post" : ((fp->method == FORM_METHOD_INTERNAL) ? "internal" : "get")); if (fp->target) Strcat(s, Sprintf(" target=\"%s\"", html_quote(fp->target))); if (fp->enctype == FORM_ENCTYPE_MULTIPART) Strcat_charp(s, " enctype=\"multipart/form-data\""); #ifdef USE_M17N if (fp->charset) Strcat(s, Sprintf(" accept-charset=\"%s\"", html_quote(fp->charset))); #endif Strcat_charp(s, ">"); pushTextLine(tl, newTextLine(s, 0)); } } #endif #ifdef MENU_SELECT if (n_select > 0) { FormSelectOptionItem *ip; for (i = 0; i < n_select; i++) { s = Sprintf("<select_int selectnumber=%d>", i); pushTextLine(tl, newTextLine(s, 0)); for (ip = select_option[i].first; ip; ip = ip->next) { s = Sprintf("<option_int value=\"%s\" label=\"%s\"%s>", html_quote(ip->value ? ip->value->ptr : ip->label->ptr), html_quote(ip->label->ptr), ip->checked ? " selected" : ""); pushTextLine(tl, newTextLine(s, 0)); } s = Strnew_charp("</select_int>"); pushTextLine(tl, newTextLine(s, 0)); } } #endif /* MENU_SELECT */ if (n_textarea > 0) { for (i = 0; i < n_textarea; i++) { s = Sprintf("<textarea_int textareanumber=%d>", i); pushTextLine(tl, newTextLine(s, 0)); s = Strnew_charp(html_quote(textarea_str[i]->ptr)); Strcat_charp(s, "</textarea_int>"); pushTextLine(tl, newTextLine(s, 0)); } } s = Strnew_charp("</internal>"); pushTextLine(tl, newTextLine(s, 0)); if (henv->buf) appendTextLineList(henv->buf, tl); else if (henv->f) { TextLineListItem *p; for (p = tl->first; p; p = p->next) fprintf(henv->f, "%s\n", Str_conv_to_halfdump(p->ptr->line)->ptr); } } void loadHTMLstream(URLFile *f, Buffer *newBuf, FILE * src, int internal) { struct environment envs[MAX_ENV_LEVEL]; clen_t linelen = 0; clen_t trbyte = 0; Str lineBuf2 = Strnew(); #ifdef USE_M17N wc_ces charset = WC_CES_US_ASCII; wc_ces volatile doc_charset = DocumentCharset; #endif struct html_feed_environ htmlenv1; struct readbuffer obuf; #ifdef USE_IMAGE int volatile image_flag; #endif MySignalHandler(*volatile prevtrap) (SIGNAL_ARG) = NULL; #ifdef USE_M17N if (fmInitialized && graph_ok()) { symbol_width = symbol_width0 = 1; } else { symbol_width0 = 0; get_symbol(DisplayCharset, &symbol_width0); symbol_width = WcOption.use_wide ? symbol_width0 : 1; } #else symbol_width = symbol_width0 = 1; #endif cur_title = NULL; n_textarea = 0; cur_textarea = NULL; max_textarea = MAX_TEXTAREA; textarea_str = New_N(Str, max_textarea); #ifdef MENU_SELECT n_select = 0; max_select = MAX_SELECT; select_option = New_N(FormSelectOption, max_select); #endif /* MENU_SELECT */ cur_select = NULL; form_sp = -1; form_max = -1; forms_size = 0; forms = NULL; cur_hseq = 1; #ifdef USE_IMAGE cur_iseq = 1; if (newBuf->image_flag) image_flag = newBuf->image_flag; else if (activeImage && displayImage && autoImage) image_flag = IMG_FLAG_AUTO; else image_flag = IMG_FLAG_SKIP; #endif if (w3m_halfload) { newBuf->buffername = "---"; #ifdef USE_M17N newBuf->document_charset = InnerCharset; #endif max_textarea = 0; #ifdef MENU_SELECT max_select = 0; #endif HTMLlineproc3(newBuf, f->stream); w3m_halfload = FALSE; return; } init_henv(&htmlenv1, &obuf, envs, MAX_ENV_LEVEL, NULL, newBuf->width, 0); if (w3m_halfdump) htmlenv1.f = stdout; else htmlenv1.buf = newTextLineList(); #if defined(USE_M17N) || defined(USE_IMAGE) cur_baseURL = baseURL(newBuf); #endif if (SETJMP(AbortLoading) != 0) { HTMLlineproc1("<br>Transfer Interrupted!<br>", &htmlenv1); goto phase2; } TRAP_ON; #ifdef USE_M17N if (newBuf != NULL) { if (newBuf->bufferprop & BP_FRAME) charset = InnerCharset; else if (newBuf->document_charset) charset = doc_charset = newBuf->document_charset; } if (content_charset && UseContentCharset) doc_charset = content_charset; else if (f->guess_type && !strcasecmp(f->guess_type, "application/xhtml+xml")) doc_charset = WC_CES_UTF_8; meta_charset = 0; #endif #if 0 do_blankline(&htmlenv1, &obuf, 0, 0, htmlenv1.limit); obuf.flag = RB_IGNORE_P; #endif if (IStype(f->stream) != IST_ENCODED) f->stream = newEncodedStream(f->stream, f->encoding); while ((lineBuf2 = StrmyUFgets(f))->length) { #ifdef USE_NNTP if (f->scheme == SCM_NEWS && lineBuf2->ptr[0] == '.') { Strshrinkfirst(lineBuf2, 1); if (lineBuf2->ptr[0] == '\n' || lineBuf2->ptr[0] == '\r' || lineBuf2->ptr[0] == '\0') { /* * iseos(f->stream) = TRUE; */ break; } } #endif /* USE_NNTP */ if (src) Strfputs(lineBuf2, src); linelen += lineBuf2->length; if (w3m_dump & DUMP_EXTRA) printf("W3m-in-progress: %s\n", convert_size2(linelen, current_content_length, TRUE)); if (w3m_dump & DUMP_SOURCE) continue; showProgress(&linelen, &trbyte); /* * if (frame_source) * continue; */ #ifdef USE_M17N if (meta_charset) { /* <META> */ if (content_charset == 0 && UseContentCharset) { doc_charset = meta_charset; charset = WC_CES_US_ASCII; } meta_charset = 0; } #endif lineBuf2 = convertLine(f, lineBuf2, HTML_MODE, &charset, doc_charset); #ifdef USE_M17N cur_document_charset = charset; #endif HTMLlineproc0(lineBuf2->ptr, &htmlenv1, internal); } if (obuf.status != R_ST_NORMAL) { HTMLlineproc0("\n", &htmlenv1, internal); } obuf.status = R_ST_NORMAL; completeHTMLstream(&htmlenv1, &obuf); flushline(&htmlenv1, &obuf, 0, 2, htmlenv1.limit); #if defined(USE_M17N) || defined(USE_IMAGE) cur_baseURL = NULL; #endif #ifdef USE_M17N cur_document_charset = 0; #endif if (htmlenv1.title) newBuf->buffername = htmlenv1.title; if (w3m_halfdump) { TRAP_OFF; print_internal_information(&htmlenv1); return; } if (w3m_backend) { TRAP_OFF; print_internal_information(&htmlenv1); backend_halfdump_buf = htmlenv1.buf; return; } phase2: newBuf->trbyte = trbyte + linelen; TRAP_OFF; #ifdef USE_M17N if (!(newBuf->bufferprop & BP_FRAME)) newBuf->document_charset = charset; #endif #ifdef USE_IMAGE newBuf->image_flag = image_flag; #endif HTMLlineproc2(newBuf, htmlenv1.buf); } /* * loadHTMLString: read string and make new buffer */ Buffer * loadHTMLString(Str page) { URLFile f; MySignalHandler(*volatile prevtrap) (SIGNAL_ARG) = NULL; Buffer *newBuf; init_stream(&f, SCM_LOCAL, newStrStream(page)); newBuf = newBuffer(INIT_BUFFER_WIDTH); if (SETJMP(AbortLoading) != 0) { TRAP_OFF; discardBuffer(newBuf); UFclose(&f); return NULL; } TRAP_ON; #ifdef USE_M17N newBuf->document_charset = InnerCharset; #endif loadHTMLstream(&f, newBuf, NULL, TRUE); #ifdef USE_M17N newBuf->document_charset = WC_CES_US_ASCII; #endif TRAP_OFF; UFclose(&f); newBuf->topLine = newBuf->firstLine; newBuf->lastLine = newBuf->currentLine; newBuf->currentLine = newBuf->firstLine; newBuf->type = "text/html"; newBuf->real_type = newBuf->type; if (n_textarea) formResetBuffer(newBuf, newBuf->formitem); return newBuf; } #ifdef USE_GOPHER /* * loadGopherDir: get gopher directory */ Str loadGopherDir(URLFile *uf, ParsedURL *pu, wc_ces * charset) { Str volatile tmp; Str lbuf, name, file, host, port; char *volatile p, *volatile q; MySignalHandler(*volatile prevtrap) (SIGNAL_ARG) = NULL; #ifdef USE_M17N wc_ces doc_charset = DocumentCharset; #endif tmp = parsedURL2Str(pu); p = html_quote(tmp->ptr); tmp = convertLine(NULL, Strnew_charp(file_unquote(tmp->ptr)), RAW_MODE, charset, doc_charset); q = html_quote(tmp->ptr); tmp = Strnew_m_charp("<html>\n<head>\n<base href=\"", p, "\">\n<title>", q, "</title>\n</head>\n<body>\n<h1>Index of ", q, "</h1>\n<table>\n", NULL); if (SETJMP(AbortLoading) != 0) goto gopher_end; TRAP_ON; while (1) { if (lbuf = StrUFgets(uf), lbuf->length == 0) break; if (lbuf->ptr[0] == '.' && (lbuf->ptr[1] == '\n' || lbuf->ptr[1] == '\r')) break; lbuf = convertLine(uf, lbuf, HTML_MODE, charset, doc_charset); p = lbuf->ptr; for (q = p; *q && *q != '\t'; q++) ; name = Strnew_charp_n(p, q - p); if (!*q) continue; p = q + 1; for (q = p; *q && *q != '\t'; q++) ; file = Strnew_charp_n(p, q - p); if (!*q) continue; p = q + 1; for (q = p; *q && *q != '\t'; q++) ; host = Strnew_charp_n(p, q - p); if (!*q) continue; p = q + 1; for (q = p; *q && *q != '\t' && *q != '\r' && *q != '\n'; q++) ; port = Strnew_charp_n(p, q - p); switch (name->ptr[0]) { case '0': p = "[text file]"; break; case '1': p = "[directory]"; break; case 'm': p = "[message]"; break; case 's': p = "[sound]"; break; case 'g': p = "[gif]"; break; case 'h': p = "[HTML]"; break; default: p = "[unsupported]"; break; } q = Strnew_m_charp("gopher://", host->ptr, ":", port->ptr, "/", file->ptr, NULL)->ptr; Strcat_m_charp(tmp, "<a href=\"", html_quote(url_encode(q, NULL, *charset)), "\">", p, html_quote(name->ptr + 1), "</a>\n", NULL); } gopher_end: TRAP_OFF; Strcat_charp(tmp, "</table>\n</body>\n</html>\n"); return tmp; } #endif /* USE_GOPHER */ /* * loadBuffer: read file and make new buffer */ Buffer * loadBuffer(URLFile *uf, Buffer *volatile newBuf) { FILE *volatile src = NULL; #ifdef USE_M17N wc_ces charset = WC_CES_US_ASCII; wc_ces volatile doc_charset = DocumentCharset; #endif Str lineBuf2; volatile char pre_lbuf = '\0'; int nlines; Str tmpf; clen_t linelen = 0, trbyte = 0; Lineprop *propBuffer = NULL; #ifdef USE_ANSI_COLOR Linecolor *colorBuffer = NULL; #endif MySignalHandler(*volatile prevtrap) (SIGNAL_ARG) = NULL; if (newBuf == NULL) newBuf = newBuffer(INIT_BUFFER_WIDTH); if (SETJMP(AbortLoading) != 0) { goto _end; } TRAP_ON; if (newBuf->sourcefile == NULL && (uf->scheme != SCM_LOCAL || newBuf->mailcap)) { tmpf = tmpfname(TMPF_SRC, NULL); src = fopen(tmpf->ptr, "w"); if (src) newBuf->sourcefile = tmpf->ptr; } #ifdef USE_M17N if (newBuf->document_charset) charset = doc_charset = newBuf->document_charset; if (content_charset && UseContentCharset) doc_charset = content_charset; #endif nlines = 0; if (IStype(uf->stream) != IST_ENCODED) uf->stream = newEncodedStream(uf->stream, uf->encoding); while ((lineBuf2 = StrmyISgets(uf->stream))->length) { #ifdef USE_NNTP if (uf->scheme == SCM_NEWS && lineBuf2->ptr[0] == '.') { Strshrinkfirst(lineBuf2, 1); if (lineBuf2->ptr[0] == '\n' || lineBuf2->ptr[0] == '\r' || lineBuf2->ptr[0] == '\0') { /* * iseos(uf->stream) = TRUE; */ break; } } #endif /* USE_NNTP */ if (src) Strfputs(lineBuf2, src); linelen += lineBuf2->length; if (w3m_dump & DUMP_EXTRA) printf("W3m-in-progress: %s\n", convert_size2(linelen, current_content_length, TRUE)); if (w3m_dump & DUMP_SOURCE) continue; showProgress(&linelen, &trbyte); if (frame_source) continue; lineBuf2 = convertLine(uf, lineBuf2, PAGER_MODE, &charset, doc_charset); if (squeezeBlankLine) { if (lineBuf2->ptr[0] == '\n' && pre_lbuf == '\n') { ++nlines; continue; } pre_lbuf = lineBuf2->ptr[0]; } ++nlines; Strchop(lineBuf2); lineBuf2 = checkType(lineBuf2, &propBuffer, NULL); addnewline(newBuf, lineBuf2->ptr, propBuffer, colorBuffer, lineBuf2->length, FOLD_BUFFER_WIDTH, nlines); } _end: TRAP_OFF; newBuf->topLine = newBuf->firstLine; newBuf->lastLine = newBuf->currentLine; newBuf->currentLine = newBuf->firstLine; newBuf->trbyte = trbyte + linelen; #ifdef USE_M17N newBuf->document_charset = charset; #endif if (src) fclose(src); return newBuf; } #ifdef USE_IMAGE Buffer * loadImageBuffer(URLFile *uf, Buffer *newBuf) { Image image; ImageCache *cache; Str tmp, tmpf; FILE *src = NULL; URLFile f; MySignalHandler(*volatile prevtrap) (SIGNAL_ARG) = NULL; struct stat st; const ParsedURL *pu = newBuf ? &newBuf->currentURL : NULL; loadImage(newBuf, IMG_FLAG_STOP); image.url = uf->url; image.ext = uf->ext; image.width = -1; image.height = -1; image.cache = NULL; cache = getImage(&image, (ParsedURL *)pu, IMG_FLAG_AUTO); if (!(pu && pu->is_nocache) && cache->loaded & IMG_FLAG_LOADED && !stat(cache->file, &st)) goto image_buffer; if (IStype(uf->stream) != IST_ENCODED) uf->stream = newEncodedStream(uf->stream, uf->encoding); TRAP_ON; if (save2tmp(*uf, cache->file) < 0) { TRAP_OFF; return NULL; } TRAP_OFF; cache->loaded = IMG_FLAG_LOADED; cache->index = 0; image_buffer: if (newBuf == NULL) newBuf = newBuffer(INIT_BUFFER_WIDTH); cache->loaded |= IMG_FLAG_DONT_REMOVE; if (newBuf->sourcefile == NULL && uf->scheme != SCM_LOCAL) newBuf->sourcefile = cache->file; tmp = Sprintf("<img src=\"%s\"><br><br>", html_quote(image.url)); tmpf = tmpfname(TMPF_SRC, ".html"); src = fopen(tmpf->ptr, "w"); newBuf->mailcap_source = tmpf->ptr; init_stream(&f, SCM_LOCAL, newStrStream(tmp)); loadHTMLstream(&f, newBuf, src, TRUE); UFclose(&f); if (src) fclose(src); newBuf->topLine = newBuf->firstLine; newBuf->lastLine = newBuf->currentLine; newBuf->currentLine = newBuf->firstLine; newBuf->image_flag = IMG_FLAG_AUTO; return newBuf; } #endif static Str conv_symbol(Line *l) { Str tmp = NULL; char *p = l->lineBuf, *ep = p + l->len; Lineprop *pr = l->propBuf; #ifdef USE_M17N int w; char **symbol = NULL; #else char **symbol = get_symbol(); #endif for (; p < ep; p++, pr++) { if (*pr & PC_SYMBOL) { #ifdef USE_M17N char c = ((char)wtf_get_code((wc_uchar *) p) & 0x7f) - SYMBOL_BASE; int len = get_mclen(p); #else char c = *p - SYMBOL_BASE; #endif if (tmp == NULL) { tmp = Strnew_size(l->len); Strcopy_charp_n(tmp, l->lineBuf, p - l->lineBuf); #ifdef USE_M17N w = (*pr & PC_KANJI) ? 2 : 1; symbol = get_symbol(DisplayCharset, &w); #endif } Strcat_charp(tmp, symbol[(int)c]); #ifdef USE_M17N p += len - 1; pr += len - 1; #endif } else if (tmp != NULL) Strcat_char(tmp, *p); } if (tmp) return tmp; else return Strnew_charp_n(l->lineBuf, l->len); } /* * saveBuffer: write buffer to file */ static void _saveBuffer(Buffer *buf, Line *l, FILE * f, int cont) { Str tmp; int is_html = FALSE; #ifdef USE_M17N int set_charset = !DisplayCharset; wc_ces charset = DisplayCharset ? DisplayCharset : WC_CES_US_ASCII; #endif is_html = is_html_type(buf->type); pager_next: for (; l != NULL; l = l->next) { if (is_html) tmp = conv_symbol(l); else tmp = Strnew_charp_n(l->lineBuf, l->len); tmp = wc_Str_conv(tmp, InnerCharset, charset); Strfputs(tmp, f); if (Strlastchar(tmp) != '\n' && !(cont && l->next && l->next->bpos)) putc('\n', f); } if (buf->pagerSource && !(buf->bufferprop & BP_CLOSE)) { l = getNextPage(buf, PagerMax); #ifdef USE_M17N if (set_charset) charset = buf->document_charset; #endif goto pager_next; } } void saveBuffer(Buffer *buf, FILE * f, int cont) { _saveBuffer(buf, buf->firstLine, f, cont); } void saveBufferBody(Buffer *buf, FILE * f, int cont) { Line *l = buf->firstLine; while (l != NULL && l->real_linenumber == 0) l = l->next; _saveBuffer(buf, l, f, cont); } static Buffer * loadcmdout(char *cmd, Buffer *(*loadproc) (URLFile *, Buffer *), Buffer *defaultbuf) { FILE *f, *popen(const char *, const char *); Buffer *buf; URLFile uf; if (cmd == NULL || *cmd == '\0') return NULL; f = popen(cmd, "r"); if (f == NULL) return NULL; init_stream(&uf, SCM_UNKNOWN, newFileStream(f, (void (*)())pclose)); buf = loadproc(&uf, defaultbuf); UFclose(&uf); return buf; } /* * getshell: execute shell command and get the result into a buffer */ Buffer * getshell(char *cmd) { Buffer *buf; buf = loadcmdout(cmd, loadBuffer, NULL); if (buf == NULL) return NULL; buf->filename = cmd; buf->buffername = Sprintf("%s %s", SHELLBUFFERNAME, conv_from_system(cmd))->ptr; return buf; } /* * getpipe: execute shell command and connect pipe to the buffer */ Buffer * getpipe(char *cmd) { FILE *f, *popen(const char *, const char *); Buffer *buf; if (cmd == NULL || *cmd == '\0') return NULL; f = popen(cmd, "r"); if (f == NULL) return NULL; buf = newBuffer(INIT_BUFFER_WIDTH); buf->pagerSource = newFileStream(f, (void (*)())pclose); buf->filename = cmd; buf->buffername = Sprintf("%s %s", PIPEBUFFERNAME, conv_from_system(cmd))->ptr; buf->bufferprop |= BP_PIPE; #ifdef USE_M17N buf->document_charset = WC_CES_US_ASCII; #endif return buf; } /* * Open pager buffer */ Buffer * openPagerBuffer(InputStream stream, Buffer *buf) { if (buf == NULL) buf = newBuffer(INIT_BUFFER_WIDTH); buf->pagerSource = stream; buf->buffername = getenv("MAN_PN"); if (buf->buffername == NULL) buf->buffername = PIPEBUFFERNAME; else buf->buffername = conv_from_system(buf->buffername); buf->bufferprop |= BP_PIPE; #ifdef USE_M17N if (content_charset && UseContentCharset) buf->document_charset = content_charset; else buf->document_charset = WC_CES_US_ASCII; #endif buf->currentLine = buf->firstLine; return buf; } Buffer * openGeneralPagerBuffer(InputStream stream) { Buffer *buf; char *t = "text/plain"; Buffer *t_buf = NULL; URLFile uf; init_stream(&uf, SCM_UNKNOWN, stream); #ifdef USE_M17N content_charset = 0; #endif t_buf = newBuffer(INIT_BUFFER_WIDTH); copyParsedURL(&t_buf->currentURL, NULL); t_buf->currentURL.scheme = SCM_LOCAL; t_buf->currentURL.file = "-"; if (SearchHeader) { readHeader(&uf, t_buf, TRUE, NULL); t = checkContentType(t_buf); if (t == NULL) t = "text/plain"; if (t_buf) { t_buf->topLine = t_buf->firstLine; t_buf->currentLine = t_buf->lastLine; } SearchHeader = FALSE; } else if (DefaultType) { t = DefaultType; DefaultType = NULL; } if (is_html_type(t)) { buf = loadHTMLBuffer(&uf, t_buf); buf->type = "text/html"; } else if (is_plain_text_type(t)) { if (IStype(stream) != IST_ENCODED) stream = newEncodedStream(stream, uf.encoding); buf = openPagerBuffer(stream, t_buf); buf->type = "text/plain"; } #ifdef USE_IMAGE else if (activeImage && displayImage && !useExtImageViewer && !(w3m_dump & ~DUMP_FRAME) && !strncasecmp(t, "image/", 6)) { buf = loadImageBuffer(&uf, t_buf); buf->type = "text/html"; } #endif else { if (searchExtViewer(t)) { buf = doExternal(uf, t, t_buf); UFclose(&uf); if (buf == NULL || buf == NO_BUFFER) return buf; } else { /* unknown type is regarded as text/plain */ if (IStype(stream) != IST_ENCODED) stream = newEncodedStream(stream, uf.encoding); buf = openPagerBuffer(stream, t_buf); buf->type = "text/plain"; } } buf->real_type = t; return buf; } Line * getNextPage(Buffer *buf, int plen) { Line *volatile top = buf->topLine, *volatile last = buf->lastLine, *volatile cur = buf->currentLine; int i; int volatile nlines = 0; clen_t linelen = 0, trbyte = buf->trbyte; Str lineBuf2; char volatile pre_lbuf = '\0'; URLFile uf; #ifdef USE_M17N wc_ces charset; wc_ces volatile doc_charset = DocumentCharset; wc_uint8 old_auto_detect = WcOption.auto_detect; #endif int volatile squeeze_flag = FALSE; Lineprop *propBuffer = NULL; #ifdef USE_ANSI_COLOR Linecolor *colorBuffer = NULL; #endif MySignalHandler(*volatile prevtrap) (SIGNAL_ARG) = NULL; if (buf->pagerSource == NULL) return NULL; if (last != NULL) { nlines = last->real_linenumber; pre_lbuf = *(last->lineBuf); if (pre_lbuf == '\0') pre_lbuf = '\n'; buf->currentLine = last; } #ifdef USE_M17N charset = buf->document_charset; if (buf->document_charset != WC_CES_US_ASCII) doc_charset = buf->document_charset; else if (UseContentCharset) { content_charset = 0; checkContentType(buf); if (content_charset) doc_charset = content_charset; } WcOption.auto_detect = buf->auto_detect; #endif if (SETJMP(AbortLoading) != 0) { goto pager_end; } TRAP_ON; init_stream(&uf, SCM_UNKNOWN, NULL); for (i = 0; i < plen; i++) { lineBuf2 = StrmyISgets(buf->pagerSource); if (lineBuf2->length == 0) { /* Assume that `cmd == buf->filename' */ if (buf->filename) buf->buffername = Sprintf("%s %s", CPIPEBUFFERNAME, conv_from_system(buf->filename))-> ptr; else if (getenv("MAN_PN") == NULL) buf->buffername = CPIPEBUFFERNAME; buf->bufferprop |= BP_CLOSE; break; } linelen += lineBuf2->length; showProgress(&linelen, &trbyte); lineBuf2 = convertLine(&uf, lineBuf2, PAGER_MODE, &charset, doc_charset); if (squeezeBlankLine) { squeeze_flag = FALSE; if (lineBuf2->ptr[0] == '\n' && pre_lbuf == '\n') { ++nlines; --i; squeeze_flag = TRUE; continue; } pre_lbuf = lineBuf2->ptr[0]; } ++nlines; Strchop(lineBuf2); lineBuf2 = checkType(lineBuf2, &propBuffer, &colorBuffer); addnewline(buf, lineBuf2->ptr, propBuffer, colorBuffer, lineBuf2->length, FOLD_BUFFER_WIDTH, nlines); if (!top) { top = buf->firstLine; cur = top; } if (buf->lastLine->real_linenumber - buf->firstLine->real_linenumber >= PagerMax) { Line *l = buf->firstLine; do { if (top == l) top = l->next; if (cur == l) cur = l->next; if (last == l) last = NULL; l = l->next; } while (l && l->bpos); buf->firstLine = l; buf->firstLine->prev = NULL; } } pager_end: TRAP_OFF; buf->trbyte = trbyte + linelen; #ifdef USE_M17N buf->document_charset = charset; WcOption.auto_detect = old_auto_detect; #endif buf->topLine = top; buf->currentLine = cur; if (!last) last = buf->firstLine; else if (last && (last->next || !squeeze_flag)) last = last->next; return last; } int save2tmp(URLFile uf, char *tmpf) { FILE *ff; int check; clen_t linelen = 0, trbyte = 0; MySignalHandler(*volatile prevtrap) (SIGNAL_ARG) = NULL; static JMP_BUF env_bak; volatile int retval = 0; char *volatile buf = NULL; ff = fopen(tmpf, "wb"); if (ff == NULL) { /* fclose(f); */ return -1; } bcopy(AbortLoading, env_bak, sizeof(JMP_BUF)); if (SETJMP(AbortLoading) != 0) { goto _end; } TRAP_ON; check = 0; #ifdef USE_NNTP if (uf.scheme == SCM_NEWS) { char c; while (c = UFgetc(&uf), !iseos(uf.stream)) { if (c == '\n') { if (check == 0) check++; else if (check == 3) break; } else if (c == '.' && check == 1) check++; else if (c == '\r' && check == 2) check++; else check = 0; putc(c, ff); linelen += sizeof(c); showProgress(&linelen, &trbyte); } } else #endif /* USE_NNTP */ { int count; buf = NewWithoutGC_N(char, SAVE_BUF_SIZE); while ((count = ISread_n(uf.stream, buf, SAVE_BUF_SIZE)) > 0) { if (fwrite(buf, 1, count, ff) != count) { retval = -2; goto _end; } linelen += count; showProgress(&linelen, &trbyte); } } _end: bcopy(env_bak, AbortLoading, sizeof(JMP_BUF)); TRAP_OFF; xfree(buf); fclose(ff); current_content_length = 0; return retval; } Buffer * doExternal(URLFile uf, char *type, Buffer *defaultbuf) { Str tmpf, command; struct mailcap *mcap; int mc_stat; Buffer *buf = NULL; char *header, *src = NULL, *ext = uf.ext; if (!(mcap = searchExtViewer(type))) return NULL; if (mcap->nametemplate) { tmpf = unquote_mailcap(mcap->nametemplate, NULL, "", NULL, NULL); if (tmpf->ptr[0] == '.') ext = tmpf->ptr; } tmpf = tmpfname(TMPF_DFL, (ext && *ext) ? ext : NULL); if (IStype(uf.stream) != IST_ENCODED) uf.stream = newEncodedStream(uf.stream, uf.encoding); header = checkHeader(defaultbuf, "Content-Type:"); if (header) header = conv_to_system(header); command = unquote_mailcap(mcap->viewer, type, tmpf->ptr, header, &mc_stat); #ifndef __EMX__ if (!(mc_stat & MCSTAT_REPNAME)) { Str tmp = Sprintf("(%s) < %s", command->ptr, shell_quote(tmpf->ptr)); command = tmp; } #endif #ifdef HAVE_SETPGRP if (!(mcap->flags & (MAILCAP_HTMLOUTPUT | MAILCAP_COPIOUSOUTPUT)) && !(mcap->flags & MAILCAP_NEEDSTERMINAL) && BackgroundExtViewer) { flush_tty(); if (!fork()) { setup_child(FALSE, 0, UFfileno(&uf)); if (save2tmp(uf, tmpf->ptr) < 0) exit(1); UFclose(&uf); myExec(command->ptr); } return NO_BUFFER; } else #endif { if (save2tmp(uf, tmpf->ptr) < 0) { return NULL; } } if (mcap->flags & (MAILCAP_HTMLOUTPUT | MAILCAP_COPIOUSOUTPUT)) { if (defaultbuf == NULL) defaultbuf = newBuffer(INIT_BUFFER_WIDTH); if (defaultbuf->sourcefile) src = defaultbuf->sourcefile; else src = tmpf->ptr; defaultbuf->sourcefile = NULL; defaultbuf->mailcap = mcap; } if (mcap->flags & MAILCAP_HTMLOUTPUT) { buf = loadcmdout(command->ptr, loadHTMLBuffer, defaultbuf); if (buf && buf != NO_BUFFER) { buf->type = "text/html"; buf->mailcap_source = buf->sourcefile; buf->sourcefile = src; } } else if (mcap->flags & MAILCAP_COPIOUSOUTPUT) { buf = loadcmdout(command->ptr, loadBuffer, defaultbuf); if (buf && buf != NO_BUFFER) { buf->type = "text/plain"; buf->mailcap_source = buf->sourcefile; buf->sourcefile = src; } } else { if (mcap->flags & MAILCAP_NEEDSTERMINAL || !BackgroundExtViewer) { fmTerm(); mySystem(command->ptr, 0); fmInit(); if (CurrentTab && Currentbuf) displayBuffer(Currentbuf, B_FORCE_REDRAW); } else { mySystem(command->ptr, 1); } buf = NO_BUFFER; } if (buf && buf != NO_BUFFER) { if ((buf->buffername == NULL || buf->buffername[0] == '\0') && buf->filename) buf->buffername = conv_from_system(lastFileName(buf->filename)); buf->edit = mcap->edit; buf->mailcap = mcap; } return buf; } static int _MoveFile(char *path1, char *path2) { InputStream f1; FILE *f2; int is_pipe; clen_t linelen = 0, trbyte = 0; char *buf = NULL; int count; f1 = openIS(path1); if (f1 == NULL) return -1; if (*path2 == '|' && PermitSaveToPipe) { is_pipe = TRUE; f2 = popen(path2 + 1, "w"); } else { is_pipe = FALSE; f2 = fopen(path2, "wb"); } if (f2 == NULL) { ISclose(f1); return -1; } current_content_length = 0; buf = NewWithoutGC_N(char, SAVE_BUF_SIZE); while ((count = ISread_n(f1, buf, SAVE_BUF_SIZE)) > 0) { fwrite(buf, 1, count, f2); linelen += count; showProgress(&linelen, &trbyte); } xfree(buf); ISclose(f1); if (is_pipe) pclose(f2); else fclose(f2); return 0; } int _doFileCopy(char *tmpf, char *defstr, int download) { #ifndef __MINGW32_VERSION Str msg; Str filen; char *p, *q = NULL; pid_t pid; char *lock; #if !(defined(HAVE_SYMLINK) && defined(HAVE_LSTAT)) FILE *f; #endif struct stat st; clen_t size = 0; int is_pipe = FALSE; if (fmInitialized) { p = searchKeyData(); if (p == NULL || *p == '\0') { /* FIXME: gettextize? */ q = inputLineHist("(Download)Save file to: ", defstr, IN_COMMAND, SaveHist); if (q == NULL || *q == '\0') return FALSE; p = conv_to_system(q); } if (*p == '|' && PermitSaveToPipe) is_pipe = TRUE; else { if (q) { p = unescape_spaces(Strnew_charp(q))->ptr; p = conv_to_system(p); } p = expandPath(p); if (checkOverWrite(p) < 0) return -1; } if (checkCopyFile(tmpf, p) < 0) { /* FIXME: gettextize? */ msg = Sprintf("Can't copy. %s and %s are identical.", conv_from_system(tmpf), conv_from_system(p)); disp_err_message(msg->ptr, FALSE); return -1; } if (!download) { if (_MoveFile(tmpf, p) < 0) { /* FIXME: gettextize? */ msg = Sprintf("Can't save to %s", conv_from_system(p)); disp_err_message(msg->ptr, FALSE); } return -1; } lock = tmpfname(TMPF_DFL, ".lock")->ptr; #if defined(HAVE_SYMLINK) && defined(HAVE_LSTAT) symlink(p, lock); #else f = fopen(lock, "w"); if (f) fclose(f); #endif flush_tty(); pid = fork(); if (!pid) { setup_child(FALSE, 0, -1); if (!_MoveFile(tmpf, p) && PreserveTimestamp && !is_pipe && !stat(tmpf, &st)) setModtime(p, st.st_mtime); unlink(lock); exit(0); } if (!stat(tmpf, &st)) size = st.st_size; addDownloadList(pid, conv_from_system(tmpf), p, lock, size); } else { q = searchKeyData(); if (q == NULL || *q == '\0') { /* FIXME: gettextize? */ printf("(Download)Save file to: "); fflush(stdout); filen = Strfgets(stdin); if (filen->length == 0) return -1; q = filen->ptr; } for (p = q + strlen(q) - 1; IS_SPACE(*p); p--) ; *(p + 1) = '\0'; if (*q == '\0') return -1; p = q; if (*p == '|' && PermitSaveToPipe) is_pipe = TRUE; else { p = expandPath(p); if (checkOverWrite(p) < 0) return -1; } if (checkCopyFile(tmpf, p) < 0) { /* FIXME: gettextize? */ printf("Can't copy. %s and %s are identical.", tmpf, p); return -1; } if (_MoveFile(tmpf, p) < 0) { /* FIXME: gettextize? */ printf("Can't save to %s\n", p); return -1; } if (PreserveTimestamp && !is_pipe && !stat(tmpf, &st)) setModtime(p, st.st_mtime); } #endif /* __MINGW32_VERSION */ return 0; } int doFileMove(char *tmpf, char *defstr) { int ret = doFileCopy(tmpf, defstr); unlink(tmpf); return ret; } int doFileSave(URLFile uf, char *defstr) { #ifndef __MINGW32_VERSION Str msg; Str filen; char *p, *q; pid_t pid; char *lock; char *tmpf = NULL; #if !(defined(HAVE_SYMLINK) && defined(HAVE_LSTAT)) FILE *f; #endif if (fmInitialized) { p = searchKeyData(); if (p == NULL || *p == '\0') { /* FIXME: gettextize? */ p = inputLineHist("(Download)Save file to: ", defstr, IN_FILENAME, SaveHist); if (p == NULL || *p == '\0') return -1; p = conv_to_system(p); } if (checkOverWrite(p) < 0) return -1; if (checkSaveFile(uf.stream, p) < 0) { /* FIXME: gettextize? */ msg = Sprintf("Can't save. Load file and %s are identical.", conv_from_system(p)); disp_err_message(msg->ptr, FALSE); return -1; } /* * if (save2tmp(uf, p) < 0) { * msg = Sprintf("Can't save to %s", conv_from_system(p)); * disp_err_message(msg->ptr, FALSE); * } */ lock = tmpfname(TMPF_DFL, ".lock")->ptr; #if defined(HAVE_SYMLINK) && defined(HAVE_LSTAT) symlink(p, lock); #else f = fopen(lock, "w"); if (f) fclose(f); #endif flush_tty(); pid = fork(); if (!pid) { int err; if ((uf.content_encoding != CMP_NOCOMPRESS) && AutoUncompress) { uncompress_stream(&uf, &tmpf); if (tmpf) unlink(tmpf); } setup_child(FALSE, 0, UFfileno(&uf)); err = save2tmp(uf, p); if (err == 0 && PreserveTimestamp && uf.modtime != -1) setModtime(p, uf.modtime); UFclose(&uf); unlink(lock); if (err != 0) exit(-err); exit(0); } addDownloadList(pid, uf.url, p, lock, current_content_length); } else { q = searchKeyData(); if (q == NULL || *q == '\0') { /* FIXME: gettextize? */ printf("(Download)Save file to: "); fflush(stdout); filen = Strfgets(stdin); if (filen->length == 0) return -1; q = filen->ptr; } for (p = q + strlen(q) - 1; IS_SPACE(*p); p--) ; *(p + 1) = '\0'; if (*q == '\0') return -1; p = expandPath(q); if (checkOverWrite(p) < 0) return -1; if (checkSaveFile(uf.stream, p) < 0) { /* FIXME: gettextize? */ printf("Can't save. Load file and %s are identical.", p); return -1; } if (uf.content_encoding != CMP_NOCOMPRESS && AutoUncompress) { uncompress_stream(&uf, &tmpf); if (tmpf) unlink(tmpf); } if (save2tmp(uf, p) < 0) { /* FIXME: gettextize? */ printf("Can't save to %s\n", p); return -1; } if (PreserveTimestamp && uf.modtime != -1) setModtime(p, uf.modtime); } #endif /* __MINGW32_VERSION */ return 0; } int checkCopyFile(char *path1, char *path2) { struct stat st1, st2; if (*path2 == '|' && PermitSaveToPipe) return 0; if ((stat(path1, &st1) == 0) && (stat(path2, &st2) == 0)) if (st1.st_ino == st2.st_ino) return -1; return 0; } int checkSaveFile(InputStream stream, char *path2) { struct stat st1, st2; int des = ISfileno(stream); if (des < 0) return 0; if (*path2 == '|' && PermitSaveToPipe) return 0; if ((fstat(des, &st1) == 0) && (stat(path2, &st2) == 0)) if (st1.st_ino == st2.st_ino) return -1; return 0; } int checkOverWrite(char *path) { struct stat st; char *ans; if (stat(path, &st) < 0) return 0; /* FIXME: gettextize? */ ans = inputAnswer("File exists. Overwrite? (y/n)"); if (ans && TOLOWER(*ans) == 'y') return 0; else return -1; } char * inputAnswer(char *prompt) { char *ans; if (QuietMessage) return "n"; if (fmInitialized) { term_raw(); ans = inputChar(prompt); } else { printf("%s", prompt); fflush(stdout); ans = Strfgets(stdin)->ptr; } return ans; } static void uncompress_stream(URLFile *uf, char **src) { #ifndef __MINGW32_VERSION pid_t pid1; FILE *f1; char *expand_cmd = GUNZIP_CMDNAME; char *expand_name = GUNZIP_NAME; char *tmpf = NULL; char *ext = NULL; struct compression_decoder *d; if (IStype(uf->stream) != IST_ENCODED) { uf->stream = newEncodedStream(uf->stream, uf->encoding); uf->encoding = ENC_7BIT; } for (d = compression_decoders; d->type != CMP_NOCOMPRESS; d++) { if (uf->compression == d->type) { if (d->auxbin_p) expand_cmd = auxbinFile(d->cmd); else expand_cmd = d->cmd; expand_name = d->name; ext = d->ext; break; } } uf->compression = CMP_NOCOMPRESS; if (uf->scheme != SCM_LOCAL #ifdef USE_IMAGE && !image_source #endif ) { tmpf = tmpfname(TMPF_DFL, ext)->ptr; } /* child1 -- stdout|f1=uf -> parent */ pid1 = open_pipe_rw(&f1, NULL); if (pid1 < 0) { UFclose(uf); return; } if (pid1 == 0) { /* child */ pid_t pid2; FILE *f2 = stdin; /* uf -> child2 -- stdout|stdin -> child1 */ pid2 = open_pipe_rw(&f2, NULL); if (pid2 < 0) { UFclose(uf); exit(1); } if (pid2 == 0) { /* child2 */ char *buf = NewWithoutGC_N(char, SAVE_BUF_SIZE); int count; FILE *f = NULL; setup_child(TRUE, 2, UFfileno(uf)); if (tmpf) f = fopen(tmpf, "wb"); while ((count = ISread_n(uf->stream, buf, SAVE_BUF_SIZE)) > 0) { if (fwrite(buf, 1, count, stdout) != count) break; if (f && fwrite(buf, 1, count, f) != count) break; } UFclose(uf); if (f) fclose(f); xfree(buf); exit(0); } /* child1 */ dup2(1, 2); /* stderr>&stdout */ setup_child(TRUE, -1, -1); execlp(expand_cmd, expand_name, NULL); exit(1); } if (tmpf) { if (src) *src = tmpf; else uf->scheme = SCM_LOCAL; } UFhalfclose(uf); uf->stream = newFileStream(f1, (void (*)())fclose); #endif /* __MINGW32_VERSION */ } static FILE * lessopen_stream(char *path) { char *lessopen; FILE *fp; lessopen = getenv("LESSOPEN"); if (lessopen == NULL) { return NULL; } if (lessopen[0] == '\0') { return NULL; } if (lessopen[0] == '|') { /* pipe mode */ Str tmpf; int c; ++lessopen; tmpf = Sprintf(lessopen, shell_quote(path)); fp = popen(tmpf->ptr, "r"); if (fp == NULL) { return NULL; } c = getc(fp); if (c == EOF) { pclose(fp); return NULL; } ungetc(c, fp); } else { /* filename mode */ /* not supported m(__)m */ fp = NULL; } return fp; } #if 0 void reloadBuffer(Buffer *buf) { URLFile uf; if (buf->sourcefile == NULL || buf->pagerSource != NULL) return; init_stream(&uf, SCM_UNKNOWN, NULL); examineFile(buf->mailcap_source ? buf->mailcap_source : buf->sourcefile, &uf); if (uf.stream == NULL) return; is_redisplay = TRUE; buf->allLine = 0; buf->href = NULL; buf->name = NULL; buf->img = NULL; buf->formitem = NULL; buf->linklist = NULL; buf->maplist = NULL; if (buf->hmarklist) buf->hmarklist->nmark = 0; if (buf->imarklist) buf->imarklist->nmark = 0; if (is_html_type(buf->type)) loadHTMLBuffer(&uf, buf); else loadBuffer(&uf, buf); UFclose(&uf); is_redisplay = FALSE; } #endif static char * guess_filename(char *file) { char *p = NULL, *s; if (file != NULL) p = mybasename(file); if (p == NULL || *p == '\0') return DEF_SAVE_FILE; s = p; if (*p == '#') p++; while (*p != '\0') { if ((*p == '#' && *(p + 1) != '\0') || *p == '?') { *p = '\0'; break; } p++; } return s; } char * guess_save_name(Buffer *buf, char *path) { if (buf && buf->document_header) { Str name = NULL; char *p, *q; if ((p = checkHeader(buf, "Content-Disposition:")) != NULL && (q = strcasestr(p, "filename")) != NULL && (q == p || IS_SPACE(*(q - 1)) || *(q - 1) == ';') && matchattr(q, "filename", 8, &name)) path = name->ptr; else if ((p = checkHeader(buf, "Content-Type:")) != NULL && (q = strcasestr(p, "name")) != NULL && (q == p || IS_SPACE(*(q - 1)) || *(q - 1) == ';') && matchattr(q, "name", 4, &name)) path = name->ptr; } return guess_filename(path); } /* Local Variables: */ /* c-basic-offset: 4 */ /* tab-width: 8 */ /* End: */
./CrossVul/dataset_final_sorted/CWE-20/c/good_5420_0
crossvul-cpp_data_bad_4790_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % M M AAA TTTTT L AAA BBBB % % MM MM A A T L A A B B % % M M M AAAAA T L AAAAA BBBB % % M M A A T L A A B B % % M M A A T LLLLL A A BBBB % % % % % % Read MATLAB Image Format % % % % Software Design % % Jaroslav Fojtik % % 2001-2008 % % % % % % Permission is hereby granted, free of charge, to any person obtaining a % % copy of this software and associated documentation files ("ImageMagick"), % % to deal in ImageMagick without restriction, including without limitation % % the rights to use, copy, modify, merge, publish, distribute, sublicense, % % and/or sell copies of ImageMagick, and to permit persons to whom the % % ImageMagick is furnished to do so, subject to the following conditions: % % % % The above copyright notice and this permission notice shall be included in % % all copies or substantial portions of ImageMagick. % % % % The software is provided "as is", without warranty of any kind, express or % % implied, including but not limited to the warranties of merchantability, % % fitness for a particular purpose and noninfringement. In no event shall % % ImageMagick Studio be liable for any claim, damages or other liability, % % whether in an action of contract, tort or otherwise, arising from, out of % % or in connection with ImageMagick or the use or other dealings in % % ImageMagick. % % % % Except as contained in this notice, the name of the ImageMagick Studio % % shall not be used in advertising or otherwise to promote the sale, use or % % other dealings in ImageMagick without prior written authorization from the % % ImageMagick Studio. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* 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-private.h" #include "magick/colormap.h" #include "magick/colorspace-private.h" #include "magick/distort.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/option.h" #include "magick/pixel.h" #include "magick/pixel-accessor.h" #include "magick/quantum-private.h" #include "magick/resource_.h" #include "magick/static.h" #include "magick/string_.h" #include "magick/module.h" #include "magick/transform.h" #include "magick/utility-private.h" #if defined(MAGICKCORE_ZLIB_DELEGATE) #include "zlib.h" #endif /* Forward declaration. */ static MagickBooleanType WriteMATImage(const ImageInfo *,Image *); /* Auto coloring method, sorry this creates some artefact inside data MinReal+j*MaxComplex = red MaxReal+j*MaxComplex = black MinReal+j*0 = white MaxReal+j*0 = black MinReal+j*MinComplex = blue MaxReal+j*MinComplex = black */ typedef struct { char identific[124]; unsigned short Version; char EndianIndicator[2]; unsigned long DataType; unsigned long ObjectSize; unsigned long unknown1; unsigned long unknown2; unsigned short unknown5; unsigned char StructureFlag; unsigned char StructureClass; unsigned long unknown3; unsigned long unknown4; unsigned long DimFlag; unsigned long SizeX; unsigned long SizeY; unsigned short Flag1; unsigned short NameFlag; } MATHeader; static const char *MonthsTab[12]={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"}; static const char *DayOfWTab[7]={"Sun","Mon","Tue","Wed","Thu","Fri","Sat"}; static const char *OsDesc= #if defined(MAGICKCORE_WINDOWS_SUPPORT) "PCWIN"; #else #ifdef __APPLE__ "MAC"; #else "LNX86"; #endif #endif typedef enum { miINT8 = 1, /* 8 bit signed */ miUINT8, /* 8 bit unsigned */ miINT16, /* 16 bit signed */ miUINT16, /* 16 bit unsigned */ miINT32, /* 32 bit signed */ miUINT32, /* 32 bit unsigned */ miSINGLE, /* IEEE 754 single precision float */ miRESERVE1, miDOUBLE, /* IEEE 754 double precision float */ miRESERVE2, miRESERVE3, miINT64, /* 64 bit signed */ miUINT64, /* 64 bit unsigned */ miMATRIX, /* MATLAB array */ miCOMPRESSED, /* Compressed Data */ miUTF8, /* Unicode UTF-8 Encoded Character Data */ miUTF16, /* Unicode UTF-16 Encoded Character Data */ miUTF32 /* Unicode UTF-32 Encoded Character Data */ } mat5_data_type; typedef enum { mxCELL_CLASS=1, /* cell array */ mxSTRUCT_CLASS, /* structure */ mxOBJECT_CLASS, /* object */ mxCHAR_CLASS, /* character array */ mxSPARSE_CLASS, /* sparse array */ mxDOUBLE_CLASS, /* double precision array */ mxSINGLE_CLASS, /* single precision floating point */ mxINT8_CLASS, /* 8 bit signed integer */ mxUINT8_CLASS, /* 8 bit unsigned integer */ mxINT16_CLASS, /* 16 bit signed integer */ mxUINT16_CLASS, /* 16 bit unsigned integer */ mxINT32_CLASS, /* 32 bit signed integer */ mxUINT32_CLASS, /* 32 bit unsigned integer */ mxINT64_CLASS, /* 64 bit signed integer */ mxUINT64_CLASS, /* 64 bit unsigned integer */ mxFUNCTION_CLASS /* Function handle */ } arrayclasstype; #define FLAG_COMPLEX 0x8 #define FLAG_GLOBAL 0x4 #define FLAG_LOGICAL 0x2 static const QuantumType z2qtype[4] = {GrayQuantum, BlueQuantum, GreenQuantum, RedQuantum}; static void InsertComplexDoubleRow(double *p, int y, Image * image, double MinVal, double MaxVal) { ExceptionInfo *exception; double f; int x; register PixelPacket *q; if (MinVal == 0) MinVal = -1; if (MaxVal == 0) MaxVal = 1; exception=(&image->exception); q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) return; for (x = 0; x < (ssize_t) image->columns; x++) { if (*p > 0) { f = (*p / MaxVal) * (QuantumRange - GetPixelRed(q)); if (f + GetPixelRed(q) > QuantumRange) SetPixelRed(q,QuantumRange); else SetPixelRed(q,GetPixelRed(q)+(int) f); if ((int) f / 2.0 > GetPixelGreen(q)) { SetPixelGreen(q,0); SetPixelBlue(q,0); } else { SetPixelBlue(q,GetPixelBlue(q)-(int) (f/2.0)); SetPixelGreen(q,GetPixelBlue(q)); } } if (*p < 0) { f = (*p / MaxVal) * (QuantumRange - GetPixelBlue(q)); if (f + GetPixelBlue(q) > QuantumRange) SetPixelBlue(q,QuantumRange); else SetPixelBlue(q,GetPixelBlue(q)+(int) f); if ((int) f / 2.0 > q->green) { SetPixelRed(q,0); SetPixelGreen(q,0); } else { SetPixelRed(q,GetPixelRed(q)-(int) (f/2.0)); SetPixelGreen(q,GetPixelRed(q)); } } p++; q++; } if (!SyncAuthenticPixels(image,exception)) return; return; } static void InsertComplexFloatRow(float *p, int y, Image * image, double MinVal, double MaxVal) { ExceptionInfo *exception; double f; int x; register PixelPacket *q; if (MinVal == 0) MinVal = -1; if (MaxVal == 0) MaxVal = 1; exception=(&image->exception); q = QueueAuthenticPixels(image, 0, y, image->columns, 1,exception); if (q == (PixelPacket *) NULL) return; for (x = 0; x < (ssize_t) image->columns; x++) { if (*p > 0) { f = (*p / MaxVal) * (QuantumRange - GetPixelRed(q)); if (f + GetPixelRed(q) > QuantumRange) SetPixelRed(q,QuantumRange); else SetPixelRed(q,GetPixelRed(q)+(int) f); if ((int) f / 2.0 > GetPixelGreen(q)) { SetPixelGreen(q,0); SetPixelBlue(q,0); } else { SetPixelBlue(q,GetPixelBlue(q)-(int) (f/2.0)); SetPixelGreen(q,GetPixelBlue(q)); } } if (*p < 0) { f = (*p / MaxVal) * (QuantumRange - GetPixelBlue(q)); if (f + GetPixelBlue(q) > QuantumRange) SetPixelBlue(q,QuantumRange); else SetPixelBlue(q,GetPixelBlue(q)+(int) f); if ((int) f / 2.0 > q->green) { SetPixelGreen(q,0); SetPixelRed(q,0); } else { SetPixelRed(q,GetPixelRed(q)-(int) (f/2.0)); SetPixelGreen(q,GetPixelRed(q)); } } p++; q++; } if (!SyncAuthenticPixels(image,exception)) return; return; } /************** READERS ******************/ /* This function reads one block of floats*/ static void ReadBlobFloatsLSB(Image * image, size_t len, float *data) { while (len >= 4) { *data++ = ReadBlobFloat(image); len -= sizeof(float); } if (len > 0) (void) SeekBlob(image, len, SEEK_CUR); } static void ReadBlobFloatsMSB(Image * image, size_t len, float *data) { while (len >= 4) { *data++ = ReadBlobFloat(image); len -= sizeof(float); } if (len > 0) (void) SeekBlob(image, len, SEEK_CUR); } /* This function reads one block of doubles*/ static void ReadBlobDoublesLSB(Image * image, size_t len, double *data) { while (len >= 8) { *data++ = ReadBlobDouble(image); len -= sizeof(double); } if (len > 0) (void) SeekBlob(image, len, SEEK_CUR); } static void ReadBlobDoublesMSB(Image * image, size_t len, double *data) { while (len >= 8) { *data++ = ReadBlobDouble(image); len -= sizeof(double); } if (len > 0) (void) SeekBlob(image, len, SEEK_CUR); } /* Calculate minimum and maximum from a given block of data */ static void CalcMinMax(Image *image, int endian_indicator, int SizeX, int SizeY, size_t CellType, unsigned ldblk, void *BImgBuff, double *Min, double *Max) { MagickOffsetType filepos; int i, x; void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data); void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data); double *dblrow; float *fltrow; if (endian_indicator == LSBEndian) { ReadBlobDoublesXXX = ReadBlobDoublesLSB; ReadBlobFloatsXXX = ReadBlobFloatsLSB; } else /* MI */ { ReadBlobDoublesXXX = ReadBlobDoublesMSB; ReadBlobFloatsXXX = ReadBlobFloatsMSB; } filepos = TellBlob(image); /* Please note that file seeking occurs only in the case of doubles */ for (i = 0; i < SizeY; i++) { if (CellType==miDOUBLE) { ReadBlobDoublesXXX(image, ldblk, (double *)BImgBuff); dblrow = (double *)BImgBuff; if (i == 0) { *Min = *Max = *dblrow; } for (x = 0; x < SizeX; x++) { if (*Min > *dblrow) *Min = *dblrow; if (*Max < *dblrow) *Max = *dblrow; dblrow++; } } if (CellType==miSINGLE) { ReadBlobFloatsXXX(image, ldblk, (float *)BImgBuff); fltrow = (float *)BImgBuff; if (i == 0) { *Min = *Max = *fltrow; } for (x = 0; x < (ssize_t) SizeX; x++) { if (*Min > *fltrow) *Min = *fltrow; if (*Max < *fltrow) *Max = *fltrow; fltrow++; } } } (void) SeekBlob(image, filepos, SEEK_SET); } static void FixSignedValues(PixelPacket *q, int y) { while(y-->0) { /* Please note that negative values will overflow Q=8; QuantumRange=255: <0;127> + 127+1 = <128; 255> <-1;-128> + 127+1 = <0; 127> */ SetPixelRed(q,GetPixelRed(q)+QuantumRange/2+1); SetPixelGreen(q,GetPixelGreen(q)+QuantumRange/2+1); SetPixelBlue(q,GetPixelBlue(q)+QuantumRange/2+1); q++; } } /** Fix whole row of logical/binary data. It means pack it. */ static void FixLogical(unsigned char *Buff,int ldblk) { unsigned char mask=128; unsigned char *BuffL = Buff; unsigned char val = 0; while(ldblk-->0) { if(*Buff++ != 0) val |= mask; mask >>= 1; if(mask==0) { *BuffL++ = val; val = 0; mask = 128; } } *BuffL = val; } #if defined(MAGICKCORE_ZLIB_DELEGATE) static voidpf AcquireZIPMemory(voidpf context,unsigned int items, unsigned int size) { (void) context; return((voidpf) AcquireQuantumMemory(items,size)); } static void RelinquishZIPMemory(voidpf context,voidpf memory) { (void) context; memory=RelinquishMagickMemory(memory); } #endif #if defined(MAGICKCORE_ZLIB_DELEGATE) /** This procedure decompreses an image block for a new MATLAB format. */ static Image *DecompressBlock(Image *orig, MagickOffsetType Size, ImageInfo *clone_info, ExceptionInfo *exception) { Image *image2; void *CacheBlock, *DecompressBlock; z_stream zip_info; FILE *mat_file; size_t magick_size; size_t extent; int file; int status; int zip_status; if(clone_info==NULL) return NULL; if(clone_info->file) /* Close file opened from previous transaction. */ { fclose(clone_info->file); clone_info->file = NULL; (void) remove_utf8(clone_info->filename); } CacheBlock = AcquireQuantumMemory((size_t)((Size<16384)?Size:16384),sizeof(unsigned char *)); if(CacheBlock==NULL) return NULL; DecompressBlock = AcquireQuantumMemory((size_t)(4096),sizeof(unsigned char *)); if(DecompressBlock==NULL) { RelinquishMagickMemory(CacheBlock); return NULL; } mat_file=0; file = AcquireUniqueFileResource(clone_info->filename); if (file != -1) mat_file = fdopen(file,"w"); if(!mat_file) { RelinquishMagickMemory(CacheBlock); RelinquishMagickMemory(DecompressBlock); (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Cannot create file stream for decompressed image"); return NULL; } zip_info.zalloc=AcquireZIPMemory; zip_info.zfree=RelinquishZIPMemory; zip_info.opaque = (voidpf) NULL; zip_status = inflateInit(&zip_info); if (zip_status != Z_OK) { RelinquishMagickMemory(CacheBlock); RelinquishMagickMemory(DecompressBlock); (void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError, "UnableToUncompressImage","`%s'",clone_info->filename); (void) fclose(mat_file); RelinquishUniqueFileResource(clone_info->filename); return NULL; } /* zip_info.next_out = 8*4;*/ zip_info.avail_in = 0; zip_info.total_out = 0; while(Size>0 && !EOFBlob(orig)) { magick_size = ReadBlob(orig, (Size<16384)?Size:16384, (unsigned char *) CacheBlock); zip_info.next_in = (Bytef *) CacheBlock; zip_info.avail_in = (uInt) magick_size; while(zip_info.avail_in>0) { zip_info.avail_out = 4096; zip_info.next_out = (Bytef *) DecompressBlock; zip_status = inflate(&zip_info,Z_NO_FLUSH); if ((zip_status != Z_OK) && (zip_status != Z_STREAM_END)) break; extent=fwrite(DecompressBlock, 4096-zip_info.avail_out, 1, mat_file); (void) extent; if(zip_status == Z_STREAM_END) goto DblBreak; } if ((zip_status != Z_OK) && (zip_status != Z_STREAM_END)) break; Size -= magick_size; } DblBreak: inflateEnd(&zip_info); (void)fclose(mat_file); RelinquishMagickMemory(CacheBlock); RelinquishMagickMemory(DecompressBlock); if((clone_info->file=fopen(clone_info->filename,"rb"))==NULL) goto UnlinkFile; if( (image2 = AcquireImage(clone_info))==NULL ) goto EraseFile; status = OpenBlob(clone_info,image2,ReadBinaryBlobMode,exception); if (status == MagickFalse) { DeleteImageFromList(&image2); EraseFile: fclose(clone_info->file); clone_info->file = NULL; UnlinkFile: RelinquishUniqueFileResource(clone_info->filename); return NULL; } return image2; } #endif static Image *ReadMATImageV4(const ImageInfo *image_info,Image *image, ExceptionInfo *exception) { typedef struct { unsigned char Type[4]; unsigned int nRows; unsigned int nCols; unsigned int imagf; unsigned int nameLen; } MAT4_HDR; long ldblk; EndianType endian; Image *rotate_image; MagickBooleanType status; MAT4_HDR HDR; QuantumInfo *quantum_info; QuantumFormatType format_type; register ssize_t i; ssize_t y; unsigned char *pixels; unsigned int depth; (void) SeekBlob(image,0,SEEK_SET); ldblk=ReadBlobLSBLong(image); if ((ldblk > 9999) || (ldblk < 0)) return((Image *) NULL); HDR.Type[3]=ldblk % 10; ldblk /= 10; /* T digit */ HDR.Type[2]=ldblk % 10; ldblk /= 10; /* P digit */ HDR.Type[1]=ldblk % 10; ldblk /= 10; /* O digit */ HDR.Type[0]=ldblk; /* M digit */ if (HDR.Type[3] != 0) return((Image *) NULL); /* Data format */ if (HDR.Type[2] != 0) return((Image *) NULL); /* Always 0 */ if (HDR.Type[0] == 0) { HDR.nRows=ReadBlobLSBLong(image); HDR.nCols=ReadBlobLSBLong(image); HDR.imagf=ReadBlobLSBLong(image); HDR.nameLen=ReadBlobLSBLong(image); endian=LSBEndian; } else { HDR.nRows=ReadBlobMSBLong(image); HDR.nCols=ReadBlobMSBLong(image); HDR.imagf=ReadBlobMSBLong(image); HDR.nameLen=ReadBlobMSBLong(image); endian=MSBEndian; } if (HDR.nameLen > 0xFFFF) return((Image *) NULL); for (i=0; i < (ssize_t) HDR.nameLen; i++) { int byte; /* Skip matrix name. */ byte=ReadBlobByte(image); if (byte == EOF) return((Image *) NULL); } image->columns=(size_t) HDR.nRows; image->rows=(size_t) HDR.nCols; SetImageColorspace(image,GRAYColorspace); if (image_info->ping != MagickFalse) { Swap(image->columns,image->rows); return(image); } status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) return((Image *) NULL); quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) return((Image *) NULL); switch(HDR.Type[1]) { case 0: format_type=FloatingPointQuantumFormat; depth=64; break; case 1: format_type=FloatingPointQuantumFormat; depth=32; break; case 2: format_type=UnsignedQuantumFormat; depth=16; break; case 3: format_type=SignedQuantumFormat; depth=16; case 4: format_type=UnsignedQuantumFormat; depth=8; break; default: format_type=UnsignedQuantumFormat; depth=8; break; } image->depth=depth; if (HDR.Type[0] != 0) SetQuantumEndian(image,quantum_info,MSBEndian); status=SetQuantumFormat(image,quantum_info,format_type); status=SetQuantumDepth(image,quantum_info,depth); status=SetQuantumEndian(image,quantum_info,endian); SetQuantumScale(quantum_info,1.0); pixels=(unsigned char *) GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { ssize_t count; register PixelPacket *magick_restrict q; count=ReadBlob(image,depth/8*image->columns,(unsigned char *) pixels); if (count == -1) break; q=QueueAuthenticPixels(image,0,image->rows-y-1,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, GrayQuantum,pixels,exception); if ((HDR.Type[1] == 2) || (HDR.Type[1] == 3)) FixSignedValues(q,image->columns); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (HDR.imagf == 1) for (y=0; y < (ssize_t) image->rows; y++) { /* Read complex pixels. */ status=ReadBlob(image,depth/8*image->columns,(unsigned char *) pixels); if (status == -1) break; if (HDR.Type[1] == 0) InsertComplexDoubleRow((double *) pixels,y,image,0,0); else InsertComplexFloatRow((float *) pixels,y,image,0,0); } quantum_info=DestroyQuantumInfo(quantum_info); rotate_image=RotateImage(image,90.0,exception); if (rotate_image != (Image *) NULL) { image=DestroyImage(image); image=rotate_image; } return(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d M A T L A B i m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadMATImage() reads an MAT X 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 ReadMATImage method is: % % Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: Method ReadMATImage 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: Specifies a pointer to a ImageInfo structure. % % o exception: return any errors or warnings in this structure. % */ static Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image, *image2=NULL, *rotated_image; PixelPacket *q; unsigned int status; MATHeader MATLAB_HDR; size_t size; size_t CellType; QuantumInfo *quantum_info; ImageInfo *clone_info; int i; ssize_t ldblk; unsigned char *BImgBuff = NULL; double MinVal, MaxVal; size_t Unknown6; unsigned z, z2; unsigned Frames; int logging; int sample_size; MagickOffsetType filepos=0x80; BlobInfo *blob; size_t one; unsigned int (*ReadBlobXXXLong)(Image *image); unsigned short (*ReadBlobXXXShort)(Image *image); void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data); void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data); assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); logging = LogMagickEvent(CoderEvent,GetMagickModule(),"enter"); /* Open image file. */ image = AcquireImage(image_info); status = OpenBlob(image_info, image, ReadBinaryBlobMode, exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read MATLAB image. */ clone_info=CloneImageInfo(image_info); if(ReadBlob(image,124,(unsigned char *) &MATLAB_HDR.identific) != 124) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (strncmp(MATLAB_HDR.identific,"MATLAB",6) != 0) { image2=ReadMATImageV4(image_info,image,exception); if (image2 == NULL) goto MATLAB_KO; image=image2; goto END_OF_READING; } MATLAB_HDR.Version = ReadBlobLSBShort(image); if(ReadBlob(image,2,(unsigned char *) &MATLAB_HDR.EndianIndicator) != 2) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule()," Endian %c%c", MATLAB_HDR.EndianIndicator[0],MATLAB_HDR.EndianIndicator[1]); if (!strncmp(MATLAB_HDR.EndianIndicator, "IM", 2)) { ReadBlobXXXLong = ReadBlobLSBLong; ReadBlobXXXShort = ReadBlobLSBShort; ReadBlobDoublesXXX = ReadBlobDoublesLSB; ReadBlobFloatsXXX = ReadBlobFloatsLSB; image->endian = LSBEndian; } else if (!strncmp(MATLAB_HDR.EndianIndicator, "MI", 2)) { ReadBlobXXXLong = ReadBlobMSBLong; ReadBlobXXXShort = ReadBlobMSBShort; ReadBlobDoublesXXX = ReadBlobDoublesMSB; ReadBlobFloatsXXX = ReadBlobFloatsMSB; image->endian = MSBEndian; } else goto MATLAB_KO; /* unsupported endian */ if (strncmp(MATLAB_HDR.identific, "MATLAB", 6)) MATLAB_KO: ThrowReaderException(CorruptImageError,"ImproperImageHeader"); filepos = TellBlob(image); while(!EOFBlob(image)) /* object parser loop */ { Frames = 1; (void) SeekBlob(image,filepos,SEEK_SET); /* printf("pos=%X\n",TellBlob(image)); */ MATLAB_HDR.DataType = ReadBlobXXXLong(image); if(EOFBlob(image)) break; MATLAB_HDR.ObjectSize = ReadBlobXXXLong(image); if(EOFBlob(image)) break; filepos += MATLAB_HDR.ObjectSize + 4 + 4; image2 = image; #if defined(MAGICKCORE_ZLIB_DELEGATE) if(MATLAB_HDR.DataType == miCOMPRESSED) { image2 = DecompressBlock(image,MATLAB_HDR.ObjectSize,clone_info,exception); if(image2==NULL) continue; MATLAB_HDR.DataType = ReadBlobXXXLong(image2); /* replace compressed object type. */ } #endif if(MATLAB_HDR.DataType!=miMATRIX) continue; /* skip another objects. */ MATLAB_HDR.unknown1 = ReadBlobXXXLong(image2); MATLAB_HDR.unknown2 = ReadBlobXXXLong(image2); MATLAB_HDR.unknown5 = ReadBlobXXXLong(image2); MATLAB_HDR.StructureClass = MATLAB_HDR.unknown5 & 0xFF; MATLAB_HDR.StructureFlag = (MATLAB_HDR.unknown5>>8) & 0xFF; MATLAB_HDR.unknown3 = ReadBlobXXXLong(image2); if(image!=image2) MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2); /* ??? don't understand why ?? */ MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2); MATLAB_HDR.DimFlag = ReadBlobXXXLong(image2); MATLAB_HDR.SizeX = ReadBlobXXXLong(image2); MATLAB_HDR.SizeY = ReadBlobXXXLong(image2); switch(MATLAB_HDR.DimFlag) { case 8: z2=z=1; break; /* 2D matrix*/ case 12: z2=z = ReadBlobXXXLong(image2); /* 3D matrix RGB*/ Unknown6 = ReadBlobXXXLong(image2); (void) Unknown6; if(z!=3) ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported"); break; case 16: z2=z = ReadBlobXXXLong(image2); /* 4D matrix animation */ if(z!=3 && z!=1) ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported"); Frames = ReadBlobXXXLong(image2); break; default: ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported"); } MATLAB_HDR.Flag1 = ReadBlobXXXShort(image2); MATLAB_HDR.NameFlag = ReadBlobXXXShort(image2); if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), "MATLAB_HDR.StructureClass %d",MATLAB_HDR.StructureClass); if (MATLAB_HDR.StructureClass != mxCHAR_CLASS && MATLAB_HDR.StructureClass != mxSINGLE_CLASS && /* float + complex float */ MATLAB_HDR.StructureClass != mxDOUBLE_CLASS && /* double + complex double */ MATLAB_HDR.StructureClass != mxINT8_CLASS && MATLAB_HDR.StructureClass != mxUINT8_CLASS && /* uint8 + uint8 3D */ MATLAB_HDR.StructureClass != mxINT16_CLASS && MATLAB_HDR.StructureClass != mxUINT16_CLASS && /* uint16 + uint16 3D */ MATLAB_HDR.StructureClass != mxINT32_CLASS && MATLAB_HDR.StructureClass != mxUINT32_CLASS && /* uint32 + uint32 3D */ MATLAB_HDR.StructureClass != mxINT64_CLASS && MATLAB_HDR.StructureClass != mxUINT64_CLASS) /* uint64 + uint64 3D */ ThrowReaderException(CoderError,"UnsupportedCellTypeInTheMatrix"); switch (MATLAB_HDR.NameFlag) { case 0: size = ReadBlobXXXLong(image2); /* Object name string size */ size = 4 * (ssize_t) ((size + 3 + 1) / 4); (void) SeekBlob(image2, size, SEEK_CUR); break; case 1: case 2: case 3: case 4: (void) ReadBlob(image2, 4, (unsigned char *) &size); /* Object name string */ break; default: goto MATLAB_KO; } CellType = ReadBlobXXXLong(image2); /* Additional object type */ if (logging) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "MATLAB_HDR.CellType: %.20g",(double) CellType); (void) ReadBlob(image2, 4, (unsigned char *) &size); /* data size */ NEXT_FRAME: switch (CellType) { case miINT8: case miUINT8: sample_size = 8; if(MATLAB_HDR.StructureFlag & FLAG_LOGICAL) image->depth = 1; else image->depth = 8; /* Byte type cell */ ldblk = (ssize_t) MATLAB_HDR.SizeX; break; case miINT16: case miUINT16: sample_size = 16; image->depth = 16; /* Word type cell */ ldblk = (ssize_t) (2 * MATLAB_HDR.SizeX); break; case miINT32: case miUINT32: sample_size = 32; image->depth = 32; /* Dword type cell */ ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX); break; case miINT64: case miUINT64: sample_size = 64; image->depth = 64; /* Qword type cell */ ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX); break; case miSINGLE: sample_size = 32; image->depth = 32; /* double type cell */ (void) SetImageOption(clone_info,"quantum:format","floating-point"); if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX) { /* complex float type cell */ } ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX); break; case miDOUBLE: sample_size = 64; image->depth = 64; /* double type cell */ (void) SetImageOption(clone_info,"quantum:format","floating-point"); DisableMSCWarning(4127) if (sizeof(double) != 8) RestoreMSCWarning ThrowReaderException(CoderError, "IncompatibleSizeOfDouble"); if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX) { /* complex double type cell */ } ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX); break; default: ThrowReaderException(CoderError, "UnsupportedCellTypeInTheMatrix"); } (void) sample_size; image->columns = MATLAB_HDR.SizeX; image->rows = MATLAB_HDR.SizeY; quantum_info=AcquireQuantumInfo(clone_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); one=1; image->colors = one << image->depth; if (image->columns == 0 || image->rows == 0) goto MATLAB_KO; /* Image is gray when no complex flag is set and 2D Matrix */ if ((MATLAB_HDR.DimFlag == 8) && ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0)) { SetImageColorspace(image,GRAYColorspace); image->type=GrayscaleType; } /* If ping is true, then only set image size and colors without reading any image data. */ if (image_info->ping) { size_t temp = image->columns; image->columns = image->rows; image->rows = temp; goto done_reading; /* !!!!!! BAD !!!! */ } status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } /* ----- Load raster data ----- */ BImgBuff = (unsigned char *) AcquireQuantumMemory((size_t) (ldblk),sizeof(double)); /* Ldblk was set in the check phase */ if (BImgBuff == NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); MinVal = 0; MaxVal = 0; if (CellType==miDOUBLE || CellType==miSINGLE) /* Find Min and Max Values for floats */ { CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &quantum_info->minimum, &quantum_info->maximum); } /* Main loop for reading all scanlines */ if(z==1) z=0; /* read grey scanlines */ /* else read color scanlines */ do { for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++) { q=GetAuthenticPixels(image,0,MATLAB_HDR.SizeY-i-1,image->columns,1,exception); if (q == (PixelPacket *) NULL) { if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), " MAT set image pixels returns unexpected NULL on a row %u.", (unsigned)(MATLAB_HDR.SizeY-i-1)); goto done_reading; /* Skip image rotation, when cannot set image pixels */ } if(ReadBlob(image2,ldblk,(unsigned char *)BImgBuff) != (ssize_t) ldblk) { if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), " MAT cannot read scanrow %u from a file.", (unsigned)(MATLAB_HDR.SizeY-i-1)); goto ExitLoop; } if((CellType==miINT8 || CellType==miUINT8) && (MATLAB_HDR.StructureFlag & FLAG_LOGICAL)) { FixLogical((unsigned char *)BImgBuff,ldblk); if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0) { ImportQuantumPixelsFailed: if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), " MAT failed to ImportQuantumPixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1)); break; } } else { if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0) goto ImportQuantumPixelsFailed; if (z<=1 && /* fix only during a last pass z==0 || z==1 */ (CellType==miINT8 || CellType==miINT16 || CellType==miINT32 || CellType==miINT64)) FixSignedValues(q,MATLAB_HDR.SizeX); } if (!SyncAuthenticPixels(image,exception)) { if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), " MAT failed to sync image pixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1)); goto ExitLoop; } } } while(z-- >= 2); quantum_info=DestroyQuantumInfo(quantum_info); ExitLoop: /* Read complex part of numbers here */ if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX) { /* Find Min and Max Values for complex parts of floats */ CellType = ReadBlobXXXLong(image2); /* Additional object type */ i = ReadBlobXXXLong(image2); /* size of a complex part - toss away*/ if (CellType==miDOUBLE || CellType==miSINGLE) { CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &MinVal, &MaxVal); } if (CellType==miDOUBLE) for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++) { ReadBlobDoublesXXX(image2, ldblk, (double *)BImgBuff); InsertComplexDoubleRow((double *)BImgBuff, i, image, MinVal, MaxVal); } if (CellType==miSINGLE) for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++) { ReadBlobFloatsXXX(image2, ldblk, (float *)BImgBuff); InsertComplexFloatRow((float *)BImgBuff, i, image, MinVal, MaxVal); } } /* Image is gray when no complex flag is set and 2D Matrix AGAIN!!! */ if ((MATLAB_HDR.DimFlag == 8) && ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0)) image->type=GrayscaleType; if (image->depth == 1) image->type=BilevelType; if(image2==image) image2 = NULL; /* Remove shadow copy to an image before rotation. */ /* Rotate image. */ rotated_image = RotateImage(image, 90.0, exception); if (rotated_image != (Image *) NULL) { /* Remove page offsets added by RotateImage */ rotated_image->page.x=0; rotated_image->page.y=0; blob = rotated_image->blob; rotated_image->blob = image->blob; rotated_image->colors = image->colors; image->blob = blob; AppendImageToList(&image,rotated_image); DeleteImageFromList(&image); } done_reading: if(image2!=NULL) if(image2!=image) { DeleteImageFromList(&image2); if(clone_info) { if(clone_info->file) { fclose(clone_info->file); clone_info->file = NULL; (void) remove_utf8(clone_info->filename); } } } /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (image->next == (Image *) NULL) break; image=SyncNextImageInList(image); image->columns=image->rows=0; image->colors=0; /* row scan buffer is no longer needed */ RelinquishMagickMemory(BImgBuff); BImgBuff = NULL; if(--Frames>0) { z = z2; if(image2==NULL) image2 = image; goto NEXT_FRAME; } if(image2!=NULL) if(image2!=image) /* Does shadow temporary decompressed image exist? */ { /* CloseBlob(image2); */ DeleteImageFromList(&image2); if(clone_info) { if(clone_info->file) { fclose(clone_info->file); clone_info->file = NULL; (void) unlink(clone_info->filename); } } } } RelinquishMagickMemory(BImgBuff); END_OF_READING: clone_info=DestroyImageInfo(clone_info); CloseBlob(image); { Image *p; ssize_t scene=0; /* Rewind list, removing any empty images while rewinding. */ p=image; image=NULL; while (p != (Image *) NULL) { Image *tmp=p; if ((p->rows == 0) || (p->columns == 0)) { p=p->previous; DeleteImageFromList(&tmp); } else { image=p; p=p->previous; } } /* Fix scene numbers */ for (p=image; p != (Image *) NULL; p=p->next) p->scene=scene++; } if(clone_info != NULL) /* cleanup garbage file from compression */ { if(clone_info->file) { fclose(clone_info->file); clone_info->file = NULL; (void) remove_utf8(clone_info->filename); } DestroyImageInfo(clone_info); clone_info = NULL; } if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),"return"); if(image==NULL) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); return (image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r M A T I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Method RegisterMATImage adds attributes for the MAT 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 RegisterMATImage method is: % % size_t RegisterMATImage(void) % */ ModuleExport size_t RegisterMATImage(void) { MagickInfo *entry; entry=SetMagickInfo("MAT"); entry->decoder=(DecodeImageHandler *) ReadMATImage; entry->encoder=(EncodeImageHandler *) WriteMATImage; entry->blob_support=MagickFalse; entry->seekable_stream=MagickTrue; entry->description=AcquireString("MATLAB level 5 image format"); entry->module=AcquireString("MAT"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r M A T I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Method UnregisterMATImage removes format registrations made by the % MAT module from the list of supported formats. % % The format of the UnregisterMATImage method is: % % UnregisterMATImage(void) % */ ModuleExport void UnregisterMATImage(void) { (void) UnregisterMagickInfo("MAT"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e M A T L A B I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Function WriteMATImage writes an Matlab matrix to a file. % % The format of the WriteMATImage method is: % % unsigned int WriteMATImage(const ImageInfo *image_info,Image *image) % % A description of each parameter follows. % % o status: Function WriteMATImage return True if the image is written. % False is returned is there is a memory shortage or if the image file % fails to write. % % o image_info: Specifies a pointer to a ImageInfo structure. % % o image: A pointer to an Image structure. % */ static MagickBooleanType WriteMATImage(const ImageInfo *image_info,Image *image) { ExceptionInfo *exception; ssize_t y; unsigned z; const PixelPacket *p; unsigned int status; int logging; size_t DataSize; char padding; char MATLAB_HDR[0x80]; time_t current_time; struct tm local_time; unsigned char *pixels; int is_gray; MagickOffsetType scene; QuantumInfo *quantum_info; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); logging=LogMagickEvent(CoderEvent,GetMagickModule(),"enter MAT"); (void) logging; status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(MagickFalse); image->depth=8; current_time=time((time_t *) NULL); #if defined(MAGICKCORE_HAVE_LOCALTIME_R) (void) localtime_r(&current_time,&local_time); #else (void) memcpy(&local_time,localtime(&current_time),sizeof(local_time)); #endif (void) memset(MATLAB_HDR,' ',MagickMin(sizeof(MATLAB_HDR),124)); FormatLocaleString(MATLAB_HDR,sizeof(MATLAB_HDR), "MATLAB 5.0 MAT-file, Platform: %s, Created on: %s %s %2d %2d:%2d:%2d %d", OsDesc,DayOfWTab[local_time.tm_wday],MonthsTab[local_time.tm_mon], local_time.tm_mday,local_time.tm_hour,local_time.tm_min, local_time.tm_sec,local_time.tm_year+1900); MATLAB_HDR[0x7C]=0; MATLAB_HDR[0x7D]=1; MATLAB_HDR[0x7E]='I'; MATLAB_HDR[0x7F]='M'; (void) WriteBlob(image,sizeof(MATLAB_HDR),(unsigned char *) MATLAB_HDR); scene=0; do { (void) TransformImageColorspace(image,sRGBColorspace); is_gray = SetImageGray(image,&image->exception); z = is_gray ? 0 : 3; /* Store MAT header. */ DataSize = image->rows /*Y*/ * image->columns /*X*/; if(!is_gray) DataSize *= 3 /*Z*/; padding=((unsigned char)(DataSize-1) & 0x7) ^ 0x7; (void) WriteBlobLSBLong(image, miMATRIX); (void) WriteBlobLSBLong(image, (unsigned int) DataSize+padding+(is_gray ? 48 : 56)); (void) WriteBlobLSBLong(image, 0x6); /* 0x88 */ (void) WriteBlobLSBLong(image, 0x8); /* 0x8C */ (void) WriteBlobLSBLong(image, 0x6); /* 0x90 */ (void) WriteBlobLSBLong(image, 0); (void) WriteBlobLSBLong(image, 0x5); /* 0x98 */ (void) WriteBlobLSBLong(image, is_gray ? 0x8 : 0xC); /* 0x9C - DimFlag */ (void) WriteBlobLSBLong(image, (unsigned int) image->rows); /* x: 0xA0 */ (void) WriteBlobLSBLong(image, (unsigned int) image->columns); /* y: 0xA4 */ if(!is_gray) { (void) WriteBlobLSBLong(image, 3); /* z: 0xA8 */ (void) WriteBlobLSBLong(image, 0); } (void) WriteBlobLSBShort(image, 1); /* 0xB0 */ (void) WriteBlobLSBShort(image, 1); /* 0xB2 */ (void) WriteBlobLSBLong(image, 'M'); /* 0xB4 */ (void) WriteBlobLSBLong(image, 0x2); /* 0xB8 */ (void) WriteBlobLSBLong(image, (unsigned int) DataSize); /* 0xBC */ /* Store image data. */ exception=(&image->exception); quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); pixels=GetQuantumPixels(quantum_info); do { for (y=0; y < (ssize_t)image->columns; y++) { p=GetVirtualPixels(image,y,0,1,image->rows,&image->exception); if (p == (const PixelPacket *) NULL) break; (void) ExportQuantumPixels(image,(const CacheView *) NULL,quantum_info, z2qtype[z],pixels,exception); (void) WriteBlob(image,image->rows,pixels); } if (!SyncAuthenticPixels(image,exception)) break; } while(z-- >= 2); while(padding-->0) (void) WriteBlobByte(image,0); quantum_info=DestroyQuantumInfo(quantum_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-20/c/bad_4790_0
crossvul-cpp_data_good_3515_0
/* * AppArmor security module * * This file contains AppArmor LSM hooks. * * Copyright (C) 1998-2008 Novell/SUSE * Copyright 2009-2010 Canonical Ltd. * * 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, version 2 of the * License. */ #include <linux/security.h> #include <linux/moduleparam.h> #include <linux/mm.h> #include <linux/mman.h> #include <linux/mount.h> #include <linux/namei.h> #include <linux/ptrace.h> #include <linux/ctype.h> #include <linux/sysctl.h> #include <linux/audit.h> #include <linux/user_namespace.h> #include <net/sock.h> #include "include/apparmor.h" #include "include/apparmorfs.h" #include "include/audit.h" #include "include/capability.h" #include "include/context.h" #include "include/file.h" #include "include/ipc.h" #include "include/path.h" #include "include/policy.h" #include "include/procattr.h" /* Flag indicating whether initialization completed */ int apparmor_initialized __initdata; /* * LSM hook functions */ /* * free the associated aa_task_cxt and put its profiles */ static void apparmor_cred_free(struct cred *cred) { aa_free_task_context(cred->security); cred->security = NULL; } /* * allocate the apparmor part of blank credentials */ static int apparmor_cred_alloc_blank(struct cred *cred, gfp_t gfp) { /* freed by apparmor_cred_free */ struct aa_task_cxt *cxt = aa_alloc_task_context(gfp); if (!cxt) return -ENOMEM; cred->security = cxt; return 0; } /* * prepare new aa_task_cxt for modification by prepare_cred block */ static int apparmor_cred_prepare(struct cred *new, const struct cred *old, gfp_t gfp) { /* freed by apparmor_cred_free */ struct aa_task_cxt *cxt = aa_alloc_task_context(gfp); if (!cxt) return -ENOMEM; aa_dup_task_context(cxt, old->security); new->security = cxt; return 0; } /* * transfer the apparmor data to a blank set of creds */ static void apparmor_cred_transfer(struct cred *new, const struct cred *old) { const struct aa_task_cxt *old_cxt = old->security; struct aa_task_cxt *new_cxt = new->security; aa_dup_task_context(new_cxt, old_cxt); } static int apparmor_ptrace_access_check(struct task_struct *child, unsigned int mode) { int error = cap_ptrace_access_check(child, mode); if (error) return error; return aa_ptrace(current, child, mode); } static int apparmor_ptrace_traceme(struct task_struct *parent) { int error = cap_ptrace_traceme(parent); if (error) return error; return aa_ptrace(parent, current, PTRACE_MODE_ATTACH); } /* Derived from security/commoncap.c:cap_capget */ static int apparmor_capget(struct task_struct *target, kernel_cap_t *effective, kernel_cap_t *inheritable, kernel_cap_t *permitted) { struct aa_profile *profile; const struct cred *cred; rcu_read_lock(); cred = __task_cred(target); profile = aa_cred_profile(cred); *effective = cred->cap_effective; *inheritable = cred->cap_inheritable; *permitted = cred->cap_permitted; if (!unconfined(profile)) { *effective = cap_intersect(*effective, profile->caps.allow); *permitted = cap_intersect(*permitted, profile->caps.allow); } rcu_read_unlock(); return 0; } static int apparmor_capable(struct task_struct *task, const struct cred *cred, struct user_namespace *ns, int cap, int audit) { struct aa_profile *profile; /* cap_capable returns 0 on success, else -EPERM */ int error = cap_capable(task, cred, ns, cap, audit); if (!error) { profile = aa_cred_profile(cred); if (!unconfined(profile)) error = aa_capable(task, profile, cap, audit); } return error; } /** * common_perm - basic common permission check wrapper fn for paths * @op: operation being checked * @path: path to check permission of (NOT NULL) * @mask: requested permissions mask * @cond: conditional info for the permission request (NOT NULL) * * Returns: %0 else error code if error or permission denied */ static int common_perm(int op, struct path *path, u32 mask, struct path_cond *cond) { struct aa_profile *profile; int error = 0; profile = __aa_current_profile(); if (!unconfined(profile)) error = aa_path_perm(op, profile, path, 0, mask, cond); return error; } /** * common_perm_dir_dentry - common permission wrapper when path is dir, dentry * @op: operation being checked * @dir: directory of the dentry (NOT NULL) * @dentry: dentry to check (NOT NULL) * @mask: requested permissions mask * @cond: conditional info for the permission request (NOT NULL) * * Returns: %0 else error code if error or permission denied */ static int common_perm_dir_dentry(int op, struct path *dir, struct dentry *dentry, u32 mask, struct path_cond *cond) { struct path path = { dir->mnt, dentry }; return common_perm(op, &path, mask, cond); } /** * common_perm_mnt_dentry - common permission wrapper when mnt, dentry * @op: operation being checked * @mnt: mount point of dentry (NOT NULL) * @dentry: dentry to check (NOT NULL) * @mask: requested permissions mask * * Returns: %0 else error code if error or permission denied */ static int common_perm_mnt_dentry(int op, struct vfsmount *mnt, struct dentry *dentry, u32 mask) { struct path path = { mnt, dentry }; struct path_cond cond = { dentry->d_inode->i_uid, dentry->d_inode->i_mode }; return common_perm(op, &path, mask, &cond); } /** * common_perm_rm - common permission wrapper for operations doing rm * @op: operation being checked * @dir: directory that the dentry is in (NOT NULL) * @dentry: dentry being rm'd (NOT NULL) * @mask: requested permission mask * * Returns: %0 else error code if error or permission denied */ static int common_perm_rm(int op, struct path *dir, struct dentry *dentry, u32 mask) { struct inode *inode = dentry->d_inode; struct path_cond cond = { }; if (!inode || !dir->mnt || !mediated_filesystem(inode)) return 0; cond.uid = inode->i_uid; cond.mode = inode->i_mode; return common_perm_dir_dentry(op, dir, dentry, mask, &cond); } /** * common_perm_create - common permission wrapper for operations doing create * @op: operation being checked * @dir: directory that dentry will be created in (NOT NULL) * @dentry: dentry to create (NOT NULL) * @mask: request permission mask * @mode: created file mode * * Returns: %0 else error code if error or permission denied */ static int common_perm_create(int op, struct path *dir, struct dentry *dentry, u32 mask, umode_t mode) { struct path_cond cond = { current_fsuid(), mode }; if (!dir->mnt || !mediated_filesystem(dir->dentry->d_inode)) return 0; return common_perm_dir_dentry(op, dir, dentry, mask, &cond); } static int apparmor_path_unlink(struct path *dir, struct dentry *dentry) { return common_perm_rm(OP_UNLINK, dir, dentry, AA_MAY_DELETE); } static int apparmor_path_mkdir(struct path *dir, struct dentry *dentry, int mode) { return common_perm_create(OP_MKDIR, dir, dentry, AA_MAY_CREATE, S_IFDIR); } static int apparmor_path_rmdir(struct path *dir, struct dentry *dentry) { return common_perm_rm(OP_RMDIR, dir, dentry, AA_MAY_DELETE); } static int apparmor_path_mknod(struct path *dir, struct dentry *dentry, int mode, unsigned int dev) { return common_perm_create(OP_MKNOD, dir, dentry, AA_MAY_CREATE, mode); } static int apparmor_path_truncate(struct path *path) { struct path_cond cond = { path->dentry->d_inode->i_uid, path->dentry->d_inode->i_mode }; if (!path->mnt || !mediated_filesystem(path->dentry->d_inode)) return 0; return common_perm(OP_TRUNC, path, MAY_WRITE | AA_MAY_META_WRITE, &cond); } static int apparmor_path_symlink(struct path *dir, struct dentry *dentry, const char *old_name) { return common_perm_create(OP_SYMLINK, dir, dentry, AA_MAY_CREATE, S_IFLNK); } static int apparmor_path_link(struct dentry *old_dentry, struct path *new_dir, struct dentry *new_dentry) { struct aa_profile *profile; int error = 0; if (!mediated_filesystem(old_dentry->d_inode)) return 0; profile = aa_current_profile(); if (!unconfined(profile)) error = aa_path_link(profile, old_dentry, new_dir, new_dentry); return error; } static int apparmor_path_rename(struct path *old_dir, struct dentry *old_dentry, struct path *new_dir, struct dentry *new_dentry) { struct aa_profile *profile; int error = 0; if (!mediated_filesystem(old_dentry->d_inode)) return 0; profile = aa_current_profile(); if (!unconfined(profile)) { struct path old_path = { old_dir->mnt, old_dentry }; struct path new_path = { new_dir->mnt, new_dentry }; struct path_cond cond = { old_dentry->d_inode->i_uid, old_dentry->d_inode->i_mode }; error = aa_path_perm(OP_RENAME_SRC, profile, &old_path, 0, MAY_READ | AA_MAY_META_READ | MAY_WRITE | AA_MAY_META_WRITE | AA_MAY_DELETE, &cond); if (!error) error = aa_path_perm(OP_RENAME_DEST, profile, &new_path, 0, MAY_WRITE | AA_MAY_META_WRITE | AA_MAY_CREATE, &cond); } return error; } static int apparmor_path_chmod(struct dentry *dentry, struct vfsmount *mnt, mode_t mode) { if (!mediated_filesystem(dentry->d_inode)) return 0; return common_perm_mnt_dentry(OP_CHMOD, mnt, dentry, AA_MAY_CHMOD); } static int apparmor_path_chown(struct path *path, uid_t uid, gid_t gid) { struct path_cond cond = { path->dentry->d_inode->i_uid, path->dentry->d_inode->i_mode }; if (!mediated_filesystem(path->dentry->d_inode)) return 0; return common_perm(OP_CHOWN, path, AA_MAY_CHOWN, &cond); } static int apparmor_inode_getattr(struct vfsmount *mnt, struct dentry *dentry) { if (!mediated_filesystem(dentry->d_inode)) return 0; return common_perm_mnt_dentry(OP_GETATTR, mnt, dentry, AA_MAY_META_READ); } static int apparmor_dentry_open(struct file *file, const struct cred *cred) { struct aa_file_cxt *fcxt = file->f_security; struct aa_profile *profile; int error = 0; if (!mediated_filesystem(file->f_path.dentry->d_inode)) return 0; /* If in exec, permission is handled by bprm hooks. * Cache permissions granted by the previous exec check, with * implicit read and executable mmap which are required to * actually execute the image. */ if (current->in_execve) { fcxt->allow = MAY_EXEC | MAY_READ | AA_EXEC_MMAP; return 0; } profile = aa_cred_profile(cred); if (!unconfined(profile)) { struct inode *inode = file->f_path.dentry->d_inode; struct path_cond cond = { inode->i_uid, inode->i_mode }; error = aa_path_perm(OP_OPEN, profile, &file->f_path, 0, aa_map_file_to_perms(file), &cond); /* todo cache full allowed permissions set and state */ fcxt->allow = aa_map_file_to_perms(file); } return error; } static int apparmor_file_alloc_security(struct file *file) { /* freed by apparmor_file_free_security */ file->f_security = aa_alloc_file_context(GFP_KERNEL); if (!file->f_security) return -ENOMEM; return 0; } static void apparmor_file_free_security(struct file *file) { struct aa_file_cxt *cxt = file->f_security; aa_free_file_context(cxt); } static int common_file_perm(int op, struct file *file, u32 mask) { struct aa_file_cxt *fcxt = file->f_security; struct aa_profile *profile, *fprofile = aa_cred_profile(file->f_cred); int error = 0; BUG_ON(!fprofile); if (!file->f_path.mnt || !mediated_filesystem(file->f_path.dentry->d_inode)) return 0; profile = __aa_current_profile(); /* revalidate access, if task is unconfined, or the cached cred * doesn't match or if the request is for more permissions than * was granted. * * Note: the test for !unconfined(fprofile) is to handle file * delegation from unconfined tasks */ if (!unconfined(profile) && !unconfined(fprofile) && ((fprofile != profile) || (mask & ~fcxt->allow))) error = aa_file_perm(op, profile, file, mask); return error; } static int apparmor_file_permission(struct file *file, int mask) { return common_file_perm(OP_FPERM, file, mask); } static int apparmor_file_lock(struct file *file, unsigned int cmd) { u32 mask = AA_MAY_LOCK; if (cmd == F_WRLCK) mask |= MAY_WRITE; return common_file_perm(OP_FLOCK, file, mask); } static int common_mmap(int op, struct file *file, unsigned long prot, unsigned long flags) { struct dentry *dentry; int mask = 0; if (!file || !file->f_security) return 0; if (prot & PROT_READ) mask |= MAY_READ; /* * Private mappings don't require write perms since they don't * write back to the files */ if ((prot & PROT_WRITE) && !(flags & MAP_PRIVATE)) mask |= MAY_WRITE; if (prot & PROT_EXEC) mask |= AA_EXEC_MMAP; dentry = file->f_path.dentry; return common_file_perm(op, file, mask); } static int apparmor_file_mmap(struct file *file, unsigned long reqprot, unsigned long prot, unsigned long flags, unsigned long addr, unsigned long addr_only) { int rc = 0; /* do DAC check */ rc = cap_file_mmap(file, reqprot, prot, flags, addr, addr_only); if (rc || addr_only) return rc; return common_mmap(OP_FMMAP, file, prot, flags); } static int apparmor_file_mprotect(struct vm_area_struct *vma, unsigned long reqprot, unsigned long prot) { return common_mmap(OP_FMPROT, vma->vm_file, prot, !(vma->vm_flags & VM_SHARED) ? MAP_PRIVATE : 0); } static int apparmor_getprocattr(struct task_struct *task, char *name, char **value) { int error = -ENOENT; struct aa_profile *profile; /* released below */ const struct cred *cred = get_task_cred(task); struct aa_task_cxt *cxt = cred->security; profile = aa_cred_profile(cred); if (strcmp(name, "current") == 0) error = aa_getprocattr(aa_newest_version(cxt->profile), value); else if (strcmp(name, "prev") == 0 && cxt->previous) error = aa_getprocattr(aa_newest_version(cxt->previous), value); else if (strcmp(name, "exec") == 0 && cxt->onexec) error = aa_getprocattr(aa_newest_version(cxt->onexec), value); else error = -EINVAL; put_cred(cred); return error; } static int apparmor_setprocattr(struct task_struct *task, char *name, void *value, size_t size) { char *command, *args = value; size_t arg_size; int error; if (size == 0) return -EINVAL; /* args points to a PAGE_SIZE buffer, AppArmor requires that * the buffer must be null terminated or have size <= PAGE_SIZE -1 * so that AppArmor can null terminate them */ if (args[size - 1] != '\0') { if (size == PAGE_SIZE) return -EINVAL; args[size] = '\0'; } /* task can only write its own attributes */ if (current != task) return -EACCES; args = value; args = strim(args); command = strsep(&args, " "); if (!args) return -EINVAL; args = skip_spaces(args); if (!*args) return -EINVAL; arg_size = size - (args - (char *) value); if (strcmp(name, "current") == 0) { if (strcmp(command, "changehat") == 0) { error = aa_setprocattr_changehat(args, arg_size, !AA_DO_TEST); } else if (strcmp(command, "permhat") == 0) { error = aa_setprocattr_changehat(args, arg_size, AA_DO_TEST); } else if (strcmp(command, "changeprofile") == 0) { error = aa_setprocattr_changeprofile(args, !AA_ONEXEC, !AA_DO_TEST); } else if (strcmp(command, "permprofile") == 0) { error = aa_setprocattr_changeprofile(args, !AA_ONEXEC, AA_DO_TEST); } else if (strcmp(command, "permipc") == 0) { error = aa_setprocattr_permipc(args); } else { struct common_audit_data sa; COMMON_AUDIT_DATA_INIT(&sa, NONE); sa.aad.op = OP_SETPROCATTR; sa.aad.info = name; sa.aad.error = -EINVAL; return aa_audit(AUDIT_APPARMOR_DENIED, __aa_current_profile(), GFP_KERNEL, &sa, NULL); } } else if (strcmp(name, "exec") == 0) { error = aa_setprocattr_changeprofile(args, AA_ONEXEC, !AA_DO_TEST); } else { /* only support the "current" and "exec" process attributes */ return -EINVAL; } if (!error) error = size; return error; } static int apparmor_task_setrlimit(struct task_struct *task, unsigned int resource, struct rlimit *new_rlim) { struct aa_profile *profile = aa_current_profile(); int error = 0; if (!unconfined(profile)) error = aa_task_setrlimit(profile, task, resource, new_rlim); return error; } static struct security_operations apparmor_ops = { .name = "apparmor", .ptrace_access_check = apparmor_ptrace_access_check, .ptrace_traceme = apparmor_ptrace_traceme, .capget = apparmor_capget, .capable = apparmor_capable, .path_link = apparmor_path_link, .path_unlink = apparmor_path_unlink, .path_symlink = apparmor_path_symlink, .path_mkdir = apparmor_path_mkdir, .path_rmdir = apparmor_path_rmdir, .path_mknod = apparmor_path_mknod, .path_rename = apparmor_path_rename, .path_chmod = apparmor_path_chmod, .path_chown = apparmor_path_chown, .path_truncate = apparmor_path_truncate, .dentry_open = apparmor_dentry_open, .inode_getattr = apparmor_inode_getattr, .file_permission = apparmor_file_permission, .file_alloc_security = apparmor_file_alloc_security, .file_free_security = apparmor_file_free_security, .file_mmap = apparmor_file_mmap, .file_mprotect = apparmor_file_mprotect, .file_lock = apparmor_file_lock, .getprocattr = apparmor_getprocattr, .setprocattr = apparmor_setprocattr, .cred_alloc_blank = apparmor_cred_alloc_blank, .cred_free = apparmor_cred_free, .cred_prepare = apparmor_cred_prepare, .cred_transfer = apparmor_cred_transfer, .bprm_set_creds = apparmor_bprm_set_creds, .bprm_committing_creds = apparmor_bprm_committing_creds, .bprm_committed_creds = apparmor_bprm_committed_creds, .bprm_secureexec = apparmor_bprm_secureexec, .task_setrlimit = apparmor_task_setrlimit, }; /* * AppArmor sysfs module parameters */ static int param_set_aabool(const char *val, const struct kernel_param *kp); static int param_get_aabool(char *buffer, const struct kernel_param *kp); #define param_check_aabool(name, p) __param_check(name, p, int) static struct kernel_param_ops param_ops_aabool = { .set = param_set_aabool, .get = param_get_aabool }; static int param_set_aauint(const char *val, const struct kernel_param *kp); static int param_get_aauint(char *buffer, const struct kernel_param *kp); #define param_check_aauint(name, p) __param_check(name, p, int) static struct kernel_param_ops param_ops_aauint = { .set = param_set_aauint, .get = param_get_aauint }; static int param_set_aalockpolicy(const char *val, const struct kernel_param *kp); static int param_get_aalockpolicy(char *buffer, const struct kernel_param *kp); #define param_check_aalockpolicy(name, p) __param_check(name, p, int) static struct kernel_param_ops param_ops_aalockpolicy = { .set = param_set_aalockpolicy, .get = param_get_aalockpolicy }; static int param_set_audit(const char *val, struct kernel_param *kp); static int param_get_audit(char *buffer, struct kernel_param *kp); static int param_set_mode(const char *val, struct kernel_param *kp); static int param_get_mode(char *buffer, struct kernel_param *kp); /* Flag values, also controllable via /sys/module/apparmor/parameters * We define special types as we want to do additional mediation. */ /* AppArmor global enforcement switch - complain, enforce, kill */ enum profile_mode aa_g_profile_mode = APPARMOR_ENFORCE; module_param_call(mode, param_set_mode, param_get_mode, &aa_g_profile_mode, S_IRUSR | S_IWUSR); /* Debug mode */ int aa_g_debug; module_param_named(debug, aa_g_debug, aabool, S_IRUSR | S_IWUSR); /* Audit mode */ enum audit_mode aa_g_audit; module_param_call(audit, param_set_audit, param_get_audit, &aa_g_audit, S_IRUSR | S_IWUSR); /* Determines if audit header is included in audited messages. This * provides more context if the audit daemon is not running */ int aa_g_audit_header = 1; module_param_named(audit_header, aa_g_audit_header, aabool, S_IRUSR | S_IWUSR); /* lock out loading/removal of policy * TODO: add in at boot loading of policy, which is the only way to * load policy, if lock_policy is set */ int aa_g_lock_policy; module_param_named(lock_policy, aa_g_lock_policy, aalockpolicy, S_IRUSR | S_IWUSR); /* Syscall logging mode */ int aa_g_logsyscall; module_param_named(logsyscall, aa_g_logsyscall, aabool, S_IRUSR | S_IWUSR); /* Maximum pathname length before accesses will start getting rejected */ unsigned int aa_g_path_max = 2 * PATH_MAX; module_param_named(path_max, aa_g_path_max, aauint, S_IRUSR | S_IWUSR); /* Determines how paranoid loading of policy is and how much verification * on the loaded policy is done. */ int aa_g_paranoid_load = 1; module_param_named(paranoid_load, aa_g_paranoid_load, aabool, S_IRUSR | S_IWUSR); /* Boot time disable flag */ static unsigned int apparmor_enabled = CONFIG_SECURITY_APPARMOR_BOOTPARAM_VALUE; module_param_named(enabled, apparmor_enabled, aabool, S_IRUSR); static int __init apparmor_enabled_setup(char *str) { unsigned long enabled; int error = strict_strtoul(str, 0, &enabled); if (!error) apparmor_enabled = enabled ? 1 : 0; return 1; } __setup("apparmor=", apparmor_enabled_setup); /* set global flag turning off the ability to load policy */ static int param_set_aalockpolicy(const char *val, const struct kernel_param *kp) { if (!capable(CAP_MAC_ADMIN)) return -EPERM; if (aa_g_lock_policy) return -EACCES; return param_set_bool(val, kp); } static int param_get_aalockpolicy(char *buffer, const struct kernel_param *kp) { if (!capable(CAP_MAC_ADMIN)) return -EPERM; return param_get_bool(buffer, kp); } static int param_set_aabool(const char *val, const struct kernel_param *kp) { if (!capable(CAP_MAC_ADMIN)) return -EPERM; return param_set_bool(val, kp); } static int param_get_aabool(char *buffer, const struct kernel_param *kp) { if (!capable(CAP_MAC_ADMIN)) return -EPERM; return param_get_bool(buffer, kp); } static int param_set_aauint(const char *val, const struct kernel_param *kp) { if (!capable(CAP_MAC_ADMIN)) return -EPERM; return param_set_uint(val, kp); } static int param_get_aauint(char *buffer, const struct kernel_param *kp) { if (!capable(CAP_MAC_ADMIN)) return -EPERM; return param_get_uint(buffer, kp); } static int param_get_audit(char *buffer, struct kernel_param *kp) { if (!capable(CAP_MAC_ADMIN)) return -EPERM; if (!apparmor_enabled) return -EINVAL; return sprintf(buffer, "%s", audit_mode_names[aa_g_audit]); } static int param_set_audit(const char *val, struct kernel_param *kp) { int i; if (!capable(CAP_MAC_ADMIN)) return -EPERM; if (!apparmor_enabled) return -EINVAL; if (!val) return -EINVAL; for (i = 0; i < AUDIT_MAX_INDEX; i++) { if (strcmp(val, audit_mode_names[i]) == 0) { aa_g_audit = i; return 0; } } return -EINVAL; } static int param_get_mode(char *buffer, struct kernel_param *kp) { if (!capable(CAP_MAC_ADMIN)) return -EPERM; if (!apparmor_enabled) return -EINVAL; return sprintf(buffer, "%s", profile_mode_names[aa_g_profile_mode]); } static int param_set_mode(const char *val, struct kernel_param *kp) { int i; if (!capable(CAP_MAC_ADMIN)) return -EPERM; if (!apparmor_enabled) return -EINVAL; if (!val) return -EINVAL; for (i = 0; i < APPARMOR_NAMES_MAX_INDEX; i++) { if (strcmp(val, profile_mode_names[i]) == 0) { aa_g_profile_mode = i; return 0; } } return -EINVAL; } /* * AppArmor init functions */ /** * set_init_cxt - set a task context and profile on the first task. * * TODO: allow setting an alternate profile than unconfined */ static int __init set_init_cxt(void) { struct cred *cred = (struct cred *)current->real_cred; struct aa_task_cxt *cxt; cxt = aa_alloc_task_context(GFP_KERNEL); if (!cxt) return -ENOMEM; cxt->profile = aa_get_profile(root_ns->unconfined); cred->security = cxt; return 0; } static int __init apparmor_init(void) { int error; if (!apparmor_enabled || !security_module_enable(&apparmor_ops)) { aa_info_message("AppArmor disabled by boot time parameter"); apparmor_enabled = 0; return 0; } error = aa_alloc_root_ns(); if (error) { AA_ERROR("Unable to allocate default profile namespace\n"); goto alloc_out; } error = set_init_cxt(); if (error) { AA_ERROR("Failed to set context on init task\n"); goto register_security_out; } error = register_security(&apparmor_ops); if (error) { AA_ERROR("Unable to register AppArmor\n"); goto set_init_cxt_out; } /* Report that AppArmor successfully initialized */ apparmor_initialized = 1; if (aa_g_profile_mode == APPARMOR_COMPLAIN) aa_info_message("AppArmor initialized: complain mode enabled"); else if (aa_g_profile_mode == APPARMOR_KILL) aa_info_message("AppArmor initialized: kill mode enabled"); else aa_info_message("AppArmor initialized"); return error; set_init_cxt_out: aa_free_task_context(current->real_cred->security); register_security_out: aa_free_root_ns(); alloc_out: aa_destroy_aafs(); apparmor_enabled = 0; return error; } security_initcall(apparmor_init);
./CrossVul/dataset_final_sorted/CWE-20/c/good_3515_0
crossvul-cpp_data_bad_5845_13
/* * 32bit Socket syscall emulation. Based on arch/sparc64/kernel/sys_sparc32.c. * * Copyright (C) 2000 VA Linux Co * Copyright (C) 2000 Don Dugger <n0ano@valinux.com> * Copyright (C) 1999 Arun Sharma <arun.sharma@intel.com> * Copyright (C) 1997,1998 Jakub Jelinek (jj@sunsite.mff.cuni.cz) * Copyright (C) 1997 David S. Miller (davem@caip.rutgers.edu) * Copyright (C) 2000 Hewlett-Packard Co. * Copyright (C) 2000 David Mosberger-Tang <davidm@hpl.hp.com> * Copyright (C) 2000,2001 Andi Kleen, SuSE Labs */ #include <linux/kernel.h> #include <linux/gfp.h> #include <linux/fs.h> #include <linux/types.h> #include <linux/file.h> #include <linux/icmpv6.h> #include <linux/socket.h> #include <linux/syscalls.h> #include <linux/filter.h> #include <linux/compat.h> #include <linux/security.h> #include <linux/export.h> #include <net/scm.h> #include <net/sock.h> #include <net/ip.h> #include <net/ipv6.h> #include <asm/uaccess.h> #include <net/compat.h> static inline int iov_from_user_compat_to_kern(struct iovec *kiov, struct compat_iovec __user *uiov32, int niov) { int tot_len = 0; while (niov > 0) { compat_uptr_t buf; compat_size_t len; if (get_user(len, &uiov32->iov_len) || get_user(buf, &uiov32->iov_base)) return -EFAULT; if (len > INT_MAX - tot_len) len = INT_MAX - tot_len; tot_len += len; kiov->iov_base = compat_ptr(buf); kiov->iov_len = (__kernel_size_t) len; uiov32++; kiov++; niov--; } return tot_len; } int get_compat_msghdr(struct msghdr *kmsg, struct compat_msghdr __user *umsg) { compat_uptr_t tmp1, tmp2, tmp3; if (!access_ok(VERIFY_READ, umsg, sizeof(*umsg)) || __get_user(tmp1, &umsg->msg_name) || __get_user(kmsg->msg_namelen, &umsg->msg_namelen) || __get_user(tmp2, &umsg->msg_iov) || __get_user(kmsg->msg_iovlen, &umsg->msg_iovlen) || __get_user(tmp3, &umsg->msg_control) || __get_user(kmsg->msg_controllen, &umsg->msg_controllen) || __get_user(kmsg->msg_flags, &umsg->msg_flags)) return -EFAULT; if (kmsg->msg_namelen > sizeof(struct sockaddr_storage)) return -EINVAL; kmsg->msg_name = compat_ptr(tmp1); kmsg->msg_iov = compat_ptr(tmp2); kmsg->msg_control = compat_ptr(tmp3); return 0; } /* I've named the args so it is easy to tell whose space the pointers are in. */ int verify_compat_iovec(struct msghdr *kern_msg, struct iovec *kern_iov, struct sockaddr_storage *kern_address, int mode) { int tot_len; if (kern_msg->msg_namelen) { if (mode == VERIFY_READ) { int err = move_addr_to_kernel(kern_msg->msg_name, kern_msg->msg_namelen, kern_address); if (err < 0) return err; } kern_msg->msg_name = kern_address; } else kern_msg->msg_name = NULL; tot_len = iov_from_user_compat_to_kern(kern_iov, (struct compat_iovec __user *)kern_msg->msg_iov, kern_msg->msg_iovlen); if (tot_len >= 0) kern_msg->msg_iov = kern_iov; return tot_len; } /* Bleech... */ #define CMSG_COMPAT_ALIGN(len) ALIGN((len), sizeof(s32)) #define CMSG_COMPAT_DATA(cmsg) \ ((void __user *)((char __user *)(cmsg) + CMSG_COMPAT_ALIGN(sizeof(struct compat_cmsghdr)))) #define CMSG_COMPAT_SPACE(len) \ (CMSG_COMPAT_ALIGN(sizeof(struct compat_cmsghdr)) + CMSG_COMPAT_ALIGN(len)) #define CMSG_COMPAT_LEN(len) \ (CMSG_COMPAT_ALIGN(sizeof(struct compat_cmsghdr)) + (len)) #define CMSG_COMPAT_FIRSTHDR(msg) \ (((msg)->msg_controllen) >= sizeof(struct compat_cmsghdr) ? \ (struct compat_cmsghdr __user *)((msg)->msg_control) : \ (struct compat_cmsghdr __user *)NULL) #define CMSG_COMPAT_OK(ucmlen, ucmsg, mhdr) \ ((ucmlen) >= sizeof(struct compat_cmsghdr) && \ (ucmlen) <= (unsigned long) \ ((mhdr)->msg_controllen - \ ((char *)(ucmsg) - (char *)(mhdr)->msg_control))) static inline struct compat_cmsghdr __user *cmsg_compat_nxthdr(struct msghdr *msg, struct compat_cmsghdr __user *cmsg, int cmsg_len) { char __user *ptr = (char __user *)cmsg + CMSG_COMPAT_ALIGN(cmsg_len); if ((unsigned long)(ptr + 1 - (char __user *)msg->msg_control) > msg->msg_controllen) return NULL; return (struct compat_cmsghdr __user *)ptr; } /* There is a lot of hair here because the alignment rules (and * thus placement) of cmsg headers and length are different for * 32-bit apps. -DaveM */ int cmsghdr_from_user_compat_to_kern(struct msghdr *kmsg, struct sock *sk, unsigned char *stackbuf, int stackbuf_size) { struct compat_cmsghdr __user *ucmsg; struct cmsghdr *kcmsg, *kcmsg_base; compat_size_t ucmlen; __kernel_size_t kcmlen, tmp; int err = -EFAULT; kcmlen = 0; kcmsg_base = kcmsg = (struct cmsghdr *)stackbuf; ucmsg = CMSG_COMPAT_FIRSTHDR(kmsg); while (ucmsg != NULL) { if (get_user(ucmlen, &ucmsg->cmsg_len)) return -EFAULT; /* Catch bogons. */ if (!CMSG_COMPAT_OK(ucmlen, ucmsg, kmsg)) return -EINVAL; tmp = ((ucmlen - CMSG_COMPAT_ALIGN(sizeof(*ucmsg))) + CMSG_ALIGN(sizeof(struct cmsghdr))); tmp = CMSG_ALIGN(tmp); kcmlen += tmp; ucmsg = cmsg_compat_nxthdr(kmsg, ucmsg, ucmlen); } if (kcmlen == 0) return -EINVAL; /* The kcmlen holds the 64-bit version of the control length. * It may not be modified as we do not stick it into the kmsg * until we have successfully copied over all of the data * from the user. */ if (kcmlen > stackbuf_size) kcmsg_base = kcmsg = sock_kmalloc(sk, kcmlen, GFP_KERNEL); if (kcmsg == NULL) return -ENOBUFS; /* Now copy them over neatly. */ memset(kcmsg, 0, kcmlen); ucmsg = CMSG_COMPAT_FIRSTHDR(kmsg); while (ucmsg != NULL) { if (__get_user(ucmlen, &ucmsg->cmsg_len)) goto Efault; if (!CMSG_COMPAT_OK(ucmlen, ucmsg, kmsg)) goto Einval; tmp = ((ucmlen - CMSG_COMPAT_ALIGN(sizeof(*ucmsg))) + CMSG_ALIGN(sizeof(struct cmsghdr))); if ((char *)kcmsg_base + kcmlen - (char *)kcmsg < CMSG_ALIGN(tmp)) goto Einval; kcmsg->cmsg_len = tmp; tmp = CMSG_ALIGN(tmp); if (__get_user(kcmsg->cmsg_level, &ucmsg->cmsg_level) || __get_user(kcmsg->cmsg_type, &ucmsg->cmsg_type) || copy_from_user(CMSG_DATA(kcmsg), CMSG_COMPAT_DATA(ucmsg), (ucmlen - CMSG_COMPAT_ALIGN(sizeof(*ucmsg))))) goto Efault; /* Advance. */ kcmsg = (struct cmsghdr *)((char *)kcmsg + tmp); ucmsg = cmsg_compat_nxthdr(kmsg, ucmsg, ucmlen); } /* Ok, looks like we made it. Hook it up and return success. */ kmsg->msg_control = kcmsg_base; kmsg->msg_controllen = kcmlen; return 0; Einval: err = -EINVAL; Efault: if (kcmsg_base != (struct cmsghdr *)stackbuf) sock_kfree_s(sk, kcmsg_base, kcmlen); return err; } int put_cmsg_compat(struct msghdr *kmsg, int level, int type, int len, void *data) { struct compat_cmsghdr __user *cm = (struct compat_cmsghdr __user *) kmsg->msg_control; struct compat_cmsghdr cmhdr; struct compat_timeval ctv; struct compat_timespec cts[3]; int cmlen; if (cm == NULL || kmsg->msg_controllen < sizeof(*cm)) { kmsg->msg_flags |= MSG_CTRUNC; return 0; /* XXX: return error? check spec. */ } if (!COMPAT_USE_64BIT_TIME) { if (level == SOL_SOCKET && type == SCM_TIMESTAMP) { struct timeval *tv = (struct timeval *)data; ctv.tv_sec = tv->tv_sec; ctv.tv_usec = tv->tv_usec; data = &ctv; len = sizeof(ctv); } if (level == SOL_SOCKET && (type == SCM_TIMESTAMPNS || type == SCM_TIMESTAMPING)) { int count = type == SCM_TIMESTAMPNS ? 1 : 3; int i; struct timespec *ts = (struct timespec *)data; for (i = 0; i < count; i++) { cts[i].tv_sec = ts[i].tv_sec; cts[i].tv_nsec = ts[i].tv_nsec; } data = &cts; len = sizeof(cts[0]) * count; } } cmlen = CMSG_COMPAT_LEN(len); if (kmsg->msg_controllen < cmlen) { kmsg->msg_flags |= MSG_CTRUNC; cmlen = kmsg->msg_controllen; } cmhdr.cmsg_level = level; cmhdr.cmsg_type = type; cmhdr.cmsg_len = cmlen; if (copy_to_user(cm, &cmhdr, sizeof cmhdr)) return -EFAULT; if (copy_to_user(CMSG_COMPAT_DATA(cm), data, cmlen - sizeof(struct compat_cmsghdr))) return -EFAULT; cmlen = CMSG_COMPAT_SPACE(len); if (kmsg->msg_controllen < cmlen) cmlen = kmsg->msg_controllen; kmsg->msg_control += cmlen; kmsg->msg_controllen -= cmlen; return 0; } void scm_detach_fds_compat(struct msghdr *kmsg, struct scm_cookie *scm) { struct compat_cmsghdr __user *cm = (struct compat_cmsghdr __user *) kmsg->msg_control; int fdmax = (kmsg->msg_controllen - sizeof(struct compat_cmsghdr)) / sizeof(int); int fdnum = scm->fp->count; struct file **fp = scm->fp->fp; int __user *cmfptr; int err = 0, i; if (fdnum < fdmax) fdmax = fdnum; for (i = 0, cmfptr = (int __user *) CMSG_COMPAT_DATA(cm); i < fdmax; i++, cmfptr++) { int new_fd; err = security_file_receive(fp[i]); if (err) break; err = get_unused_fd_flags(MSG_CMSG_CLOEXEC & kmsg->msg_flags ? O_CLOEXEC : 0); if (err < 0) break; new_fd = err; err = put_user(new_fd, cmfptr); if (err) { put_unused_fd(new_fd); break; } /* Bump the usage count and install the file. */ fd_install(new_fd, get_file(fp[i])); } if (i > 0) { int cmlen = CMSG_COMPAT_LEN(i * sizeof(int)); err = put_user(SOL_SOCKET, &cm->cmsg_level); if (!err) err = put_user(SCM_RIGHTS, &cm->cmsg_type); if (!err) err = put_user(cmlen, &cm->cmsg_len); if (!err) { cmlen = CMSG_COMPAT_SPACE(i * sizeof(int)); kmsg->msg_control += cmlen; kmsg->msg_controllen -= cmlen; } } if (i < fdnum) kmsg->msg_flags |= MSG_CTRUNC; /* * All of the files that fit in the message have had their * usage counts incremented, so we just free the list. */ __scm_destroy(scm); } static int do_set_attach_filter(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen) { struct compat_sock_fprog __user *fprog32 = (struct compat_sock_fprog __user *)optval; struct sock_fprog __user *kfprog = compat_alloc_user_space(sizeof(struct sock_fprog)); compat_uptr_t ptr; u16 len; if (!access_ok(VERIFY_READ, fprog32, sizeof(*fprog32)) || !access_ok(VERIFY_WRITE, kfprog, sizeof(struct sock_fprog)) || __get_user(len, &fprog32->len) || __get_user(ptr, &fprog32->filter) || __put_user(len, &kfprog->len) || __put_user(compat_ptr(ptr), &kfprog->filter)) return -EFAULT; return sock_setsockopt(sock, level, optname, (char __user *)kfprog, sizeof(struct sock_fprog)); } static int do_set_sock_timeout(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen) { struct compat_timeval __user *up = (struct compat_timeval __user *)optval; struct timeval ktime; mm_segment_t old_fs; int err; if (optlen < sizeof(*up)) return -EINVAL; if (!access_ok(VERIFY_READ, up, sizeof(*up)) || __get_user(ktime.tv_sec, &up->tv_sec) || __get_user(ktime.tv_usec, &up->tv_usec)) return -EFAULT; old_fs = get_fs(); set_fs(KERNEL_DS); err = sock_setsockopt(sock, level, optname, (char *)&ktime, sizeof(ktime)); set_fs(old_fs); return err; } static int compat_sock_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen) { if (optname == SO_ATTACH_FILTER) return do_set_attach_filter(sock, level, optname, optval, optlen); if (optname == SO_RCVTIMEO || optname == SO_SNDTIMEO) return do_set_sock_timeout(sock, level, optname, optval, optlen); return sock_setsockopt(sock, level, optname, optval, optlen); } asmlinkage long compat_sys_setsockopt(int fd, int level, int optname, char __user *optval, unsigned int optlen) { int err; struct socket *sock = sockfd_lookup(fd, &err); if (sock) { err = security_socket_setsockopt(sock, level, optname); if (err) { sockfd_put(sock); return err; } if (level == SOL_SOCKET) err = compat_sock_setsockopt(sock, level, optname, optval, optlen); else if (sock->ops->compat_setsockopt) err = sock->ops->compat_setsockopt(sock, level, optname, optval, optlen); else err = sock->ops->setsockopt(sock, level, optname, optval, optlen); sockfd_put(sock); } return err; } static int do_get_sock_timeout(struct socket *sock, int level, int optname, char __user *optval, int __user *optlen) { struct compat_timeval __user *up; struct timeval ktime; mm_segment_t old_fs; int len, err; up = (struct compat_timeval __user *) optval; if (get_user(len, optlen)) return -EFAULT; if (len < sizeof(*up)) return -EINVAL; len = sizeof(ktime); old_fs = get_fs(); set_fs(KERNEL_DS); err = sock_getsockopt(sock, level, optname, (char *) &ktime, &len); set_fs(old_fs); if (!err) { if (put_user(sizeof(*up), optlen) || !access_ok(VERIFY_WRITE, up, sizeof(*up)) || __put_user(ktime.tv_sec, &up->tv_sec) || __put_user(ktime.tv_usec, &up->tv_usec)) err = -EFAULT; } return err; } static int compat_sock_getsockopt(struct socket *sock, int level, int optname, char __user *optval, int __user *optlen) { if (optname == SO_RCVTIMEO || optname == SO_SNDTIMEO) return do_get_sock_timeout(sock, level, optname, optval, optlen); return sock_getsockopt(sock, level, optname, optval, optlen); } int compat_sock_get_timestamp(struct sock *sk, struct timeval __user *userstamp) { struct compat_timeval __user *ctv; int err; struct timeval tv; if (COMPAT_USE_64BIT_TIME) return sock_get_timestamp(sk, userstamp); ctv = (struct compat_timeval __user *) userstamp; err = -ENOENT; if (!sock_flag(sk, SOCK_TIMESTAMP)) sock_enable_timestamp(sk, SOCK_TIMESTAMP); tv = ktime_to_timeval(sk->sk_stamp); if (tv.tv_sec == -1) return err; if (tv.tv_sec == 0) { sk->sk_stamp = ktime_get_real(); tv = ktime_to_timeval(sk->sk_stamp); } err = 0; if (put_user(tv.tv_sec, &ctv->tv_sec) || put_user(tv.tv_usec, &ctv->tv_usec)) err = -EFAULT; return err; } EXPORT_SYMBOL(compat_sock_get_timestamp); int compat_sock_get_timestampns(struct sock *sk, struct timespec __user *userstamp) { struct compat_timespec __user *ctv; int err; struct timespec ts; if (COMPAT_USE_64BIT_TIME) return sock_get_timestampns (sk, userstamp); ctv = (struct compat_timespec __user *) userstamp; err = -ENOENT; if (!sock_flag(sk, SOCK_TIMESTAMP)) sock_enable_timestamp(sk, SOCK_TIMESTAMP); ts = ktime_to_timespec(sk->sk_stamp); if (ts.tv_sec == -1) return err; if (ts.tv_sec == 0) { sk->sk_stamp = ktime_get_real(); ts = ktime_to_timespec(sk->sk_stamp); } err = 0; if (put_user(ts.tv_sec, &ctv->tv_sec) || put_user(ts.tv_nsec, &ctv->tv_nsec)) err = -EFAULT; return err; } EXPORT_SYMBOL(compat_sock_get_timestampns); asmlinkage long compat_sys_getsockopt(int fd, int level, int optname, char __user *optval, int __user *optlen) { int err; struct socket *sock = sockfd_lookup(fd, &err); if (sock) { err = security_socket_getsockopt(sock, level, optname); if (err) { sockfd_put(sock); return err; } if (level == SOL_SOCKET) err = compat_sock_getsockopt(sock, level, optname, optval, optlen); else if (sock->ops->compat_getsockopt) err = sock->ops->compat_getsockopt(sock, level, optname, optval, optlen); else err = sock->ops->getsockopt(sock, level, optname, optval, optlen); sockfd_put(sock); } return err; } struct compat_group_req { __u32 gr_interface; struct __kernel_sockaddr_storage gr_group __attribute__ ((aligned(4))); } __packed; struct compat_group_source_req { __u32 gsr_interface; struct __kernel_sockaddr_storage gsr_group __attribute__ ((aligned(4))); struct __kernel_sockaddr_storage gsr_source __attribute__ ((aligned(4))); } __packed; struct compat_group_filter { __u32 gf_interface; struct __kernel_sockaddr_storage gf_group __attribute__ ((aligned(4))); __u32 gf_fmode; __u32 gf_numsrc; struct __kernel_sockaddr_storage gf_slist[1] __attribute__ ((aligned(4))); } __packed; #define __COMPAT_GF0_SIZE (sizeof(struct compat_group_filter) - \ sizeof(struct __kernel_sockaddr_storage)) int compat_mc_setsockopt(struct sock *sock, int level, int optname, char __user *optval, unsigned int optlen, int (*setsockopt)(struct sock *, int, int, char __user *, unsigned int)) { char __user *koptval = optval; int koptlen = optlen; switch (optname) { case MCAST_JOIN_GROUP: case MCAST_LEAVE_GROUP: { struct compat_group_req __user *gr32 = (void *)optval; struct group_req __user *kgr = compat_alloc_user_space(sizeof(struct group_req)); u32 interface; if (!access_ok(VERIFY_READ, gr32, sizeof(*gr32)) || !access_ok(VERIFY_WRITE, kgr, sizeof(struct group_req)) || __get_user(interface, &gr32->gr_interface) || __put_user(interface, &kgr->gr_interface) || copy_in_user(&kgr->gr_group, &gr32->gr_group, sizeof(kgr->gr_group))) return -EFAULT; koptval = (char __user *)kgr; koptlen = sizeof(struct group_req); break; } case MCAST_JOIN_SOURCE_GROUP: case MCAST_LEAVE_SOURCE_GROUP: case MCAST_BLOCK_SOURCE: case MCAST_UNBLOCK_SOURCE: { struct compat_group_source_req __user *gsr32 = (void *)optval; struct group_source_req __user *kgsr = compat_alloc_user_space( sizeof(struct group_source_req)); u32 interface; if (!access_ok(VERIFY_READ, gsr32, sizeof(*gsr32)) || !access_ok(VERIFY_WRITE, kgsr, sizeof(struct group_source_req)) || __get_user(interface, &gsr32->gsr_interface) || __put_user(interface, &kgsr->gsr_interface) || copy_in_user(&kgsr->gsr_group, &gsr32->gsr_group, sizeof(kgsr->gsr_group)) || copy_in_user(&kgsr->gsr_source, &gsr32->gsr_source, sizeof(kgsr->gsr_source))) return -EFAULT; koptval = (char __user *)kgsr; koptlen = sizeof(struct group_source_req); break; } case MCAST_MSFILTER: { struct compat_group_filter __user *gf32 = (void *)optval; struct group_filter __user *kgf; u32 interface, fmode, numsrc; if (!access_ok(VERIFY_READ, gf32, __COMPAT_GF0_SIZE) || __get_user(interface, &gf32->gf_interface) || __get_user(fmode, &gf32->gf_fmode) || __get_user(numsrc, &gf32->gf_numsrc)) return -EFAULT; koptlen = optlen + sizeof(struct group_filter) - sizeof(struct compat_group_filter); if (koptlen < GROUP_FILTER_SIZE(numsrc)) return -EINVAL; kgf = compat_alloc_user_space(koptlen); if (!access_ok(VERIFY_WRITE, kgf, koptlen) || __put_user(interface, &kgf->gf_interface) || __put_user(fmode, &kgf->gf_fmode) || __put_user(numsrc, &kgf->gf_numsrc) || copy_in_user(&kgf->gf_group, &gf32->gf_group, sizeof(kgf->gf_group)) || (numsrc && copy_in_user(kgf->gf_slist, gf32->gf_slist, numsrc * sizeof(kgf->gf_slist[0])))) return -EFAULT; koptval = (char __user *)kgf; break; } default: break; } return setsockopt(sock, level, optname, koptval, koptlen); } EXPORT_SYMBOL(compat_mc_setsockopt); int compat_mc_getsockopt(struct sock *sock, int level, int optname, char __user *optval, int __user *optlen, int (*getsockopt)(struct sock *, int, int, char __user *, int __user *)) { struct compat_group_filter __user *gf32 = (void *)optval; struct group_filter __user *kgf; int __user *koptlen; u32 interface, fmode, numsrc; int klen, ulen, err; if (optname != MCAST_MSFILTER) return getsockopt(sock, level, optname, optval, optlen); koptlen = compat_alloc_user_space(sizeof(*koptlen)); if (!access_ok(VERIFY_READ, optlen, sizeof(*optlen)) || __get_user(ulen, optlen)) return -EFAULT; /* adjust len for pad */ klen = ulen + sizeof(*kgf) - sizeof(*gf32); if (klen < GROUP_FILTER_SIZE(0)) return -EINVAL; if (!access_ok(VERIFY_WRITE, koptlen, sizeof(*koptlen)) || __put_user(klen, koptlen)) return -EFAULT; /* have to allow space for previous compat_alloc_user_space, too */ kgf = compat_alloc_user_space(klen+sizeof(*optlen)); if (!access_ok(VERIFY_READ, gf32, __COMPAT_GF0_SIZE) || __get_user(interface, &gf32->gf_interface) || __get_user(fmode, &gf32->gf_fmode) || __get_user(numsrc, &gf32->gf_numsrc) || __put_user(interface, &kgf->gf_interface) || __put_user(fmode, &kgf->gf_fmode) || __put_user(numsrc, &kgf->gf_numsrc) || copy_in_user(&kgf->gf_group, &gf32->gf_group, sizeof(kgf->gf_group))) return -EFAULT; err = getsockopt(sock, level, optname, (char __user *)kgf, koptlen); if (err) return err; if (!access_ok(VERIFY_READ, koptlen, sizeof(*koptlen)) || __get_user(klen, koptlen)) return -EFAULT; ulen = klen - (sizeof(*kgf)-sizeof(*gf32)); if (!access_ok(VERIFY_WRITE, optlen, sizeof(*optlen)) || __put_user(ulen, optlen)) return -EFAULT; if (!access_ok(VERIFY_READ, kgf, klen) || !access_ok(VERIFY_WRITE, gf32, ulen) || __get_user(interface, &kgf->gf_interface) || __get_user(fmode, &kgf->gf_fmode) || __get_user(numsrc, &kgf->gf_numsrc) || __put_user(interface, &gf32->gf_interface) || __put_user(fmode, &gf32->gf_fmode) || __put_user(numsrc, &gf32->gf_numsrc)) return -EFAULT; if (numsrc) { int copylen; klen -= GROUP_FILTER_SIZE(0); copylen = numsrc * sizeof(gf32->gf_slist[0]); if (copylen > klen) copylen = klen; if (copy_in_user(gf32->gf_slist, kgf->gf_slist, copylen)) return -EFAULT; } return err; } EXPORT_SYMBOL(compat_mc_getsockopt); /* Argument list sizes for compat_sys_socketcall */ #define AL(x) ((x) * sizeof(u32)) static unsigned char nas[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 asmlinkage long compat_sys_sendmsg(int fd, struct compat_msghdr __user *msg, unsigned int flags) { if (flags & MSG_CMSG_COMPAT) return -EINVAL; return __sys_sendmsg(fd, (struct msghdr __user *)msg, flags | MSG_CMSG_COMPAT); } asmlinkage long compat_sys_sendmmsg(int fd, struct compat_mmsghdr __user *mmsg, unsigned int vlen, unsigned int flags) { if (flags & MSG_CMSG_COMPAT) return -EINVAL; return __sys_sendmmsg(fd, (struct mmsghdr __user *)mmsg, vlen, flags | MSG_CMSG_COMPAT); } asmlinkage long compat_sys_recvmsg(int fd, struct compat_msghdr __user *msg, unsigned int flags) { if (flags & MSG_CMSG_COMPAT) return -EINVAL; return __sys_recvmsg(fd, (struct msghdr __user *)msg, flags | MSG_CMSG_COMPAT); } asmlinkage long compat_sys_recv(int fd, void __user *buf, size_t len, unsigned int flags) { return sys_recv(fd, buf, len, flags | MSG_CMSG_COMPAT); } asmlinkage long compat_sys_recvfrom(int fd, void __user *buf, size_t len, unsigned int flags, struct sockaddr __user *addr, int __user *addrlen) { return sys_recvfrom(fd, buf, len, flags | MSG_CMSG_COMPAT, addr, addrlen); } asmlinkage long compat_sys_recvmmsg(int fd, struct compat_mmsghdr __user *mmsg, unsigned int vlen, unsigned int flags, struct compat_timespec __user *timeout) { int datagrams; struct timespec ktspec; if (flags & MSG_CMSG_COMPAT) return -EINVAL; if (COMPAT_USE_64BIT_TIME) return __sys_recvmmsg(fd, (struct mmsghdr __user *)mmsg, vlen, flags | MSG_CMSG_COMPAT, (struct timespec *) timeout); if (timeout == NULL) return __sys_recvmmsg(fd, (struct mmsghdr __user *)mmsg, vlen, flags | MSG_CMSG_COMPAT, NULL); if (get_compat_timespec(&ktspec, timeout)) return -EFAULT; datagrams = __sys_recvmmsg(fd, (struct mmsghdr __user *)mmsg, vlen, flags | MSG_CMSG_COMPAT, &ktspec); if (datagrams > 0 && put_compat_timespec(&ktspec, timeout)) datagrams = -EFAULT; return datagrams; } asmlinkage long compat_sys_socketcall(int call, u32 __user *args) { int ret; u32 a[6]; u32 a0, a1; if (call < SYS_SOCKET || call > SYS_SENDMMSG) return -EINVAL; if (copy_from_user(a, args, nas[call])) return -EFAULT; a0 = a[0]; a1 = a[1]; switch (call) { case SYS_SOCKET: ret = sys_socket(a0, a1, a[2]); break; case SYS_BIND: ret = sys_bind(a0, compat_ptr(a1), a[2]); break; case SYS_CONNECT: ret = sys_connect(a0, compat_ptr(a1), a[2]); break; case SYS_LISTEN: ret = sys_listen(a0, a1); break; case SYS_ACCEPT: ret = sys_accept4(a0, compat_ptr(a1), compat_ptr(a[2]), 0); break; case SYS_GETSOCKNAME: ret = sys_getsockname(a0, compat_ptr(a1), compat_ptr(a[2])); break; case SYS_GETPEERNAME: ret = sys_getpeername(a0, compat_ptr(a1), compat_ptr(a[2])); break; case SYS_SOCKETPAIR: ret = sys_socketpair(a0, a1, a[2], compat_ptr(a[3])); break; case SYS_SEND: ret = sys_send(a0, compat_ptr(a1), a[2], a[3]); break; case SYS_SENDTO: ret = sys_sendto(a0, compat_ptr(a1), a[2], a[3], compat_ptr(a[4]), a[5]); break; case SYS_RECV: ret = compat_sys_recv(a0, compat_ptr(a1), a[2], a[3]); break; case SYS_RECVFROM: ret = compat_sys_recvfrom(a0, compat_ptr(a1), a[2], a[3], compat_ptr(a[4]), compat_ptr(a[5])); break; case SYS_SHUTDOWN: ret = sys_shutdown(a0, a1); break; case SYS_SETSOCKOPT: ret = compat_sys_setsockopt(a0, a1, a[2], compat_ptr(a[3]), a[4]); break; case SYS_GETSOCKOPT: ret = compat_sys_getsockopt(a0, a1, a[2], compat_ptr(a[3]), compat_ptr(a[4])); break; case SYS_SENDMSG: ret = compat_sys_sendmsg(a0, compat_ptr(a1), a[2]); break; case SYS_SENDMMSG: ret = compat_sys_sendmmsg(a0, compat_ptr(a1), a[2], a[3]); break; case SYS_RECVMSG: ret = compat_sys_recvmsg(a0, compat_ptr(a1), a[2]); break; case SYS_RECVMMSG: ret = compat_sys_recvmmsg(a0, compat_ptr(a1), a[2], a[3], compat_ptr(a[4])); break; case SYS_ACCEPT4: ret = sys_accept4(a0, compat_ptr(a1), compat_ptr(a[2]), a[3]); break; default: ret = -EINVAL; break; } return ret; }
./CrossVul/dataset_final_sorted/CWE-20/c/bad_5845_13
crossvul-cpp_data_good_5184_0
#include <stdio.h> #include <stdlib.h> #include "gd.h" #include "gdtest.h" int main() { gdImagePtr im, exp; int error = 0; im = gdImageCreate(50, 50); if (!im) { gdTestErrorMsg("gdImageCreate failed.\n"); return 1; } gdImageCropThreshold(im, 1337, 0); gdImageDestroy(im); /* this bug tests a crash, it never reaches this point if the bug exists*/ return 0; }
./CrossVul/dataset_final_sorted/CWE-20/c/good_5184_0
crossvul-cpp_data_bad_2891_13
/* user_defined.c: user defined key type * * Copyright (C) 2004 Red Hat, Inc. All Rights Reserved. * Written by David Howells (dhowells@redhat.com) * * 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/module.h> #include <linux/init.h> #include <linux/slab.h> #include <linux/seq_file.h> #include <linux/err.h> #include <keys/user-type.h> #include <linux/uaccess.h> #include "internal.h" static int logon_vet_description(const char *desc); /* * user defined keys take an arbitrary string as the description and an * arbitrary blob of data as the payload */ struct key_type key_type_user = { .name = "user", .preparse = user_preparse, .free_preparse = user_free_preparse, .instantiate = generic_key_instantiate, .update = user_update, .revoke = user_revoke, .destroy = user_destroy, .describe = user_describe, .read = user_read, }; EXPORT_SYMBOL_GPL(key_type_user); /* * This key type is essentially the same as key_type_user, but it does * not define a .read op. This is suitable for storing username and * password pairs in the keyring that you do not want to be readable * from userspace. */ struct key_type key_type_logon = { .name = "logon", .preparse = user_preparse, .free_preparse = user_free_preparse, .instantiate = generic_key_instantiate, .update = user_update, .revoke = user_revoke, .destroy = user_destroy, .describe = user_describe, .vet_description = logon_vet_description, }; EXPORT_SYMBOL_GPL(key_type_logon); /* * Preparse a user defined key payload */ int user_preparse(struct key_preparsed_payload *prep) { struct user_key_payload *upayload; size_t datalen = prep->datalen; if (datalen <= 0 || datalen > 32767 || !prep->data) return -EINVAL; upayload = kmalloc(sizeof(*upayload) + datalen, GFP_KERNEL); if (!upayload) return -ENOMEM; /* attach the data */ prep->quotalen = datalen; prep->payload.data[0] = upayload; upayload->datalen = datalen; memcpy(upayload->data, prep->data, datalen); return 0; } EXPORT_SYMBOL_GPL(user_preparse); /* * Free a preparse of a user defined key payload */ void user_free_preparse(struct key_preparsed_payload *prep) { kzfree(prep->payload.data[0]); } EXPORT_SYMBOL_GPL(user_free_preparse); static void user_free_payload_rcu(struct rcu_head *head) { struct user_key_payload *payload; payload = container_of(head, struct user_key_payload, rcu); kzfree(payload); } /* * update a user defined key * - the key's semaphore is write-locked */ int user_update(struct key *key, struct key_preparsed_payload *prep) { struct user_key_payload *zap = NULL; int ret; /* check the quota and attach the new data */ ret = key_payload_reserve(key, prep->datalen); if (ret < 0) return ret; /* attach the new data, displacing the old */ key->expiry = prep->expiry; if (!test_bit(KEY_FLAG_NEGATIVE, &key->flags)) zap = dereference_key_locked(key); rcu_assign_keypointer(key, prep->payload.data[0]); prep->payload.data[0] = NULL; if (zap) call_rcu(&zap->rcu, user_free_payload_rcu); return ret; } EXPORT_SYMBOL_GPL(user_update); /* * dispose of the links from a revoked keyring * - called with the key sem write-locked */ void user_revoke(struct key *key) { struct user_key_payload *upayload = user_key_payload_locked(key); /* clear the quota */ key_payload_reserve(key, 0); if (upayload) { rcu_assign_keypointer(key, NULL); call_rcu(&upayload->rcu, user_free_payload_rcu); } } EXPORT_SYMBOL(user_revoke); /* * dispose of the data dangling from the corpse of a user key */ void user_destroy(struct key *key) { struct user_key_payload *upayload = key->payload.data[0]; kzfree(upayload); } EXPORT_SYMBOL_GPL(user_destroy); /* * describe the user key */ void user_describe(const struct key *key, struct seq_file *m) { seq_puts(m, key->description); if (key_is_instantiated(key)) seq_printf(m, ": %u", key->datalen); } EXPORT_SYMBOL_GPL(user_describe); /* * read the key data * - the key's semaphore is read-locked */ long user_read(const struct key *key, char __user *buffer, size_t buflen) { const struct user_key_payload *upayload; long ret; upayload = user_key_payload_locked(key); ret = upayload->datalen; /* we can return the data as is */ if (buffer && buflen > 0) { if (buflen > upayload->datalen) buflen = upayload->datalen; if (copy_to_user(buffer, upayload->data, buflen) != 0) ret = -EFAULT; } return ret; } EXPORT_SYMBOL_GPL(user_read); /* Vet the description for a "logon" key */ static int logon_vet_description(const char *desc) { char *p; /* require a "qualified" description string */ p = strchr(desc, ':'); if (!p) return -EINVAL; /* also reject description with ':' as first char */ if (p == desc) return -EINVAL; return 0; }
./CrossVul/dataset_final_sorted/CWE-20/c/bad_2891_13
crossvul-cpp_data_bad_2253_1
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* Monkey HTTP Server * ================== * Copyright 2001-2014 Monkey Software LLC <eduardo@monkey.io> * * 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 <stdio.h> #include <stdlib.h> #include <limits.h> #include <sys/stat.h> #include <unistd.h> #include <string.h> #include <sys/socket.h> #include <sys/time.h> #include <sys/ioctl.h> #include <time.h> #include <netdb.h> #include <sys/wait.h> #include <signal.h> #include <ctype.h> #include <errno.h> #include <arpa/inet.h> #include <netinet/in.h> #include <sys/types.h> #include <fcntl.h> #include <monkey/monkey.h> #include <monkey/mk_request.h> #include <monkey/mk_http.h> #include <monkey/mk_http_status.h> #include <monkey/mk_string.h> #include <monkey/mk_config.h> #include <monkey/mk_scheduler.h> #include <monkey/mk_epoll.h> #include <monkey/mk_utils.h> #include <monkey/mk_header.h> #include <monkey/mk_user.h> #include <monkey/mk_method.h> #include <monkey/mk_memory.h> #include <monkey/mk_socket.h> #include <monkey/mk_cache.h> #include <monkey/mk_clock.h> #include <monkey/mk_plugin.h> #include <monkey/mk_macros.h> #include <monkey/mk_vhost.h> #include <monkey/mk_server.h> const mk_ptr_t mk_crlf = mk_ptr_init(MK_CRLF); const mk_ptr_t mk_endblock = mk_ptr_init(MK_ENDBLOCK); const mk_ptr_t mk_rh_accept = mk_ptr_init(RH_ACCEPT); const mk_ptr_t mk_rh_accept_charset = mk_ptr_init(RH_ACCEPT_CHARSET); const mk_ptr_t mk_rh_accept_encoding = mk_ptr_init(RH_ACCEPT_ENCODING); const mk_ptr_t mk_rh_accept_language = mk_ptr_init(RH_ACCEPT_LANGUAGE); const mk_ptr_t mk_rh_connection = mk_ptr_init(RH_CONNECTION); const mk_ptr_t mk_rh_cookie = mk_ptr_init(RH_COOKIE); const mk_ptr_t mk_rh_content_length = mk_ptr_init(RH_CONTENT_LENGTH); const mk_ptr_t mk_rh_content_range = mk_ptr_init(RH_CONTENT_RANGE); const mk_ptr_t mk_rh_content_type = mk_ptr_init(RH_CONTENT_TYPE); const mk_ptr_t mk_rh_if_modified_since = mk_ptr_init(RH_IF_MODIFIED_SINCE); const mk_ptr_t mk_rh_host = mk_ptr_init(RH_HOST); const mk_ptr_t mk_rh_last_modified = mk_ptr_init(RH_LAST_MODIFIED); const mk_ptr_t mk_rh_last_modified_since = mk_ptr_init(RH_LAST_MODIFIED_SINCE); const mk_ptr_t mk_rh_referer = mk_ptr_init(RH_REFERER); const mk_ptr_t mk_rh_range = mk_ptr_init(RH_RANGE); const mk_ptr_t mk_rh_user_agent = mk_ptr_init(RH_USER_AGENT); pthread_key_t request_list; /* Create a memory allocation in order to handle the request data */ static inline void mk_request_init(struct session_request *request) { request->status = MK_TRUE; request->method = MK_HTTP_METHOD_UNKNOWN; request->file_info.size = -1; request->bytes_to_send = -1; request->fd_file = -1; /* Response Headers */ mk_header_response_reset(&request->headers); } void mk_request_free(struct session_request *sr) { if (sr->fd_file > 0) { mk_vhost_close(sr); } if (sr->headers.location) { mk_mem_free(sr->headers.location); } if (sr->uri_processed.data != sr->uri.data) { mk_ptr_free(&sr->uri_processed); } if (sr->real_path.data != sr->real_path_static) { mk_ptr_free(&sr->real_path); } } int mk_request_header_toc_parse(struct headers_toc *toc, const char *data, int len) { int i = 0; int header_len; int colon; char *q; char *p = (char *) data; char *l = p; toc->length = 0; for (i = 0; l < (data + len) && p && i < MK_HEADERS_TOC_LEN; i++) { if (*p == '\r') goto out; /* Locate the colon character and the end of the line by CRLF */ colon = -1; for (q = p; *q != 0x0D; ++q) { if (*q == ':' && colon == -1) { colon = (q - p); } } /* it must be a LF after CR */ if (*(q + 1) != 0x0A) { return -1; } /* * Check if we reach the last header, take in count the first one can * be also the last. */ if (data + len == (q - 1) && colon == -1) { break; } /* * By this version we force that after the colon must exists a white * space before the value field */ if (*(p + colon + 1) != 0x20) { return -1; } /* Each header key must have a value */ header_len = q - p - colon - 2; if (header_len == 0) { return -1; } /* Register the entry */ toc->rows[i].init = p; toc->rows[i].end = q; toc->rows[i].status = 0; p = (q + mk_crlf.len); l = p; toc->length++; } out: return toc->length; } /* Return a struct with method, URI , protocol version and all static headers defined here sent in request */ static int mk_request_header_process(struct session_request *sr) { int uri_init = 0, uri_end = 0; int query_init = 0; int prot_init = 0, prot_end = 0, pos_sep = 0; int fh_limit; char *headers; char *temp = 0; mk_ptr_t host; /* Method */ sr->method_p = mk_http_method_check_str(sr->method); /* Request URI */ temp = index(sr->body.data, ' '); if (mk_unlikely(!temp)) { MK_TRACE("Error, invalid first header"); return -1; } uri_init = (temp - sr->body.data) + 1; temp = index(sr->body.data, '\n'); if (mk_unlikely(!temp)) { MK_TRACE("Error, invalid header CRLF"); return -1; } fh_limit = (temp - sr->body.data); uri_end = mk_string_char_search_r(sr->body.data, ' ', fh_limit) - 1; if (mk_unlikely(uri_end <= 0)) { MK_TRACE("Error, first header bad formed"); return -1; } prot_init = uri_end + 2; if (mk_unlikely(uri_end < uri_init)) { return -1; } /* Query String */ query_init = mk_string_char_search(sr->body.data + uri_init, '?', prot_init - uri_init); if (query_init > 0) { int init, end; init = query_init + uri_init; if (init <= uri_end) { end = uri_end; uri_end = init - 1; sr->query_string = mk_ptr_create(sr->body.data, init + 1, end + 1); } } /* Request URI Part 2 */ sr->uri = mk_ptr_create(sr->body.data, uri_init, uri_end + 1); if (mk_unlikely(sr->uri.len < 1)) { return -1; } /* HTTP Version */ prot_end = fh_limit - 1; if (mk_unlikely(prot_init == prot_end)) { return -1; } if (prot_end != prot_init && prot_end > 0) { sr->protocol = mk_http_protocol_check(sr->body.data + prot_init, prot_end - prot_init); sr->protocol_p = mk_http_protocol_check_str(sr->protocol); } headers = sr->body.data + prot_end + mk_crlf.len; /* * Process URI, if it contains ASCII encoded strings like '%20', * it will return a new memory buffer with the decoded string, otherwise * it returns NULL */ temp = mk_utils_url_decode(sr->uri); if (temp) { sr->uri_processed.data = temp; sr->uri_processed.len = strlen(temp); } else { sr->uri_processed.data = sr->uri.data; sr->uri_processed.len = sr->uri.len; } /* Creating Table of Content (index) for HTTP headers */ sr->headers_len = sr->body.len - (prot_end + mk_crlf.len); if (mk_request_header_toc_parse(&sr->headers_toc, headers, sr->headers_len) < 0) { MK_TRACE("Invalid headers"); return -1; } /* Host */ host = mk_request_header_get(&sr->headers_toc, mk_rh_host.data, mk_rh_host.len); if (host.data) { if ((pos_sep = mk_string_char_search_r(host.data, ':', host.len)) >= 0) { /* TCP port should not be higher than 65535 */ char *p; short int port_len, port_size = 6; char port[port_size]; /* just the host */ sr->host.data = host.data; sr->host.len = pos_sep; /* including the port */ sr->host_port = host; /* Port string length */ port_len = (host.len - pos_sep - 1); if (port_len >= port_size) { return -1; } /* Copy to buffer */ memcpy(port, host.data + pos_sep + 1, port_len); port[port_len] = '\0'; /* Validate that the input port is numeric */ p = port; while (*p) { if (!isdigit(*p)) return -1; p++; } /* Convert to base 10 */ errno = 0; sr->port = strtol(port, (char **) NULL, 10); if ((errno == ERANGE && (sr->port == LONG_MAX || sr->port == LONG_MIN)) || sr->port == 0) { return -1; } } else { sr->host = host; /* maybe null */ sr->port = config->standard_port; } } else { sr->host.data = NULL; } /* Looking for headers that ONLY Monkey uses */ sr->connection = mk_request_header_get(&sr->headers_toc, mk_rh_connection.data, mk_rh_connection.len); sr->range = mk_request_header_get(&sr->headers_toc, mk_rh_range.data, mk_rh_range.len); sr->if_modified_since = mk_request_header_get(&sr->headers_toc, mk_rh_if_modified_since.data, mk_rh_if_modified_since.len); /* Default Keepalive is off */ if (sr->protocol == MK_HTTP_PROTOCOL_10) { sr->keep_alive = MK_FALSE; sr->close_now = MK_TRUE; } else if(sr->protocol == MK_HTTP_PROTOCOL_11) { sr->keep_alive = MK_TRUE; sr->close_now = MK_FALSE; } if (sr->connection.data) { if (mk_string_search_n(sr->connection.data, "Keep-Alive", MK_STR_INSENSITIVE, sr->connection.len) >= 0) { sr->keep_alive = MK_TRUE; sr->close_now = MK_FALSE; } else if (mk_string_search_n(sr->connection.data, "Close", MK_STR_INSENSITIVE, sr->connection.len) >= 0) { sr->keep_alive = MK_FALSE; sr->close_now = MK_TRUE; } else { /* Set as a non-valid connection header value */ sr->connection.len = 0; } } return 0; } static int mk_request_parse(struct client_session *cs) { int i, end; int blocks = 0; struct session_request *sr_node; struct mk_list *sr_list, *sr_head; for (i = 0; i <= cs->body_pos_end; i++) { /* * Pipelining can just exists in a persistent connection or * well known as KeepAlive, so if we are in keepalive mode * we should check if we have multiple request in our body buffer */ end = mk_string_search(cs->body + i, mk_endblock.data, MK_STR_SENSITIVE) + i; if (end < 0) { return -1; } /* Allocating request block */ if (blocks == 0) { sr_node = &cs->sr_fixed; memset(sr_node, '\0', sizeof(struct session_request)); } else { sr_node = mk_mem_malloc_z(sizeof(struct session_request)); } mk_request_init(sr_node); /* We point the block with a mk_ptr_t */ sr_node->body.data = cs->body + i; sr_node->body.len = end - i; /* Method, previous catch in mk_http_pending_request */ if (i == 0) { sr_node->method = cs->first_method; } else { sr_node->method = mk_http_method_get(sr_node->body.data); } /* Looking for POST data */ if (sr_node->method == MK_HTTP_METHOD_POST) { int offset; offset = end + mk_endblock.len; sr_node->data = mk_method_get_data(cs->body + offset, cs->body_length - offset); } /* Increase index to the end of the current block */ i = (end + mk_endblock.len) - 1; /* Link block */ mk_list_add(&sr_node->_head, &cs->request_list); /* Update counter */ blocks++; } /* DEBUG BLOCKS struct mk_list *head; struct session_request *entry; printf("\n*******************\n"); mk_list_foreach(head, &cs->request_list) { entry = mk_list_entry(head, struct session_request, _head); mk_ptr_print(entry->body); fflush(stdout); } */ /* Checking pipelining connection */ if (blocks > 1) { sr_list = &cs->request_list; mk_list_foreach(sr_head, sr_list) { sr_node = mk_list_entry(sr_head, struct session_request, _head); /* Pipelining request must use GET or HEAD methods */ if (sr_node->method != MK_HTTP_METHOD_GET && sr_node->method != MK_HTTP_METHOD_HEAD) { return -1; } } cs->pipelined = MK_TRUE; } #ifdef TRACE int b = 0; if (cs->pipelined == MK_TRUE) { MK_TRACE("[FD %i] Pipeline Requests: %i blocks", cs->socket, blocks); sr_list = &cs->request_list; mk_list_foreach(sr_head, sr_list) { sr_node = mk_list_entry(sr_head, struct session_request, _head); MK_TRACE("[FD %i] Pipeline Block #%i: %p", cs->socket, b, sr_node); b++; } } #endif return 0; } /* This function allow the core to invoke the closing connection process * when some connection was not proceesed due to a premature close or similar * exception, it also take care of invoke the STAGE_40 and STAGE_50 plugins events */ static void mk_request_premature_close(int http_status, struct client_session *cs) { struct session_request *sr; struct mk_list *sr_list = &cs->request_list; struct mk_list *host_list = &config->hosts; /* * If the connection is too premature, we need to allocate a temporal session_request * to do not break the plugins stages */ if (mk_list_is_empty(sr_list) == 0) { sr = &cs->sr_fixed; memset(sr, 0, sizeof(struct session_request)); mk_request_init(sr); mk_list_add(&sr->_head, &cs->request_list); } else { sr = mk_list_entry_first(sr_list, struct session_request, _head); } /* Raise error */ if (http_status > 0) { if (!sr->host_conf) { sr->host_conf = mk_list_entry_first(host_list, struct host, _head); } mk_request_error(http_status, cs, sr); /* STAGE_40, request has ended */ mk_plugin_stage_run(MK_PLUGIN_STAGE_40, cs->socket, NULL, cs, sr); } /* STAGE_50, connection closed and remove client_session*/ mk_plugin_stage_run(MK_PLUGIN_STAGE_50, cs->socket, NULL, NULL, NULL); mk_session_remove(cs->socket); } static int mk_request_process(struct client_session *cs, struct session_request *sr) { int status = 0; int socket = cs->socket; struct mk_list *hosts = &config->hosts; struct mk_list *alias; /* Always assign the first node 'default vhost' */ sr->host_conf = mk_list_entry_first(hosts, struct host, _head); /* Parse request */ status = mk_request_header_process(sr); if (status < 0) { mk_header_set_http_status(sr, MK_CLIENT_BAD_REQUEST); mk_request_error(MK_CLIENT_BAD_REQUEST, cs, sr); return EXIT_ABORT; } sr->user_home = MK_FALSE; /* Valid request URI? */ if (sr->uri_processed.data[0] != '/') { mk_request_error(MK_CLIENT_BAD_REQUEST, cs, sr); return EXIT_NORMAL; } /* HTTP/1.1 needs Host header */ if (!sr->host.data && sr->protocol == MK_HTTP_PROTOCOL_11) { mk_request_error(MK_CLIENT_BAD_REQUEST, cs, sr); return EXIT_NORMAL; } /* Validating protocol version */ if (sr->protocol == MK_HTTP_PROTOCOL_UNKNOWN) { mk_request_error(MK_SERVER_HTTP_VERSION_UNSUP, cs, sr); return EXIT_ABORT; } /* Assign the first node alias */ alias = &sr->host_conf->server_names; sr->host_alias = mk_list_entry_first(alias, struct host_alias, _head); if (sr->host.data) { /* Match the virtual host */ mk_vhost_get(sr->host, &sr->host_conf, &sr->host_alias); /* Check if this virtual host have some redirection */ if (sr->host_conf->header_redirect.data) { mk_header_set_http_status(sr, MK_REDIR_MOVED); sr->headers.location = mk_string_dup(sr->host_conf->header_redirect.data); sr->headers.content_length = 0; mk_header_send(cs->socket, cs, sr); sr->headers.location = NULL; mk_server_cork_flag(cs->socket, TCP_CORK_OFF); return 0; } } /* Is requesting an user home directory ? */ if (config->user_dir && sr->uri_processed.len > 2 && sr->uri_processed.data[1] == MK_USER_HOME) { if (mk_user_init(cs, sr) != 0) { mk_request_error(MK_CLIENT_NOT_FOUND, cs, sr); return EXIT_ABORT; } } /* Handling method requested */ if (sr->method == MK_HTTP_METHOD_POST || sr->method == MK_HTTP_METHOD_PUT) { if ((status = mk_method_parse_data(cs, sr)) != 0) { return status; } } /* Plugins Stage 20 */ int ret; ret = mk_plugin_stage_run(MK_PLUGIN_STAGE_20, socket, NULL, cs, sr); if (ret == MK_PLUGIN_RET_CLOSE_CONX) { MK_TRACE("STAGE 20 requested close conexion"); return EXIT_ABORT; } /* Normal HTTP process */ status = mk_http_init(cs, sr); MK_TRACE("[FD %i] HTTP Init returning %i", socket, status); return status; } /* Build error page */ static mk_ptr_t *mk_request_set_default_page(char *title, mk_ptr_t message, char *signature) { char *temp; mk_ptr_t *p; p = mk_mem_malloc(sizeof(mk_ptr_t)); p->data = NULL; temp = mk_ptr_to_buf(message); mk_string_build(&p->data, &p->len, MK_REQUEST_DEFAULT_PAGE, title, temp, signature); mk_mem_free(temp); return p; } int mk_handler_read(int socket, struct client_session *cs) { int bytes; int max_read; int available = 0; int new_size; int total_bytes = 0; char *tmp = 0; MK_TRACE("MAX REQUEST SIZE: %i", config->max_request_size); try_pending: available = cs->body_size - cs->body_length; if (available <= 0) { /* Reallocate buffer size if pending data does not have space */ new_size = cs->body_size + config->transport_buffer_size; if (new_size > config->max_request_size) { MK_TRACE("Requested size is > config->max_request_size"); mk_request_premature_close(MK_CLIENT_REQUEST_ENTITY_TOO_LARGE, cs); return -1; } /* * Check if the body field still points to the initial body_fixed, if so, * allow the new space required in body, otherwise perform a realloc over * body. */ if (cs->body == cs->body_fixed) { cs->body = mk_mem_malloc(new_size + 1); cs->body_size = new_size; memcpy(cs->body, cs->body_fixed, cs->body_length); MK_TRACE("[FD %i] New size: %i, length: %i", cs->socket, new_size, cs->body_length); } else { MK_TRACE("[FD %i] Realloc from %i to %i", cs->socket, cs->body_size, new_size); tmp = mk_mem_realloc(cs->body, new_size + 1); if (tmp) { cs->body = tmp; cs->body_size = new_size; } else { mk_request_premature_close(MK_SERVER_INTERNAL_ERROR, cs); return -1; } } } /* Read content */ max_read = (cs->body_size - cs->body_length); bytes = mk_socket_read(socket, cs->body + cs->body_length, max_read); MK_TRACE("[FD %i] read %i", socket, bytes); if (bytes < 0) { if (errno == EAGAIN) { return 1; } else { mk_session_remove(socket); return -1; } } if (bytes == 0) { mk_session_remove(socket); return -1; } if (bytes > 0) { if (bytes > max_read) { MK_TRACE("[FD %i] Buffer still have data: %i", cs->socket, bytes - max_read); cs->body_length += max_read; cs->body[cs->body_length] = '\0'; total_bytes += max_read; goto try_pending; } else { cs->body_length += bytes; cs->body[cs->body_length] = '\0'; total_bytes += bytes; } MK_TRACE("[FD %i] Retry total bytes: %i", cs->socket, total_bytes); return total_bytes; } return bytes; } int mk_handler_write(int socket, struct client_session *cs) { int final_status = 0; struct session_request *sr_node; struct mk_list *sr_list; if (mk_list_is_empty(&cs->request_list) == 0) { if (mk_request_parse(cs) != 0) { return -1; } } sr_list = &cs->request_list; sr_node = mk_list_entry_first(sr_list, struct session_request, _head); if (sr_node->bytes_to_send > 0) { /* Request with data to send by static file sender */ final_status = mk_http_send_file(cs, sr_node); } else if (sr_node->bytes_to_send < 0) { final_status = mk_request_process(cs, sr_node); } /* * If we got an error, we don't want to parse * and send information for another pipelined request */ if (final_status > 0) { return final_status; } else { /* STAGE_40, request has ended */ mk_plugin_stage_run(MK_PLUGIN_STAGE_40, socket, NULL, cs, sr_node); switch (final_status) { case EXIT_NORMAL: case EXIT_ERROR: if (sr_node->close_now == MK_TRUE) { return -1; } break; case EXIT_ABORT: return -1; } } /* * If we are here, is because all pipelined request were * processed successfully, let's return 0 */ return 0; } /* Look for some index.xxx in pathfile */ mk_ptr_t mk_request_index(char *pathfile, char *file_aux, const unsigned int flen) { unsigned long len; mk_ptr_t f; struct mk_string_line *entry; struct mk_list *head; mk_ptr_reset(&f); if (!config->index_files) return f; mk_list_foreach(head, config->index_files) { entry = mk_list_entry(head, struct mk_string_line, _head); len = snprintf(file_aux, flen, "%s%s", pathfile, entry->val); if (mk_unlikely(len > flen)) { len = flen - 1; mk_warn("Path too long, truncated! '%s'", file_aux); } if (access(file_aux, F_OK) == 0) { f.data = file_aux; f.len = len; return f; } } return f; } /* Send error responses */ int mk_request_error(int http_status, struct client_session *cs, struct session_request *sr) { int ret, fd; mk_ptr_t message, *page = 0; struct error_page *entry; struct mk_list *head; struct file_info finfo; mk_header_set_http_status(sr, http_status); /* * We are nice sending error pages for clients who at least respect * the especification */ if (http_status != MK_CLIENT_LENGTH_REQUIRED && http_status != MK_CLIENT_BAD_REQUEST && http_status != MK_CLIENT_REQUEST_ENTITY_TOO_LARGE) { /* Lookup a customized error page */ mk_list_foreach(head, &sr->host_conf->error_pages) { entry = mk_list_entry(head, struct error_page, _head); if (entry->status != http_status) { continue; } /* validate error file */ ret = mk_file_get_info(entry->real_path, &finfo); if (ret == -1) { break; } /* open file */ fd = open(entry->real_path, config->open_flags); if (fd == -1) { break; } sr->fd_file = fd; sr->bytes_to_send = finfo.size; sr->headers.content_length = finfo.size; sr->headers.real_length = finfo.size; memcpy(&sr->file_info, &finfo, sizeof(struct file_info)); mk_header_send(cs->socket, cs, sr); return mk_http_send_file(cs, sr); } } mk_ptr_reset(&message); switch (http_status) { case MK_CLIENT_BAD_REQUEST: page = mk_request_set_default_page("Bad Request", sr->uri, sr->host_conf->host_signature); break; case MK_CLIENT_FORBIDDEN: page = mk_request_set_default_page("Forbidden", sr->uri, sr->host_conf->host_signature); break; case MK_CLIENT_NOT_FOUND: mk_string_build(&message.data, &message.len, "The requested URL was not found on this server."); page = mk_request_set_default_page("Not Found", message, sr->host_conf->host_signature); mk_ptr_free(&message); break; case MK_CLIENT_REQUEST_ENTITY_TOO_LARGE: mk_string_build(&message.data, &message.len, "The request entity is too large."); page = mk_request_set_default_page("Entity too large", message, sr->host_conf->host_signature); mk_ptr_free(&message); break; case MK_CLIENT_METHOD_NOT_ALLOWED: page = mk_request_set_default_page("Method Not Allowed", sr->uri, sr->host_conf->host_signature); break; case MK_CLIENT_REQUEST_TIMEOUT: case MK_CLIENT_LENGTH_REQUIRED: break; case MK_SERVER_NOT_IMPLEMENTED: page = mk_request_set_default_page("Method Not Implemented", sr->uri, sr->host_conf->host_signature); break; case MK_SERVER_INTERNAL_ERROR: page = mk_request_set_default_page("Internal Server Error", sr->uri, sr->host_conf->host_signature); break; case MK_SERVER_HTTP_VERSION_UNSUP: mk_ptr_reset(&message); page = mk_request_set_default_page("HTTP Version Not Supported", message, sr->host_conf->host_signature); break; } if (page) { sr->headers.content_length = page->len; } sr->headers.location = NULL; sr->headers.cgi = SH_NOCGI; sr->headers.pconnections_left = 0; sr->headers.last_modified = -1; if (!page) { mk_ptr_reset(&sr->headers.content_type); } else { mk_ptr_set(&sr->headers.content_type, "text/html\r\n"); } mk_header_send(cs->socket, cs, sr); if (page) { if (sr->method != MK_HTTP_METHOD_HEAD) mk_socket_send(cs->socket, page->data, page->len); mk_ptr_free(page); mk_mem_free(page); } /* Turn off TCP_CORK */ mk_server_cork_flag(cs->socket, TCP_CORK_OFF); return EXIT_ERROR; } void mk_request_free_list(struct client_session *cs) { struct session_request *sr_node; struct mk_list *sr_head, *temp; /* sr = last node */ MK_TRACE("[FD %i] Free struct client_session", cs->socket); mk_list_foreach_safe(sr_head, temp, &cs->request_list) { sr_node = mk_list_entry(sr_head, struct session_request, _head); mk_list_del(sr_head); mk_request_free(sr_node); if (sr_node != &cs->sr_fixed) { mk_mem_free(sr_node); } } } /* Create a client request struct and put it on the * main list */ struct client_session *mk_session_create(int socket, struct sched_list_node *sched) { struct client_session *cs; struct sched_connection *sc; sc = mk_sched_get_connection(sched, socket); if (!sc) { MK_TRACE("[FD %i] No sched node, could not create session", socket); return NULL; } /* Alloc memory for node */ cs = mk_mem_malloc(sizeof(struct client_session)); cs->pipelined = MK_FALSE; cs->counter_connections = 0; cs->socket = socket; cs->status = MK_REQUEST_STATUS_INCOMPLETE; mk_list_add(&cs->request_incomplete, cs_incomplete); /* creation time in unix time */ cs->init_time = sc->arrive_time; /* alloc space for body content */ if (config->transport_buffer_size > MK_REQUEST_CHUNK) { cs->body = mk_mem_malloc(config->transport_buffer_size); cs->body_size = config->transport_buffer_size; } else { /* Buffer size based in Chunk bytes */ cs->body = cs->body_fixed; cs->body_size = MK_REQUEST_CHUNK; } /* Current data length */ cs->body_length = 0; cs->body_pos_end = -1; cs->first_method = MK_HTTP_METHOD_UNKNOWN; /* Init session request list */ mk_list_init(&cs->request_list); /* Add this SESSION to the thread list */ /* Add node to list */ /* Red-Black tree insert routine */ struct rb_node **new = &(cs_list->rb_node); struct rb_node *parent = NULL; /* Figure out where to put new node */ while (*new) { struct client_session *this = container_of(*new, struct client_session, _rb_head); parent = *new; if (cs->socket < this->socket) new = &((*new)->rb_left); else if (cs->socket > this->socket) new = &((*new)->rb_right); else { break; } } /* Add new node and rebalance tree. */ rb_link_node(&cs->_rb_head, parent, new); rb_insert_color(&cs->_rb_head, cs_list); return cs; } struct client_session *mk_session_get(int socket) { struct client_session *cs; struct rb_node *node; node = cs_list->rb_node; while (node) { cs = container_of(node, struct client_session, _rb_head); if (socket < cs->socket) node = node->rb_left; else if (socket > cs->socket) node = node->rb_right; else { return cs; } } return NULL; } /* * From thread sched_list_node "list", remove the client_session * struct information */ void mk_session_remove(int socket) { struct client_session *cs_node; cs_node = mk_session_get(socket); if (cs_node) { rb_erase(&cs_node->_rb_head, cs_list); if (cs_node->body != cs_node->body_fixed) { mk_mem_free(cs_node->body); } if (mk_list_entry_orphan(&cs_node->request_incomplete) == 0) { mk_list_del(&cs_node->request_incomplete); } mk_list_del(&cs_node->request_list); mk_mem_free(cs_node); } } /* Return value of some variable sent in request */ mk_ptr_t mk_request_header_get(struct headers_toc *toc, const char *key_name, int key_len) { int i; struct header_toc_row *row; mk_ptr_t var; var.data = NULL; var.len = 0; row = toc->rows; for (i = 0; i < toc->length; i++) { /* * status = 1 means that the toc entry was already * checked by Monkey */ if (row[i].status == 1) { continue; } if (strncasecmp(row[i].init, key_name, key_len) == 0) { var.data = row[i].init + key_len + 1; var.len = row[i].end - var.data; row[i].status = 1; break; } } return var; } void mk_request_ka_next(struct client_session *cs) { cs->first_method = -1; cs->body_pos_end = -1; cs->body_length = 0; cs->counter_connections++; /* Update data for scheduler */ cs->init_time = log_current_utime; cs->status = MK_REQUEST_STATUS_INCOMPLETE; mk_list_add(&cs->request_incomplete, cs_incomplete); }
./CrossVul/dataset_final_sorted/CWE-20/c/bad_2253_1
crossvul-cpp_data_good_1420_1
/* $OpenBSD: tcp_input.c,v 1.360 2019/07/10 18:45:31 bluhm Exp $ */ /* $NetBSD: tcp_input.c,v 1.23 1996/02/13 23:43:44 christos Exp $ */ /* * Copyright (c) 1982, 1986, 1988, 1990, 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 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 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 BY THE REGENTS 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 REGENTS 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. * * @(#)COPYRIGHT 1.1 (NRL) 17 January 1995 * * NRL grants permission for redistribution and use in source and binary * forms, with or without modification, of the software and documentation * created at NRL 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. All advertising materials mentioning features or use of this software * must display the following acknowledgements: * This product includes software developed by the University of * California, Berkeley and its contributors. * This product includes software developed at the Information * Technology Division, US Naval Research Laboratory. * 4. Neither the name of the NRL nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THE SOFTWARE PROVIDED BY NRL IS PROVIDED BY NRL 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 NRL 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. * * The views and conclusions contained in the software and documentation * are those of the authors and should not be interpreted as representing * official policies, either expressed or implied, of the US Naval * Research Laboratory (NRL). */ #include "pf.h" #include <sys/param.h> #include <sys/systm.h> #include <sys/mbuf.h> #include <sys/protosw.h> #include <sys/socket.h> #include <sys/socketvar.h> #include <sys/timeout.h> #include <sys/kernel.h> #include <sys/pool.h> #include <net/if.h> #include <net/if_var.h> #include <net/route.h> #include <netinet/in.h> #include <netinet/ip.h> #include <netinet/in_pcb.h> #include <netinet/ip_var.h> #include <netinet/tcp.h> #include <netinet/tcp_fsm.h> #include <netinet/tcp_seq.h> #include <netinet/tcp_timer.h> #include <netinet/tcp_var.h> #include <netinet/tcp_debug.h> #if NPF > 0 #include <net/pfvar.h> #endif struct tcpiphdr tcp_saveti; int tcp_mss_adv(struct mbuf *, int); int tcp_flush_queue(struct tcpcb *); #ifdef INET6 #include <netinet6/in6_var.h> #include <netinet6/nd6.h> struct tcpipv6hdr tcp_saveti6; /* for the packet header length in the mbuf */ #define M_PH_LEN(m) (((struct mbuf *)(m))->m_pkthdr.len) #define M_V6_LEN(m) (M_PH_LEN(m) - sizeof(struct ip6_hdr)) #define M_V4_LEN(m) (M_PH_LEN(m) - sizeof(struct ip)) #endif /* INET6 */ int tcprexmtthresh = 3; int tcptv_keep_init = TCPTV_KEEP_INIT; int tcp_rst_ppslim = 100; /* 100pps */ int tcp_rst_ppslim_count = 0; struct timeval tcp_rst_ppslim_last; int tcp_ackdrop_ppslim = 100; /* 100pps */ int tcp_ackdrop_ppslim_count = 0; struct timeval tcp_ackdrop_ppslim_last; #define TCP_PAWS_IDLE (24 * 24 * 60 * 60 * PR_SLOWHZ) /* for modulo comparisons of timestamps */ #define TSTMP_LT(a,b) ((int)((a)-(b)) < 0) #define TSTMP_GEQ(a,b) ((int)((a)-(b)) >= 0) /* for TCP SACK comparisons */ #define SEQ_MIN(a,b) (SEQ_LT(a,b) ? (a) : (b)) #define SEQ_MAX(a,b) (SEQ_GT(a,b) ? (a) : (b)) /* * Neighbor Discovery, Neighbor Unreachability Detection Upper layer hint. */ #ifdef INET6 #define ND6_HINT(tp) \ do { \ if (tp && tp->t_inpcb && (tp->t_inpcb->inp_flags & INP_IPV6) && \ rtisvalid(tp->t_inpcb->inp_route6.ro_rt)) { \ nd6_nud_hint(tp->t_inpcb->inp_route6.ro_rt); \ } \ } while (0) #else #define ND6_HINT(tp) #endif #ifdef TCP_ECN /* * ECN (Explicit Congestion Notification) support based on RFC3168 * implementation note: * snd_last is used to track a recovery phase. * when cwnd is reduced, snd_last is set to snd_max. * while snd_last > snd_una, the sender is in a recovery phase and * its cwnd should not be reduced again. * snd_last follows snd_una when not in a recovery phase. */ #endif /* * Macro to compute ACK transmission behavior. Delay the ACK unless * we have already delayed an ACK (must send an ACK every two segments). * We also ACK immediately if we received a PUSH and the ACK-on-PUSH * option is enabled or when the packet is coming from a loopback * interface. */ #define TCP_SETUP_ACK(tp, tiflags, m) \ do { \ struct ifnet *ifp = NULL; \ if (m && (m->m_flags & M_PKTHDR)) \ ifp = if_get(m->m_pkthdr.ph_ifidx); \ if (TCP_TIMER_ISARMED(tp, TCPT_DELACK) || \ (tcp_ack_on_push && (tiflags) & TH_PUSH) || \ (ifp && (ifp->if_flags & IFF_LOOPBACK))) \ tp->t_flags |= TF_ACKNOW; \ else \ TCP_TIMER_ARM_MSEC(tp, TCPT_DELACK, tcp_delack_msecs); \ if_put(ifp); \ } while (0) void tcp_sack_partialack(struct tcpcb *, struct tcphdr *); void tcp_newreno_partialack(struct tcpcb *, struct tcphdr *); void syn_cache_put(struct syn_cache *); void syn_cache_rm(struct syn_cache *); int syn_cache_respond(struct syn_cache *, struct mbuf *); void syn_cache_timer(void *); void syn_cache_reaper(void *); void syn_cache_insert(struct syn_cache *, struct tcpcb *); void syn_cache_reset(struct sockaddr *, struct sockaddr *, struct tcphdr *, u_int); int syn_cache_add(struct sockaddr *, struct sockaddr *, struct tcphdr *, unsigned int, struct socket *, struct mbuf *, u_char *, int, struct tcp_opt_info *, tcp_seq *); struct socket *syn_cache_get(struct sockaddr *, struct sockaddr *, struct tcphdr *, unsigned int, unsigned int, struct socket *, struct mbuf *); struct syn_cache *syn_cache_lookup(struct sockaddr *, struct sockaddr *, struct syn_cache_head **, u_int); /* * Insert segment ti into reassembly queue of tcp with * control block tp. Return TH_FIN if reassembly now includes * a segment with FIN. The macro form does the common case inline * (segment is the next to be received on an established connection, * and the queue is empty), avoiding linkage into and removal * from the queue and repetition of various conversions. * Set DELACK for segments received in order, but ack immediately * when segments are out of order (so fast retransmit can work). */ int tcp_reass(struct tcpcb *tp, struct tcphdr *th, struct mbuf *m, int *tlen) { struct tcpqent *p, *q, *nq, *tiqe; /* * Allocate a new queue entry, before we throw away any data. * If we can't, just drop the packet. XXX */ tiqe = pool_get(&tcpqe_pool, PR_NOWAIT); if (tiqe == NULL) { tiqe = TAILQ_LAST(&tp->t_segq, tcpqehead); if (tiqe != NULL && th->th_seq == tp->rcv_nxt) { /* Reuse last entry since new segment fills a hole */ m_freem(tiqe->tcpqe_m); TAILQ_REMOVE(&tp->t_segq, tiqe, tcpqe_q); } if (tiqe == NULL || th->th_seq != tp->rcv_nxt) { /* Flush segment queue for this connection */ tcp_freeq(tp); tcpstat_inc(tcps_rcvmemdrop); m_freem(m); return (0); } } /* * Find a segment which begins after this one does. */ for (p = NULL, q = TAILQ_FIRST(&tp->t_segq); q != NULL; p = q, q = TAILQ_NEXT(q, tcpqe_q)) if (SEQ_GT(q->tcpqe_tcp->th_seq, th->th_seq)) break; /* * If there is a preceding segment, it may provide some of * our data already. If so, drop the data from the incoming * segment. If it provides all of our data, drop us. */ if (p != NULL) { struct tcphdr *phdr = p->tcpqe_tcp; int i; /* conversion to int (in i) handles seq wraparound */ i = phdr->th_seq + phdr->th_reseqlen - th->th_seq; if (i > 0) { if (i >= *tlen) { tcpstat_pkt(tcps_rcvduppack, tcps_rcvdupbyte, *tlen); m_freem(m); pool_put(&tcpqe_pool, tiqe); return (0); } m_adj(m, i); *tlen -= i; th->th_seq += i; } } tcpstat_pkt(tcps_rcvoopack, tcps_rcvoobyte, *tlen); /* * While we overlap succeeding segments trim them or, * if they are completely covered, dequeue them. */ for (; q != NULL; q = nq) { struct tcphdr *qhdr = q->tcpqe_tcp; int i = (th->th_seq + *tlen) - qhdr->th_seq; if (i <= 0) break; if (i < qhdr->th_reseqlen) { qhdr->th_seq += i; qhdr->th_reseqlen -= i; m_adj(q->tcpqe_m, i); break; } nq = TAILQ_NEXT(q, tcpqe_q); m_freem(q->tcpqe_m); TAILQ_REMOVE(&tp->t_segq, q, tcpqe_q); pool_put(&tcpqe_pool, q); } /* Insert the new segment queue entry into place. */ tiqe->tcpqe_m = m; th->th_reseqlen = *tlen; tiqe->tcpqe_tcp = th; if (p == NULL) { TAILQ_INSERT_HEAD(&tp->t_segq, tiqe, tcpqe_q); } else { TAILQ_INSERT_AFTER(&tp->t_segq, p, tiqe, tcpqe_q); } if (th->th_seq != tp->rcv_nxt) return (0); return (tcp_flush_queue(tp)); } int tcp_flush_queue(struct tcpcb *tp) { struct socket *so = tp->t_inpcb->inp_socket; struct tcpqent *q, *nq; int flags; /* * Present data to user, advancing rcv_nxt through * completed sequence space. */ if (TCPS_HAVEESTABLISHED(tp->t_state) == 0) return (0); q = TAILQ_FIRST(&tp->t_segq); if (q == NULL || q->tcpqe_tcp->th_seq != tp->rcv_nxt) return (0); if (tp->t_state == TCPS_SYN_RECEIVED && q->tcpqe_tcp->th_reseqlen) return (0); do { tp->rcv_nxt += q->tcpqe_tcp->th_reseqlen; flags = q->tcpqe_tcp->th_flags & TH_FIN; nq = TAILQ_NEXT(q, tcpqe_q); TAILQ_REMOVE(&tp->t_segq, q, tcpqe_q); ND6_HINT(tp); if (so->so_state & SS_CANTRCVMORE) m_freem(q->tcpqe_m); else sbappendstream(so, &so->so_rcv, q->tcpqe_m); pool_put(&tcpqe_pool, q); q = nq; } while (q != NULL && q->tcpqe_tcp->th_seq == tp->rcv_nxt); tp->t_flags |= TF_BLOCKOUTPUT; sorwakeup(so); tp->t_flags &= ~TF_BLOCKOUTPUT; return (flags); } /* * TCP input routine, follows pages 65-76 of the * protocol specification dated September, 1981 very closely. */ int tcp_input(struct mbuf **mp, int *offp, int proto, int af) { struct mbuf *m = *mp; int iphlen = *offp; struct ip *ip = NULL; struct inpcb *inp = NULL; u_int8_t *optp = NULL; int optlen = 0; int tlen, off; struct tcpcb *otp = NULL, *tp = NULL; int tiflags; struct socket *so = NULL; int todrop, acked, ourfinisacked; int hdroptlen = 0; short ostate; caddr_t saveti; tcp_seq iss, *reuse = NULL; u_long tiwin; struct tcp_opt_info opti; struct tcphdr *th; #ifdef INET6 struct ip6_hdr *ip6 = NULL; #endif /* INET6 */ #ifdef IPSEC struct m_tag *mtag; struct tdb_ident *tdbi; struct tdb *tdb; int error; #endif /* IPSEC */ #ifdef TCP_ECN u_char iptos; #endif tcpstat_inc(tcps_rcvtotal); opti.ts_present = 0; opti.maxseg = 0; /* * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN */ if (m->m_flags & (M_BCAST|M_MCAST)) goto drop; /* * Get IP and TCP header together in first mbuf. * Note: IP leaves IP header in first mbuf. */ IP6_EXTHDR_GET(th, struct tcphdr *, m, iphlen, sizeof(*th)); if (!th) { tcpstat_inc(tcps_rcvshort); return IPPROTO_DONE; } tlen = m->m_pkthdr.len - iphlen; switch (af) { case AF_INET: ip = mtod(m, struct ip *); #ifdef TCP_ECN /* save ip_tos before clearing it for checksum */ iptos = ip->ip_tos; #endif break; #ifdef INET6 case AF_INET6: ip6 = mtod(m, struct ip6_hdr *); #ifdef TCP_ECN iptos = (ntohl(ip6->ip6_flow) >> 20) & 0xff; #endif /* * Be proactive about unspecified IPv6 address in source. * As we use all-zero to indicate unbounded/unconnected pcb, * unspecified IPv6 address can be used to confuse us. * * Note that packets with unspecified IPv6 destination is * already dropped in ip6_input. */ if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src)) { /* XXX stat */ goto drop; } /* Discard packets to multicast */ if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst)) { /* XXX stat */ goto drop; } break; #endif default: unhandled_af(af); } /* * Checksum extended TCP header and data. */ if ((m->m_pkthdr.csum_flags & M_TCP_CSUM_IN_OK) == 0) { int sum; if (m->m_pkthdr.csum_flags & M_TCP_CSUM_IN_BAD) { tcpstat_inc(tcps_rcvbadsum); goto drop; } tcpstat_inc(tcps_inswcsum); switch (af) { case AF_INET: sum = in4_cksum(m, IPPROTO_TCP, iphlen, tlen); break; #ifdef INET6 case AF_INET6: sum = in6_cksum(m, IPPROTO_TCP, sizeof(struct ip6_hdr), tlen); break; #endif } if (sum != 0) { tcpstat_inc(tcps_rcvbadsum); goto drop; } } /* * Check that TCP offset makes sense, * pull out TCP options and adjust length. XXX */ off = th->th_off << 2; if (off < sizeof(struct tcphdr) || off > tlen) { tcpstat_inc(tcps_rcvbadoff); goto drop; } tlen -= off; if (off > sizeof(struct tcphdr)) { IP6_EXTHDR_GET(th, struct tcphdr *, m, iphlen, off); if (!th) { tcpstat_inc(tcps_rcvshort); return IPPROTO_DONE; } optlen = off - sizeof(struct tcphdr); optp = (u_int8_t *)(th + 1); /* * Do quick retrieval of timestamp options ("options * prediction?"). If timestamp is the only option and it's * formatted as recommended in RFC 1323 appendix A, we * quickly get the values now and not bother calling * tcp_dooptions(), etc. */ if ((optlen == TCPOLEN_TSTAMP_APPA || (optlen > TCPOLEN_TSTAMP_APPA && optp[TCPOLEN_TSTAMP_APPA] == TCPOPT_EOL)) && *(u_int32_t *)optp == htonl(TCPOPT_TSTAMP_HDR) && (th->th_flags & TH_SYN) == 0) { opti.ts_present = 1; opti.ts_val = ntohl(*(u_int32_t *)(optp + 4)); opti.ts_ecr = ntohl(*(u_int32_t *)(optp + 8)); optp = NULL; /* we've parsed the options */ } } tiflags = th->th_flags; /* * Convert TCP protocol specific fields to host format. */ th->th_seq = ntohl(th->th_seq); th->th_ack = ntohl(th->th_ack); th->th_win = ntohs(th->th_win); th->th_urp = ntohs(th->th_urp); /* * Locate pcb for segment. */ #if NPF > 0 inp = pf_inp_lookup(m); #endif findpcb: if (inp == NULL) { switch (af) { #ifdef INET6 case AF_INET6: inp = in6_pcbhashlookup(&tcbtable, &ip6->ip6_src, th->th_sport, &ip6->ip6_dst, th->th_dport, m->m_pkthdr.ph_rtableid); break; #endif case AF_INET: inp = in_pcbhashlookup(&tcbtable, ip->ip_src, th->th_sport, ip->ip_dst, th->th_dport, m->m_pkthdr.ph_rtableid); break; } } if (inp == NULL) { tcpstat_inc(tcps_pcbhashmiss); switch (af) { #ifdef INET6 case AF_INET6: inp = in6_pcblookup_listen(&tcbtable, &ip6->ip6_dst, th->th_dport, m, m->m_pkthdr.ph_rtableid); break; #endif /* INET6 */ case AF_INET: inp = in_pcblookup_listen(&tcbtable, ip->ip_dst, th->th_dport, m, m->m_pkthdr.ph_rtableid); break; } /* * If the state is CLOSED (i.e., TCB does not exist) then * all data in the incoming segment is discarded. * If the TCB exists but is in CLOSED state, it is embryonic, * but should either do a listen or a connect soon. */ if (inp == NULL) { tcpstat_inc(tcps_noport); goto dropwithreset_ratelim; } } KASSERT(sotoinpcb(inp->inp_socket) == inp); KASSERT(intotcpcb(inp) == NULL || intotcpcb(inp)->t_inpcb == inp); soassertlocked(inp->inp_socket); /* Check the minimum TTL for socket. */ switch (af) { case AF_INET: if (inp->inp_ip_minttl && inp->inp_ip_minttl > ip->ip_ttl) goto drop; break; #ifdef INET6 case AF_INET6: if (inp->inp_ip6_minhlim && inp->inp_ip6_minhlim > ip6->ip6_hlim) goto drop; break; #endif } tp = intotcpcb(inp); if (tp == NULL) goto dropwithreset_ratelim; if (tp->t_state == TCPS_CLOSED) goto drop; /* Unscale the window into a 32-bit value. */ if ((tiflags & TH_SYN) == 0) tiwin = th->th_win << tp->snd_scale; else tiwin = th->th_win; so = inp->inp_socket; if (so->so_options & (SO_DEBUG|SO_ACCEPTCONN)) { union syn_cache_sa src; union syn_cache_sa dst; bzero(&src, sizeof(src)); bzero(&dst, sizeof(dst)); switch (af) { case AF_INET: src.sin.sin_len = sizeof(struct sockaddr_in); src.sin.sin_family = AF_INET; src.sin.sin_addr = ip->ip_src; src.sin.sin_port = th->th_sport; dst.sin.sin_len = sizeof(struct sockaddr_in); dst.sin.sin_family = AF_INET; dst.sin.sin_addr = ip->ip_dst; dst.sin.sin_port = th->th_dport; break; #ifdef INET6 case AF_INET6: src.sin6.sin6_len = sizeof(struct sockaddr_in6); src.sin6.sin6_family = AF_INET6; src.sin6.sin6_addr = ip6->ip6_src; src.sin6.sin6_port = th->th_sport; dst.sin6.sin6_len = sizeof(struct sockaddr_in6); dst.sin6.sin6_family = AF_INET6; dst.sin6.sin6_addr = ip6->ip6_dst; dst.sin6.sin6_port = th->th_dport; break; #endif /* INET6 */ } if (so->so_options & SO_DEBUG) { otp = tp; ostate = tp->t_state; switch (af) { #ifdef INET6 case AF_INET6: saveti = (caddr_t) &tcp_saveti6; memcpy(&tcp_saveti6.ti6_i, ip6, sizeof(*ip6)); memcpy(&tcp_saveti6.ti6_t, th, sizeof(*th)); break; #endif case AF_INET: saveti = (caddr_t) &tcp_saveti; memcpy(&tcp_saveti.ti_i, ip, sizeof(*ip)); memcpy(&tcp_saveti.ti_t, th, sizeof(*th)); break; } } if (so->so_options & SO_ACCEPTCONN) { switch (tiflags & (TH_RST|TH_SYN|TH_ACK)) { case TH_SYN|TH_ACK|TH_RST: case TH_SYN|TH_RST: case TH_ACK|TH_RST: case TH_RST: syn_cache_reset(&src.sa, &dst.sa, th, inp->inp_rtableid); goto drop; case TH_SYN|TH_ACK: /* * Received a SYN,ACK. This should * never happen while we are in * LISTEN. Send an RST. */ goto badsyn; case TH_ACK: so = syn_cache_get(&src.sa, &dst.sa, th, iphlen, tlen, so, m); if (so == NULL) { /* * We don't have a SYN for * this ACK; send an RST. */ goto badsyn; } else if (so == (struct socket *)(-1)) { /* * We were unable to create * the connection. If the * 3-way handshake was * completed, and RST has * been sent to the peer. * Since the mbuf might be * in use for the reply, * do not free it. */ m = *mp = NULL; goto drop; } else { /* * We have created a * full-blown connection. */ tp = NULL; inp = sotoinpcb(so); tp = intotcpcb(inp); if (tp == NULL) goto badsyn; /*XXX*/ } break; default: /* * None of RST, SYN or ACK was set. * This is an invalid packet for a * TCB in LISTEN state. Send a RST. */ goto badsyn; case TH_SYN: /* * Received a SYN. */ #ifdef INET6 /* * If deprecated address is forbidden, we do * not accept SYN to deprecated interface * address to prevent any new inbound * connection from getting established. * When we do not accept SYN, we send a TCP * RST, with deprecated source address (instead * of dropping it). We compromise it as it is * much better for peer to send a RST, and * RST will be the final packet for the * exchange. * * If we do not forbid deprecated addresses, we * accept the SYN packet. RFC2462 does not * suggest dropping SYN in this case. * If we decipher RFC2462 5.5.4, it says like * this: * 1. use of deprecated addr with existing * communication is okay - "SHOULD continue * to be used" * 2. use of it with new communication: * (2a) "SHOULD NOT be used if alternate * address with sufficient scope is * available" * (2b) nothing mentioned otherwise. * Here we fall into (2b) case as we have no * choice in our source address selection - we * must obey the peer. * * The wording in RFC2462 is confusing, and * there are multiple description text for * deprecated address handling - worse, they * are not exactly the same. I believe 5.5.4 * is the best one, so we follow 5.5.4. */ if (ip6 && !ip6_use_deprecated) { struct in6_ifaddr *ia6; struct ifnet *ifp = if_get(m->m_pkthdr.ph_ifidx); if (ifp && (ia6 = in6ifa_ifpwithaddr(ifp, &ip6->ip6_dst)) && (ia6->ia6_flags & IN6_IFF_DEPRECATED)) { tp = NULL; if_put(ifp); goto dropwithreset; } if_put(ifp); } #endif /* * LISTEN socket received a SYN * from itself? This can't possibly * be valid; drop the packet. */ if (th->th_dport == th->th_sport) { switch (af) { #ifdef INET6 case AF_INET6: if (IN6_ARE_ADDR_EQUAL(&ip6->ip6_src, &ip6->ip6_dst)) { tcpstat_inc(tcps_badsyn); goto drop; } break; #endif /* INET6 */ case AF_INET: if (ip->ip_dst.s_addr == ip->ip_src.s_addr) { tcpstat_inc(tcps_badsyn); goto drop; } break; } } /* * SYN looks ok; create compressed TCP * state for it. */ if (so->so_qlen > so->so_qlimit || syn_cache_add(&src.sa, &dst.sa, th, iphlen, so, m, optp, optlen, &opti, reuse) == -1) { tcpstat_inc(tcps_dropsyn); goto drop; } return IPPROTO_DONE; } } } #ifdef DIAGNOSTIC /* * Should not happen now that all embryonic connections * are handled with compressed state. */ if (tp->t_state == TCPS_LISTEN) panic("tcp_input: TCPS_LISTEN"); #endif #if NPF > 0 pf_inp_link(m, inp); #endif #ifdef IPSEC /* Find most recent IPsec tag */ mtag = m_tag_find(m, PACKET_TAG_IPSEC_IN_DONE, NULL); if (mtag != NULL) { tdbi = (struct tdb_ident *)(mtag + 1); tdb = gettdb(tdbi->rdomain, tdbi->spi, &tdbi->dst, tdbi->proto); } else tdb = NULL; ipsp_spd_lookup(m, af, iphlen, &error, IPSP_DIRECTION_IN, tdb, inp, 0); if (error) { tcpstat_inc(tcps_rcvnosec); goto drop; } #endif /* IPSEC */ /* * Segment received on connection. * Reset idle time and keep-alive timer. */ tp->t_rcvtime = tcp_now; if (TCPS_HAVEESTABLISHED(tp->t_state)) TCP_TIMER_ARM(tp, TCPT_KEEP, tcp_keepidle); if (tp->sack_enable) tcp_del_sackholes(tp, th); /* Delete stale SACK holes */ /* * Process options. */ #ifdef TCP_SIGNATURE if (optp || (tp->t_flags & TF_SIGNATURE)) #else if (optp) #endif if (tcp_dooptions(tp, optp, optlen, th, m, iphlen, &opti, m->m_pkthdr.ph_rtableid)) goto drop; if (opti.ts_present && opti.ts_ecr) { int rtt_test; /* subtract out the tcp timestamp modulator */ opti.ts_ecr -= tp->ts_modulate; /* make sure ts_ecr is sensible */ rtt_test = tcp_now - opti.ts_ecr; if (rtt_test < 0 || rtt_test > TCP_RTT_MAX) opti.ts_ecr = 0; } #ifdef TCP_ECN /* if congestion experienced, set ECE bit in subsequent packets. */ if ((iptos & IPTOS_ECN_MASK) == IPTOS_ECN_CE) { tp->t_flags |= TF_RCVD_CE; tcpstat_inc(tcps_ecn_rcvce); } #endif /* * Header prediction: check for the two common cases * of a uni-directional data xfer. If the packet has * no control flags, is in-sequence, the window didn't * change and we're not retransmitting, it's a * candidate. If the length is zero and the ack moved * forward, we're the sender side of the xfer. Just * free the data acked & wake any higher level process * that was blocked waiting for space. If the length * is non-zero and the ack didn't move, we're the * receiver side. If we're getting packets in-order * (the reassembly queue is empty), add the data to * the socket buffer and note that we need a delayed ack. */ if (tp->t_state == TCPS_ESTABLISHED && #ifdef TCP_ECN (tiflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ECE|TH_CWR|TH_ACK)) == TH_ACK && #else (tiflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK && #endif (!opti.ts_present || TSTMP_GEQ(opti.ts_val, tp->ts_recent)) && th->th_seq == tp->rcv_nxt && tiwin && tiwin == tp->snd_wnd && tp->snd_nxt == tp->snd_max) { /* * If last ACK falls within this segment's sequence numbers, * record the timestamp. * Fix from Braden, see Stevens p. 870 */ if (opti.ts_present && SEQ_LEQ(th->th_seq, tp->last_ack_sent)) { tp->ts_recent_age = tcp_now; tp->ts_recent = opti.ts_val; } if (tlen == 0) { if (SEQ_GT(th->th_ack, tp->snd_una) && SEQ_LEQ(th->th_ack, tp->snd_max) && tp->snd_cwnd >= tp->snd_wnd && tp->t_dupacks == 0) { /* * this is a pure ack for outstanding data. */ tcpstat_inc(tcps_predack); if (opti.ts_present && opti.ts_ecr) tcp_xmit_timer(tp, tcp_now - opti.ts_ecr); else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq)) tcp_xmit_timer(tp, tcp_now - tp->t_rtttime); acked = th->th_ack - tp->snd_una; tcpstat_pkt(tcps_rcvackpack, tcps_rcvackbyte, acked); ND6_HINT(tp); sbdrop(so, &so->so_snd, acked); /* * If we had a pending ICMP message that * refers to data that have just been * acknowledged, disregard the recorded ICMP * message. */ if ((tp->t_flags & TF_PMTUD_PEND) && SEQ_GT(th->th_ack, tp->t_pmtud_th_seq)) tp->t_flags &= ~TF_PMTUD_PEND; /* * Keep track of the largest chunk of data * acknowledged since last PMTU update */ if (tp->t_pmtud_mss_acked < acked) tp->t_pmtud_mss_acked = acked; tp->snd_una = th->th_ack; /* * We want snd_last to track snd_una so * as to avoid sequence wraparound problems * for very large transfers. */ #ifdef TCP_ECN if (SEQ_GT(tp->snd_una, tp->snd_last)) #endif tp->snd_last = tp->snd_una; m_freem(m); /* * If all outstanding data are acked, stop * retransmit timer, otherwise restart timer * using current (possibly backed-off) value. * If process is waiting for space, * wakeup/selwakeup/signal. If data * are ready to send, let tcp_output * decide between more output or persist. */ if (tp->snd_una == tp->snd_max) TCP_TIMER_DISARM(tp, TCPT_REXMT); else if (TCP_TIMER_ISARMED(tp, TCPT_PERSIST) == 0) TCP_TIMER_ARM(tp, TCPT_REXMT, tp->t_rxtcur); tcp_update_sndspace(tp); if (sb_notify(so, &so->so_snd)) { tp->t_flags |= TF_BLOCKOUTPUT; sowwakeup(so); tp->t_flags &= ~TF_BLOCKOUTPUT; } if (so->so_snd.sb_cc || tp->t_flags & TF_NEEDOUTPUT) (void) tcp_output(tp); return IPPROTO_DONE; } } else if (th->th_ack == tp->snd_una && TAILQ_EMPTY(&tp->t_segq) && tlen <= sbspace(so, &so->so_rcv)) { /* * This is a pure, in-sequence data packet * with nothing on the reassembly queue and * we have enough buffer space to take it. */ /* Clean receiver SACK report if present */ if (tp->sack_enable && tp->rcv_numsacks) tcp_clean_sackreport(tp); tcpstat_inc(tcps_preddat); tp->rcv_nxt += tlen; tcpstat_pkt(tcps_rcvpack, tcps_rcvbyte, tlen); ND6_HINT(tp); TCP_SETUP_ACK(tp, tiflags, m); /* * Drop TCP, IP headers and TCP options then add data * to socket buffer. */ if (so->so_state & SS_CANTRCVMORE) m_freem(m); else { if (opti.ts_present && opti.ts_ecr) { if (tp->rfbuf_ts < opti.ts_ecr && opti.ts_ecr - tp->rfbuf_ts < hz) { tcp_update_rcvspace(tp); /* Start over with next RTT. */ tp->rfbuf_cnt = 0; tp->rfbuf_ts = 0; } else tp->rfbuf_cnt += tlen; } m_adj(m, iphlen + off); sbappendstream(so, &so->so_rcv, m); } tp->t_flags |= TF_BLOCKOUTPUT; sorwakeup(so); tp->t_flags &= ~TF_BLOCKOUTPUT; if (tp->t_flags & (TF_ACKNOW|TF_NEEDOUTPUT)) (void) tcp_output(tp); return IPPROTO_DONE; } } /* * Compute mbuf offset to TCP data segment. */ hdroptlen = iphlen + off; /* * Calculate amount of space in receive window, * and then do TCP input processing. * Receive window is amount of space in rcv queue, * but not less than advertised window. */ { int win; win = sbspace(so, &so->so_rcv); if (win < 0) win = 0; tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt)); } /* Reset receive buffer auto scaling when not in bulk receive mode. */ tp->rfbuf_cnt = 0; tp->rfbuf_ts = 0; switch (tp->t_state) { /* * If the state is SYN_RECEIVED: * if seg contains SYN/ACK, send an RST. * if seg contains an ACK, but not for our SYN/ACK, send an RST */ case TCPS_SYN_RECEIVED: if (tiflags & TH_ACK) { if (tiflags & TH_SYN) { tcpstat_inc(tcps_badsyn); goto dropwithreset; } if (SEQ_LEQ(th->th_ack, tp->snd_una) || SEQ_GT(th->th_ack, tp->snd_max)) goto dropwithreset; } break; /* * If the state is SYN_SENT: * if seg contains an ACK, but not for our SYN, drop the input. * if seg contains a RST, then drop the connection. * if seg does not contain SYN, then drop it. * Otherwise this is an acceptable SYN segment * initialize tp->rcv_nxt and tp->irs * if seg contains ack then advance tp->snd_una * if SYN has been acked change to ESTABLISHED else SYN_RCVD state * arrange for segment to be acked (eventually) * continue processing rest of data/controls, beginning with URG */ case TCPS_SYN_SENT: if ((tiflags & TH_ACK) && (SEQ_LEQ(th->th_ack, tp->iss) || SEQ_GT(th->th_ack, tp->snd_max))) goto dropwithreset; if (tiflags & TH_RST) { #ifdef TCP_ECN /* if ECN is enabled, fall back to non-ecn at rexmit */ if (tcp_do_ecn && !(tp->t_flags & TF_DISABLE_ECN)) goto drop; #endif if (tiflags & TH_ACK) tp = tcp_drop(tp, ECONNREFUSED); goto drop; } if ((tiflags & TH_SYN) == 0) goto drop; if (tiflags & TH_ACK) { tp->snd_una = th->th_ack; if (SEQ_LT(tp->snd_nxt, tp->snd_una)) tp->snd_nxt = tp->snd_una; } TCP_TIMER_DISARM(tp, TCPT_REXMT); tp->irs = th->th_seq; tcp_mss(tp, opti.maxseg); /* Reset initial window to 1 segment for retransmit */ if (tp->t_rxtshift > 0) tp->snd_cwnd = tp->t_maxseg; tcp_rcvseqinit(tp); tp->t_flags |= TF_ACKNOW; /* * If we've sent a SACK_PERMITTED option, and the peer * also replied with one, then TF_SACK_PERMIT should have * been set in tcp_dooptions(). If it was not, disable SACKs. */ if (tp->sack_enable) tp->sack_enable = tp->t_flags & TF_SACK_PERMIT; #ifdef TCP_ECN /* * if ECE is set but CWR is not set for SYN-ACK, or * both ECE and CWR are set for simultaneous open, * peer is ECN capable. */ if (tcp_do_ecn) { switch (tiflags & (TH_ACK|TH_ECE|TH_CWR)) { case TH_ACK|TH_ECE: case TH_ECE|TH_CWR: tp->t_flags |= TF_ECN_PERMIT; tiflags &= ~(TH_ECE|TH_CWR); tcpstat_inc(tcps_ecn_accepts); } } #endif if (tiflags & TH_ACK && SEQ_GT(tp->snd_una, tp->iss)) { tcpstat_inc(tcps_connects); tp->t_flags |= TF_BLOCKOUTPUT; soisconnected(so); tp->t_flags &= ~TF_BLOCKOUTPUT; tp->t_state = TCPS_ESTABLISHED; TCP_TIMER_ARM(tp, TCPT_KEEP, tcp_keepidle); /* Do window scaling on this connection? */ if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) == (TF_RCVD_SCALE|TF_REQ_SCALE)) { tp->snd_scale = tp->requested_s_scale; tp->rcv_scale = tp->request_r_scale; } tcp_flush_queue(tp); /* * if we didn't have to retransmit the SYN, * use its rtt as our initial srtt & rtt var. */ if (tp->t_rtttime) tcp_xmit_timer(tp, tcp_now - tp->t_rtttime); /* * Since new data was acked (the SYN), open the * congestion window by one MSS. We do this * here, because we won't go through the normal * ACK processing below. And since this is the * start of the connection, we know we are in * the exponential phase of slow-start. */ tp->snd_cwnd += tp->t_maxseg; } else tp->t_state = TCPS_SYN_RECEIVED; #if 0 trimthenstep6: #endif /* * Advance th->th_seq to correspond to first data byte. * If data, trim to stay within window, * dropping FIN if necessary. */ th->th_seq++; if (tlen > tp->rcv_wnd) { todrop = tlen - tp->rcv_wnd; m_adj(m, -todrop); tlen = tp->rcv_wnd; tiflags &= ~TH_FIN; tcpstat_pkt(tcps_rcvpackafterwin, tcps_rcvbyteafterwin, todrop); } tp->snd_wl1 = th->th_seq - 1; tp->rcv_up = th->th_seq; goto step6; /* * If a new connection request is received while in TIME_WAIT, * drop the old connection and start over if the if the * timestamp or the sequence numbers are above the previous * ones. */ case TCPS_TIME_WAIT: if (((tiflags & (TH_SYN|TH_ACK)) == TH_SYN) && ((opti.ts_present && TSTMP_LT(tp->ts_recent, opti.ts_val)) || SEQ_GT(th->th_seq, tp->rcv_nxt))) { #if NPF > 0 /* * The socket will be recreated but the new state * has already been linked to the socket. Remove the * link between old socket and new state. */ pf_inp_unlink(inp); #endif /* * Advance the iss by at least 32768, but * clear the msb in order to make sure * that SEG_LT(snd_nxt, iss). */ iss = tp->snd_nxt + ((arc4random() & 0x7fffffff) | 0x8000); reuse = &iss; tp = tcp_close(tp); inp = NULL; goto findpcb; } } /* * States other than LISTEN or SYN_SENT. * First check timestamp, if present. * Then check that at least some bytes of segment are within * receive window. If segment begins before rcv_nxt, * drop leading data (and SYN); if nothing left, just ack. * * RFC 1323 PAWS: If we have a timestamp reply on this segment * and it's less than opti.ts_recent, drop it. */ if (opti.ts_present && (tiflags & TH_RST) == 0 && tp->ts_recent && TSTMP_LT(opti.ts_val, tp->ts_recent)) { /* Check to see if ts_recent is over 24 days old. */ if ((int)(tcp_now - tp->ts_recent_age) > TCP_PAWS_IDLE) { /* * Invalidate ts_recent. If this segment updates * ts_recent, the age will be reset later and ts_recent * will get a valid value. If it does not, setting * ts_recent to zero will at least satisfy the * requirement that zero be placed in the timestamp * echo reply when ts_recent isn't valid. The * age isn't reset until we get a valid ts_recent * because we don't want out-of-order segments to be * dropped when ts_recent is old. */ tp->ts_recent = 0; } else { tcpstat_pkt(tcps_rcvduppack, tcps_rcvdupbyte, tlen); tcpstat_inc(tcps_pawsdrop); if (tlen) goto dropafterack; goto drop; } } todrop = tp->rcv_nxt - th->th_seq; if (todrop > 0) { if (tiflags & TH_SYN) { tiflags &= ~TH_SYN; th->th_seq++; if (th->th_urp > 1) th->th_urp--; else tiflags &= ~TH_URG; todrop--; } if (todrop > tlen || (todrop == tlen && (tiflags & TH_FIN) == 0)) { /* * Any valid FIN must be to the left of the * window. At this point, FIN must be a * duplicate or out-of-sequence, so drop it. */ tiflags &= ~TH_FIN; /* * Send ACK to resynchronize, and drop any data, * but keep on processing for RST or ACK. */ tp->t_flags |= TF_ACKNOW; todrop = tlen; tcpstat_pkt(tcps_rcvduppack, tcps_rcvdupbyte, todrop); } else { tcpstat_pkt(tcps_rcvpartduppack, tcps_rcvpartdupbyte, todrop); } hdroptlen += todrop; /* drop from head afterwards */ th->th_seq += todrop; tlen -= todrop; if (th->th_urp > todrop) th->th_urp -= todrop; else { tiflags &= ~TH_URG; th->th_urp = 0; } } /* * If new data are received on a connection after the * user processes are gone, then RST the other end. */ if ((so->so_state & SS_NOFDREF) && tp->t_state > TCPS_CLOSE_WAIT && tlen) { tp = tcp_close(tp); tcpstat_inc(tcps_rcvafterclose); goto dropwithreset; } /* * If segment ends after window, drop trailing data * (and PUSH and FIN); if nothing left, just ACK. */ todrop = (th->th_seq + tlen) - (tp->rcv_nxt+tp->rcv_wnd); if (todrop > 0) { tcpstat_inc(tcps_rcvpackafterwin); if (todrop >= tlen) { tcpstat_add(tcps_rcvbyteafterwin, tlen); /* * If window is closed can only take segments at * window edge, and have to drop data and PUSH from * incoming segments. Continue processing, but * remember to ack. Otherwise, drop segment * and ack. */ if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) { tp->t_flags |= TF_ACKNOW; tcpstat_inc(tcps_rcvwinprobe); } else goto dropafterack; } else tcpstat_add(tcps_rcvbyteafterwin, todrop); m_adj(m, -todrop); tlen -= todrop; tiflags &= ~(TH_PUSH|TH_FIN); } /* * If last ACK falls within this segment's sequence numbers, * record its timestamp if it's more recent. * NOTE that the test is modified according to the latest * proposal of the tcplw@cray.com list (Braden 1993/04/26). */ if (opti.ts_present && TSTMP_GEQ(opti.ts_val, tp->ts_recent) && SEQ_LEQ(th->th_seq, tp->last_ack_sent)) { tp->ts_recent_age = tcp_now; tp->ts_recent = opti.ts_val; } /* * If the RST bit is set examine the state: * SYN_RECEIVED STATE: * If passive open, return to LISTEN state. * If active open, inform user that connection was refused. * ESTABLISHED, FIN_WAIT_1, FIN_WAIT2, CLOSE_WAIT STATES: * Inform user that connection was reset, and close tcb. * CLOSING, LAST_ACK, TIME_WAIT STATES * Close the tcb. */ if (tiflags & TH_RST) { if (th->th_seq != tp->last_ack_sent && th->th_seq != tp->rcv_nxt && th->th_seq != (tp->rcv_nxt + 1)) goto drop; switch (tp->t_state) { case TCPS_SYN_RECEIVED: #ifdef TCP_ECN /* if ECN is enabled, fall back to non-ecn at rexmit */ if (tcp_do_ecn && !(tp->t_flags & TF_DISABLE_ECN)) goto drop; #endif so->so_error = ECONNREFUSED; goto close; case TCPS_ESTABLISHED: case TCPS_FIN_WAIT_1: case TCPS_FIN_WAIT_2: case TCPS_CLOSE_WAIT: so->so_error = ECONNRESET; close: tp->t_state = TCPS_CLOSED; tcpstat_inc(tcps_drops); tp = tcp_close(tp); goto drop; case TCPS_CLOSING: case TCPS_LAST_ACK: case TCPS_TIME_WAIT: tp = tcp_close(tp); goto drop; } } /* * If a SYN is in the window, then this is an * error and we ACK and drop the packet. */ if (tiflags & TH_SYN) goto dropafterack_ratelim; /* * If the ACK bit is off we drop the segment and return. */ if ((tiflags & TH_ACK) == 0) { if (tp->t_flags & TF_ACKNOW) goto dropafterack; else goto drop; } /* * Ack processing. */ switch (tp->t_state) { /* * In SYN_RECEIVED state, the ack ACKs our SYN, so enter * ESTABLISHED state and continue processing. * The ACK was checked above. */ case TCPS_SYN_RECEIVED: tcpstat_inc(tcps_connects); tp->t_flags |= TF_BLOCKOUTPUT; soisconnected(so); tp->t_flags &= ~TF_BLOCKOUTPUT; tp->t_state = TCPS_ESTABLISHED; TCP_TIMER_ARM(tp, TCPT_KEEP, tcp_keepidle); /* Do window scaling? */ if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) == (TF_RCVD_SCALE|TF_REQ_SCALE)) { tp->snd_scale = tp->requested_s_scale; tp->rcv_scale = tp->request_r_scale; tiwin = th->th_win << tp->snd_scale; } tcp_flush_queue(tp); tp->snd_wl1 = th->th_seq - 1; /* fall into ... */ /* * In ESTABLISHED state: drop duplicate ACKs; ACK out of range * ACKs. If the ack is in the range * tp->snd_una < th->th_ack <= tp->snd_max * then advance tp->snd_una to th->th_ack and drop * data from the retransmission queue. If this ACK reflects * more up to date window information we update our window information. */ case TCPS_ESTABLISHED: case TCPS_FIN_WAIT_1: case TCPS_FIN_WAIT_2: case TCPS_CLOSE_WAIT: case TCPS_CLOSING: case TCPS_LAST_ACK: case TCPS_TIME_WAIT: #ifdef TCP_ECN /* * if we receive ECE and are not already in recovery phase, * reduce cwnd by half but don't slow-start. * advance snd_last to snd_max not to reduce cwnd again * until all outstanding packets are acked. */ if (tcp_do_ecn && (tiflags & TH_ECE)) { if ((tp->t_flags & TF_ECN_PERMIT) && SEQ_GEQ(tp->snd_una, tp->snd_last)) { u_int win; win = min(tp->snd_wnd, tp->snd_cwnd) / tp->t_maxseg; if (win > 1) { tp->snd_ssthresh = win / 2 * tp->t_maxseg; tp->snd_cwnd = tp->snd_ssthresh; tp->snd_last = tp->snd_max; tp->t_flags |= TF_SEND_CWR; tcpstat_inc(tcps_cwr_ecn); } } tcpstat_inc(tcps_ecn_rcvece); } /* * if we receive CWR, we know that the peer has reduced * its congestion window. stop sending ecn-echo. */ if ((tiflags & TH_CWR)) { tp->t_flags &= ~TF_RCVD_CE; tcpstat_inc(tcps_ecn_rcvcwr); } #endif /* TCP_ECN */ if (SEQ_LEQ(th->th_ack, tp->snd_una)) { /* * Duplicate/old ACK processing. * Increments t_dupacks: * Pure duplicate (same seq/ack/window, no data) * Doesn't affect t_dupacks: * Data packets. * Normal window updates (window opens) * Resets t_dupacks: * New data ACKed. * Window shrinks * Old ACK */ if (tlen) { /* Drop very old ACKs unless th_seq matches */ if (th->th_seq != tp->rcv_nxt && SEQ_LT(th->th_ack, tp->snd_una - tp->max_sndwnd)) { tcpstat_inc(tcps_rcvacktooold); goto drop; } break; } /* * If we get an old ACK, there is probably packet * reordering going on. Be conservative and reset * t_dupacks so that we are less aggressive in * doing a fast retransmit. */ if (th->th_ack != tp->snd_una) { tp->t_dupacks = 0; break; } if (tiwin == tp->snd_wnd) { tcpstat_inc(tcps_rcvdupack); /* * If we have outstanding data (other than * a window probe), this is a completely * duplicate ack (ie, window info didn't * change), the ack is the biggest we've * seen and we've seen exactly our rexmt * threshold of them, assume a packet * has been dropped and retransmit it. * Kludge snd_nxt & the congestion * window so we send only this one * packet. * * We know we're losing at the current * window size so do congestion avoidance * (set ssthresh to half the current window * and pull our congestion window back to * the new ssthresh). * * Dup acks mean that packets have left the * network (they're now cached at the receiver) * so bump cwnd by the amount in the receiver * to keep a constant cwnd packets in the * network. */ if (TCP_TIMER_ISARMED(tp, TCPT_REXMT) == 0) tp->t_dupacks = 0; else if (++tp->t_dupacks == tcprexmtthresh) { tcp_seq onxt = tp->snd_nxt; u_long win = ulmin(tp->snd_wnd, tp->snd_cwnd) / 2 / tp->t_maxseg; if (SEQ_LT(th->th_ack, tp->snd_last)){ /* * False fast retx after * timeout. Do not cut window. */ tp->t_dupacks = 0; goto drop; } if (win < 2) win = 2; tp->snd_ssthresh = win * tp->t_maxseg; tp->snd_last = tp->snd_max; if (tp->sack_enable) { TCP_TIMER_DISARM(tp, TCPT_REXMT); tp->t_rtttime = 0; #ifdef TCP_ECN tp->t_flags |= TF_SEND_CWR; #endif tcpstat_inc(tcps_cwr_frecovery); tcpstat_inc(tcps_sack_recovery_episode); /* * tcp_output() will send * oldest SACK-eligible rtx. */ (void) tcp_output(tp); tp->snd_cwnd = tp->snd_ssthresh+ tp->t_maxseg * tp->t_dupacks; goto drop; } TCP_TIMER_DISARM(tp, TCPT_REXMT); tp->t_rtttime = 0; tp->snd_nxt = th->th_ack; tp->snd_cwnd = tp->t_maxseg; #ifdef TCP_ECN tp->t_flags |= TF_SEND_CWR; #endif tcpstat_inc(tcps_cwr_frecovery); tcpstat_inc(tcps_sndrexmitfast); (void) tcp_output(tp); tp->snd_cwnd = tp->snd_ssthresh + tp->t_maxseg * tp->t_dupacks; if (SEQ_GT(onxt, tp->snd_nxt)) tp->snd_nxt = onxt; goto drop; } else if (tp->t_dupacks > tcprexmtthresh) { tp->snd_cwnd += tp->t_maxseg; (void) tcp_output(tp); goto drop; } } else if (tiwin < tp->snd_wnd) { /* * The window was retracted! Previous dup * ACKs may have been due to packets arriving * after the shrunken window, not a missing * packet, so play it safe and reset t_dupacks */ tp->t_dupacks = 0; } break; } /* * If the congestion window was inflated to account * for the other side's cached packets, retract it. */ if (tp->t_dupacks >= tcprexmtthresh) { /* Check for a partial ACK */ if (SEQ_LT(th->th_ack, tp->snd_last)) { if (tp->sack_enable) tcp_sack_partialack(tp, th); else tcp_newreno_partialack(tp, th); } else { /* Out of fast recovery */ tp->snd_cwnd = tp->snd_ssthresh; if (tcp_seq_subtract(tp->snd_max, th->th_ack) < tp->snd_ssthresh) tp->snd_cwnd = tcp_seq_subtract(tp->snd_max, th->th_ack); tp->t_dupacks = 0; } } else { /* * Reset the duplicate ACK counter if we * were not in fast recovery. */ tp->t_dupacks = 0; } if (SEQ_GT(th->th_ack, tp->snd_max)) { tcpstat_inc(tcps_rcvacktoomuch); goto dropafterack_ratelim; } acked = th->th_ack - tp->snd_una; tcpstat_pkt(tcps_rcvackpack, tcps_rcvackbyte, acked); /* * If we have a timestamp reply, update smoothed * round trip time. If no timestamp is present but * transmit timer is running and timed sequence * number was acked, update smoothed round trip time. * Since we now have an rtt measurement, cancel the * timer backoff (cf., Phil Karn's retransmit alg.). * Recompute the initial retransmit timer. */ if (opti.ts_present && opti.ts_ecr) tcp_xmit_timer(tp, tcp_now - opti.ts_ecr); else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq)) tcp_xmit_timer(tp, tcp_now - tp->t_rtttime); /* * If all outstanding data is acked, stop retransmit * timer and remember to restart (more output or persist). * If there is more data to be acked, restart retransmit * timer, using current (possibly backed-off) value. */ if (th->th_ack == tp->snd_max) { TCP_TIMER_DISARM(tp, TCPT_REXMT); tp->t_flags |= TF_NEEDOUTPUT; } else if (TCP_TIMER_ISARMED(tp, TCPT_PERSIST) == 0) TCP_TIMER_ARM(tp, TCPT_REXMT, tp->t_rxtcur); /* * When new data is acked, open the congestion window. * If the window gives us less than ssthresh packets * in flight, open exponentially (maxseg per packet). * Otherwise open linearly: maxseg per window * (maxseg^2 / cwnd per packet). */ { u_int cw = tp->snd_cwnd; u_int incr = tp->t_maxseg; if (cw > tp->snd_ssthresh) incr = incr * incr / cw; if (tp->t_dupacks < tcprexmtthresh) tp->snd_cwnd = ulmin(cw + incr, TCP_MAXWIN << tp->snd_scale); } ND6_HINT(tp); if (acked > so->so_snd.sb_cc) { tp->snd_wnd -= so->so_snd.sb_cc; sbdrop(so, &so->so_snd, (int)so->so_snd.sb_cc); ourfinisacked = 1; } else { sbdrop(so, &so->so_snd, acked); tp->snd_wnd -= acked; ourfinisacked = 0; } tcp_update_sndspace(tp); if (sb_notify(so, &so->so_snd)) { tp->t_flags |= TF_BLOCKOUTPUT; sowwakeup(so); tp->t_flags &= ~TF_BLOCKOUTPUT; } /* * If we had a pending ICMP message that referred to data * that have just been acknowledged, disregard the recorded * ICMP message. */ if ((tp->t_flags & TF_PMTUD_PEND) && SEQ_GT(th->th_ack, tp->t_pmtud_th_seq)) tp->t_flags &= ~TF_PMTUD_PEND; /* * Keep track of the largest chunk of data acknowledged * since last PMTU update */ if (tp->t_pmtud_mss_acked < acked) tp->t_pmtud_mss_acked = acked; tp->snd_una = th->th_ack; #ifdef TCP_ECN /* sync snd_last with snd_una */ if (SEQ_GT(tp->snd_una, tp->snd_last)) tp->snd_last = tp->snd_una; #endif if (SEQ_LT(tp->snd_nxt, tp->snd_una)) tp->snd_nxt = tp->snd_una; switch (tp->t_state) { /* * In FIN_WAIT_1 STATE in addition to the processing * for the ESTABLISHED state if our FIN is now acknowledged * then enter FIN_WAIT_2. */ case TCPS_FIN_WAIT_1: if (ourfinisacked) { /* * If we can't receive any more * data, then closing user can proceed. * Starting the timer is contrary to the * specification, but if we don't get a FIN * we'll hang forever. */ if (so->so_state & SS_CANTRCVMORE) { tp->t_flags |= TF_BLOCKOUTPUT; soisdisconnected(so); tp->t_flags &= ~TF_BLOCKOUTPUT; TCP_TIMER_ARM(tp, TCPT_2MSL, tcp_maxidle); } tp->t_state = TCPS_FIN_WAIT_2; } break; /* * In CLOSING STATE in addition to the processing for * the ESTABLISHED state if the ACK acknowledges our FIN * then enter the TIME-WAIT state, otherwise ignore * the segment. */ case TCPS_CLOSING: if (ourfinisacked) { tp->t_state = TCPS_TIME_WAIT; tcp_canceltimers(tp); TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * TCPTV_MSL); tp->t_flags |= TF_BLOCKOUTPUT; soisdisconnected(so); tp->t_flags &= ~TF_BLOCKOUTPUT; } break; /* * In LAST_ACK, we may still be waiting for data to drain * and/or to be acked, as well as for the ack of our FIN. * If our FIN is now acknowledged, delete the TCB, * enter the closed state and return. */ case TCPS_LAST_ACK: if (ourfinisacked) { tp = tcp_close(tp); goto drop; } break; /* * In TIME_WAIT state the only thing that should arrive * is a retransmission of the remote FIN. Acknowledge * it and restart the finack timer. */ case TCPS_TIME_WAIT: TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * TCPTV_MSL); goto dropafterack; } } step6: /* * Update window information. * Don't look at window if no ACK: TAC's send garbage on first SYN. */ if ((tiflags & TH_ACK) && (SEQ_LT(tp->snd_wl1, th->th_seq) || (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) || (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) { /* keep track of pure window updates */ if (tlen == 0 && tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd) tcpstat_inc(tcps_rcvwinupd); tp->snd_wnd = tiwin; tp->snd_wl1 = th->th_seq; tp->snd_wl2 = th->th_ack; if (tp->snd_wnd > tp->max_sndwnd) tp->max_sndwnd = tp->snd_wnd; tp->t_flags |= TF_NEEDOUTPUT; } /* * Process segments with URG. */ if ((tiflags & TH_URG) && th->th_urp && TCPS_HAVERCVDFIN(tp->t_state) == 0) { /* * This is a kludge, but if we receive and accept * random urgent pointers, we'll crash in * soreceive. It's hard to imagine someone * actually wanting to send this much urgent data. */ if (th->th_urp + so->so_rcv.sb_cc > sb_max) { th->th_urp = 0; /* XXX */ tiflags &= ~TH_URG; /* XXX */ goto dodata; /* XXX */ } /* * If this segment advances the known urgent pointer, * then mark the data stream. This should not happen * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since * a FIN has been received from the remote side. * In these states we ignore the URG. * * According to RFC961 (Assigned Protocols), * the urgent pointer points to the last octet * of urgent data. We continue, however, * to consider it to indicate the first octet * of data past the urgent section as the original * spec states (in one of two places). */ if (SEQ_GT(th->th_seq+th->th_urp, tp->rcv_up)) { tp->rcv_up = th->th_seq + th->th_urp; so->so_oobmark = so->so_rcv.sb_cc + (tp->rcv_up - tp->rcv_nxt) - 1; if (so->so_oobmark == 0) so->so_state |= SS_RCVATMARK; sohasoutofband(so); tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA); } /* * Remove out of band data so doesn't get presented to user. * This can happen independent of advancing the URG pointer, * but if two URG's are pending at once, some out-of-band * data may creep in... ick. */ if (th->th_urp <= (u_int16_t) tlen && (so->so_options & SO_OOBINLINE) == 0) tcp_pulloutofband(so, th->th_urp, m, hdroptlen); } else /* * If no out of band data is expected, * pull receive urgent pointer along * with the receive window. */ if (SEQ_GT(tp->rcv_nxt, tp->rcv_up)) tp->rcv_up = tp->rcv_nxt; dodata: /* XXX */ /* * Process the segment text, merging it into the TCP sequencing queue, * and arranging for acknowledgment of receipt if necessary. * This process logically involves adjusting tp->rcv_wnd as data * is presented to the user (this happens in tcp_usrreq.c, * case PRU_RCVD). If a FIN has already been received on this * connection then we just ignore the text. */ if ((tlen || (tiflags & TH_FIN)) && TCPS_HAVERCVDFIN(tp->t_state) == 0) { tcp_seq laststart = th->th_seq; tcp_seq lastend = th->th_seq + tlen; if (th->th_seq == tp->rcv_nxt && TAILQ_EMPTY(&tp->t_segq) && tp->t_state == TCPS_ESTABLISHED) { TCP_SETUP_ACK(tp, tiflags, m); tp->rcv_nxt += tlen; tiflags = th->th_flags & TH_FIN; tcpstat_pkt(tcps_rcvpack, tcps_rcvbyte, tlen); ND6_HINT(tp); if (so->so_state & SS_CANTRCVMORE) m_freem(m); else { m_adj(m, hdroptlen); sbappendstream(so, &so->so_rcv, m); } tp->t_flags |= TF_BLOCKOUTPUT; sorwakeup(so); tp->t_flags &= ~TF_BLOCKOUTPUT; } else { m_adj(m, hdroptlen); tiflags = tcp_reass(tp, th, m, &tlen); tp->t_flags |= TF_ACKNOW; } if (tp->sack_enable) tcp_update_sack_list(tp, laststart, lastend); /* * variable len never referenced again in modern BSD, * so why bother computing it ?? */ #if 0 /* * Note the amount of data that peer has sent into * our window, in order to estimate the sender's * buffer size. */ len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt); #endif /* 0 */ } else { m_freem(m); tiflags &= ~TH_FIN; } /* * If FIN is received ACK the FIN and let the user know * that the connection is closing. Ignore a FIN received before * the connection is fully established. */ if ((tiflags & TH_FIN) && TCPS_HAVEESTABLISHED(tp->t_state)) { if (TCPS_HAVERCVDFIN(tp->t_state) == 0) { tp->t_flags |= TF_BLOCKOUTPUT; socantrcvmore(so); tp->t_flags &= ~TF_BLOCKOUTPUT; tp->t_flags |= TF_ACKNOW; tp->rcv_nxt++; } switch (tp->t_state) { /* * In ESTABLISHED STATE enter the CLOSE_WAIT state. */ case TCPS_ESTABLISHED: tp->t_state = TCPS_CLOSE_WAIT; break; /* * If still in FIN_WAIT_1 STATE FIN has not been acked so * enter the CLOSING state. */ case TCPS_FIN_WAIT_1: tp->t_state = TCPS_CLOSING; break; /* * In FIN_WAIT_2 state enter the TIME_WAIT state, * starting the time-wait timer, turning off the other * standard timers. */ case TCPS_FIN_WAIT_2: tp->t_state = TCPS_TIME_WAIT; tcp_canceltimers(tp); TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * TCPTV_MSL); tp->t_flags |= TF_BLOCKOUTPUT; soisdisconnected(so); tp->t_flags &= ~TF_BLOCKOUTPUT; break; /* * In TIME_WAIT state restart the 2 MSL time_wait timer. */ case TCPS_TIME_WAIT: TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * TCPTV_MSL); break; } } if (otp) tcp_trace(TA_INPUT, ostate, tp, otp, saveti, 0, tlen); /* * Return any desired output. */ if (tp->t_flags & (TF_ACKNOW|TF_NEEDOUTPUT)) (void) tcp_output(tp); return IPPROTO_DONE; badsyn: /* * Received a bad SYN. Increment counters and dropwithreset. */ tcpstat_inc(tcps_badsyn); tp = NULL; goto dropwithreset; dropafterack_ratelim: if (ppsratecheck(&tcp_ackdrop_ppslim_last, &tcp_ackdrop_ppslim_count, tcp_ackdrop_ppslim) == 0) { /* XXX stat */ goto drop; } /* ...fall into dropafterack... */ dropafterack: /* * Generate an ACK dropping incoming segment if it occupies * sequence space, where the ACK reflects our state. */ if (tiflags & TH_RST) goto drop; m_freem(m); tp->t_flags |= TF_ACKNOW; (void) tcp_output(tp); return IPPROTO_DONE; dropwithreset_ratelim: /* * We may want to rate-limit RSTs in certain situations, * particularly if we are sending an RST in response to * an attempt to connect to or otherwise communicate with * a port for which we have no socket. */ if (ppsratecheck(&tcp_rst_ppslim_last, &tcp_rst_ppslim_count, tcp_rst_ppslim) == 0) { /* XXX stat */ goto drop; } /* ...fall into dropwithreset... */ dropwithreset: /* * Generate a RST, dropping incoming segment. * Make ACK acceptable to originator of segment. * Don't bother to respond to RST. */ if (tiflags & TH_RST) goto drop; if (tiflags & TH_ACK) { tcp_respond(tp, mtod(m, caddr_t), th, (tcp_seq)0, th->th_ack, TH_RST, m->m_pkthdr.ph_rtableid); } else { if (tiflags & TH_SYN) tlen++; tcp_respond(tp, mtod(m, caddr_t), th, th->th_seq + tlen, (tcp_seq)0, TH_RST|TH_ACK, m->m_pkthdr.ph_rtableid); } m_freem(m); return IPPROTO_DONE; drop: /* * Drop space held by incoming segment and return. */ if (otp) tcp_trace(TA_DROP, ostate, tp, otp, saveti, 0, tlen); m_freem(m); return IPPROTO_DONE; } int tcp_dooptions(struct tcpcb *tp, u_char *cp, int cnt, struct tcphdr *th, struct mbuf *m, int iphlen, struct tcp_opt_info *oi, u_int rtableid) { u_int16_t mss = 0; int opt, optlen; #ifdef TCP_SIGNATURE caddr_t sigp = NULL; struct tdb *tdb = NULL; #endif /* TCP_SIGNATURE */ for (; cp && cnt > 0; cnt -= optlen, cp += optlen) { opt = cp[0]; if (opt == TCPOPT_EOL) break; if (opt == TCPOPT_NOP) optlen = 1; else { if (cnt < 2) break; optlen = cp[1]; if (optlen < 2 || optlen > cnt) break; } switch (opt) { default: continue; case TCPOPT_MAXSEG: if (optlen != TCPOLEN_MAXSEG) continue; if (!(th->th_flags & TH_SYN)) continue; if (TCPS_HAVERCVDSYN(tp->t_state)) continue; memcpy(&mss, cp + 2, sizeof(mss)); mss = ntohs(mss); oi->maxseg = mss; break; case TCPOPT_WINDOW: if (optlen != TCPOLEN_WINDOW) continue; if (!(th->th_flags & TH_SYN)) continue; if (TCPS_HAVERCVDSYN(tp->t_state)) continue; tp->t_flags |= TF_RCVD_SCALE; tp->requested_s_scale = min(cp[2], TCP_MAX_WINSHIFT); break; case TCPOPT_TIMESTAMP: if (optlen != TCPOLEN_TIMESTAMP) continue; oi->ts_present = 1; memcpy(&oi->ts_val, cp + 2, sizeof(oi->ts_val)); oi->ts_val = ntohl(oi->ts_val); memcpy(&oi->ts_ecr, cp + 6, sizeof(oi->ts_ecr)); oi->ts_ecr = ntohl(oi->ts_ecr); if (!(th->th_flags & TH_SYN)) continue; if (TCPS_HAVERCVDSYN(tp->t_state)) continue; /* * A timestamp received in a SYN makes * it ok to send timestamp requests and replies. */ tp->t_flags |= TF_RCVD_TSTMP; tp->ts_recent = oi->ts_val; tp->ts_recent_age = tcp_now; break; case TCPOPT_SACK_PERMITTED: if (!tp->sack_enable || optlen!=TCPOLEN_SACK_PERMITTED) continue; if (!(th->th_flags & TH_SYN)) continue; if (TCPS_HAVERCVDSYN(tp->t_state)) continue; /* MUST only be set on SYN */ tp->t_flags |= TF_SACK_PERMIT; break; case TCPOPT_SACK: tcp_sack_option(tp, th, cp, optlen); break; #ifdef TCP_SIGNATURE case TCPOPT_SIGNATURE: if (optlen != TCPOLEN_SIGNATURE) continue; if (sigp && timingsafe_bcmp(sigp, cp + 2, 16)) return (-1); sigp = cp + 2; break; #endif /* TCP_SIGNATURE */ } } #ifdef TCP_SIGNATURE if (tp->t_flags & TF_SIGNATURE) { union sockaddr_union src, dst; memset(&src, 0, sizeof(union sockaddr_union)); memset(&dst, 0, sizeof(union sockaddr_union)); switch (tp->pf) { case 0: case AF_INET: src.sa.sa_len = sizeof(struct sockaddr_in); src.sa.sa_family = AF_INET; src.sin.sin_addr = mtod(m, struct ip *)->ip_src; dst.sa.sa_len = sizeof(struct sockaddr_in); dst.sa.sa_family = AF_INET; dst.sin.sin_addr = mtod(m, struct ip *)->ip_dst; break; #ifdef INET6 case AF_INET6: src.sa.sa_len = sizeof(struct sockaddr_in6); src.sa.sa_family = AF_INET6; src.sin6.sin6_addr = mtod(m, struct ip6_hdr *)->ip6_src; dst.sa.sa_len = sizeof(struct sockaddr_in6); dst.sa.sa_family = AF_INET6; dst.sin6.sin6_addr = mtod(m, struct ip6_hdr *)->ip6_dst; break; #endif /* INET6 */ } tdb = gettdbbysrcdst(rtable_l2(rtableid), 0, &src, &dst, IPPROTO_TCP); /* * We don't have an SA for this peer, so we turn off * TF_SIGNATURE on the listen socket */ if (tdb == NULL && tp->t_state == TCPS_LISTEN) tp->t_flags &= ~TF_SIGNATURE; } if ((sigp ? TF_SIGNATURE : 0) ^ (tp->t_flags & TF_SIGNATURE)) { tcpstat_inc(tcps_rcvbadsig); return (-1); } if (sigp) { char sig[16]; if (tdb == NULL) { tcpstat_inc(tcps_rcvbadsig); return (-1); } if (tcp_signature(tdb, tp->pf, m, th, iphlen, 1, sig) < 0) return (-1); if (timingsafe_bcmp(sig, sigp, 16)) { tcpstat_inc(tcps_rcvbadsig); return (-1); } tcpstat_inc(tcps_rcvgoodsig); } #endif /* TCP_SIGNATURE */ return (0); } u_long tcp_seq_subtract(u_long a, u_long b) { return ((long)(a - b)); } /* * This function is called upon receipt of new valid data (while not in header * prediction mode), and it updates the ordered list of sacks. */ void tcp_update_sack_list(struct tcpcb *tp, tcp_seq rcv_laststart, tcp_seq rcv_lastend) { /* * First reported block MUST be the most recent one. Subsequent * blocks SHOULD be in the order in which they arrived at the * receiver. These two conditions make the implementation fully * compliant with RFC 2018. */ int i, j = 0, count = 0, lastpos = -1; struct sackblk sack, firstsack, temp[MAX_SACK_BLKS]; /* First clean up current list of sacks */ for (i = 0; i < tp->rcv_numsacks; i++) { sack = tp->sackblks[i]; if (sack.start == 0 && sack.end == 0) { count++; /* count = number of blocks to be discarded */ continue; } if (SEQ_LEQ(sack.end, tp->rcv_nxt)) { tp->sackblks[i].start = tp->sackblks[i].end = 0; count++; } else { temp[j].start = tp->sackblks[i].start; temp[j++].end = tp->sackblks[i].end; } } tp->rcv_numsacks -= count; if (tp->rcv_numsacks == 0) { /* no sack blocks currently (fast path) */ tcp_clean_sackreport(tp); if (SEQ_LT(tp->rcv_nxt, rcv_laststart)) { /* ==> need first sack block */ tp->sackblks[0].start = rcv_laststart; tp->sackblks[0].end = rcv_lastend; tp->rcv_numsacks = 1; } return; } /* Otherwise, sack blocks are already present. */ for (i = 0; i < tp->rcv_numsacks; i++) tp->sackblks[i] = temp[i]; /* first copy back sack list */ if (SEQ_GEQ(tp->rcv_nxt, rcv_lastend)) return; /* sack list remains unchanged */ /* * From here, segment just received should be (part of) the 1st sack. * Go through list, possibly coalescing sack block entries. */ firstsack.start = rcv_laststart; firstsack.end = rcv_lastend; for (i = 0; i < tp->rcv_numsacks; i++) { sack = tp->sackblks[i]; if (SEQ_LT(sack.end, firstsack.start) || SEQ_GT(sack.start, firstsack.end)) continue; /* no overlap */ if (sack.start == firstsack.start && sack.end == firstsack.end){ /* * identical block; delete it here since we will * move it to the front of the list. */ tp->sackblks[i].start = tp->sackblks[i].end = 0; lastpos = i; /* last posn with a zero entry */ continue; } if (SEQ_LEQ(sack.start, firstsack.start)) firstsack.start = sack.start; /* merge blocks */ if (SEQ_GEQ(sack.end, firstsack.end)) firstsack.end = sack.end; /* merge blocks */ tp->sackblks[i].start = tp->sackblks[i].end = 0; lastpos = i; /* last posn with a zero entry */ } if (lastpos != -1) { /* at least one merge */ for (i = 0, j = 1; i < tp->rcv_numsacks; i++) { sack = tp->sackblks[i]; if (sack.start == 0 && sack.end == 0) continue; temp[j++] = sack; } tp->rcv_numsacks = j; /* including first blk (added later) */ for (i = 1; i < tp->rcv_numsacks; i++) /* now copy back */ tp->sackblks[i] = temp[i]; } else { /* no merges -- shift sacks by 1 */ if (tp->rcv_numsacks < MAX_SACK_BLKS) tp->rcv_numsacks++; for (i = tp->rcv_numsacks-1; i > 0; i--) tp->sackblks[i] = tp->sackblks[i-1]; } tp->sackblks[0] = firstsack; return; } /* * Process the TCP SACK option. tp->snd_holes is an ordered list * of holes (oldest to newest, in terms of the sequence space). */ void tcp_sack_option(struct tcpcb *tp, struct tcphdr *th, u_char *cp, int optlen) { int tmp_olen; u_char *tmp_cp; struct sackhole *cur, *p, *temp; if (!tp->sack_enable) return; /* SACK without ACK doesn't make sense. */ if ((th->th_flags & TH_ACK) == 0) return; /* Make sure the ACK on this segment is in [snd_una, snd_max]. */ if (SEQ_LT(th->th_ack, tp->snd_una) || SEQ_GT(th->th_ack, tp->snd_max)) return; /* Note: TCPOLEN_SACK must be 2*sizeof(tcp_seq) */ if (optlen <= 2 || (optlen - 2) % TCPOLEN_SACK != 0) return; /* Note: TCPOLEN_SACK must be 2*sizeof(tcp_seq) */ tmp_cp = cp + 2; tmp_olen = optlen - 2; tcpstat_inc(tcps_sack_rcv_opts); if (tp->snd_numholes < 0) tp->snd_numholes = 0; if (tp->t_maxseg == 0) panic("tcp_sack_option"); /* Should never happen */ while (tmp_olen > 0) { struct sackblk sack; memcpy(&sack.start, tmp_cp, sizeof(tcp_seq)); sack.start = ntohl(sack.start); memcpy(&sack.end, tmp_cp + sizeof(tcp_seq), sizeof(tcp_seq)); sack.end = ntohl(sack.end); tmp_olen -= TCPOLEN_SACK; tmp_cp += TCPOLEN_SACK; if (SEQ_LEQ(sack.end, sack.start)) continue; /* bad SACK fields */ if (SEQ_LEQ(sack.end, tp->snd_una)) continue; /* old block */ if (SEQ_GT(th->th_ack, tp->snd_una)) { if (SEQ_LT(sack.start, th->th_ack)) continue; } if (SEQ_GT(sack.end, tp->snd_max)) continue; if (tp->snd_holes == NULL) { /* first hole */ tp->snd_holes = (struct sackhole *) pool_get(&sackhl_pool, PR_NOWAIT); if (tp->snd_holes == NULL) { /* ENOBUFS, so ignore SACKed block for now*/ goto done; } cur = tp->snd_holes; cur->start = th->th_ack; cur->end = sack.start; cur->rxmit = cur->start; cur->next = NULL; tp->snd_numholes = 1; tp->rcv_lastsack = sack.end; /* * dups is at least one. If more data has been * SACKed, it can be greater than one. */ cur->dups = min(tcprexmtthresh, ((sack.end - cur->end)/tp->t_maxseg)); if (cur->dups < 1) cur->dups = 1; continue; /* with next sack block */ } /* Go thru list of holes: p = previous, cur = current */ p = cur = tp->snd_holes; while (cur) { if (SEQ_LEQ(sack.end, cur->start)) /* SACKs data before the current hole */ break; /* no use going through more holes */ if (SEQ_GEQ(sack.start, cur->end)) { /* SACKs data beyond the current hole */ cur->dups++; if (((sack.end - cur->end)/tp->t_maxseg) >= tcprexmtthresh) cur->dups = tcprexmtthresh; p = cur; cur = cur->next; continue; } if (SEQ_LEQ(sack.start, cur->start)) { /* Data acks at least the beginning of hole */ if (SEQ_GEQ(sack.end, cur->end)) { /* Acks entire hole, so delete hole */ if (p != cur) { p->next = cur->next; pool_put(&sackhl_pool, cur); cur = p->next; } else { cur = cur->next; pool_put(&sackhl_pool, p); p = cur; tp->snd_holes = p; } tp->snd_numholes--; continue; } /* otherwise, move start of hole forward */ cur->start = sack.end; cur->rxmit = SEQ_MAX(cur->rxmit, cur->start); p = cur; cur = cur->next; continue; } /* move end of hole backward */ if (SEQ_GEQ(sack.end, cur->end)) { cur->end = sack.start; cur->rxmit = SEQ_MIN(cur->rxmit, cur->end); cur->dups++; if (((sack.end - cur->end)/tp->t_maxseg) >= tcprexmtthresh) cur->dups = tcprexmtthresh; p = cur; cur = cur->next; continue; } if (SEQ_LT(cur->start, sack.start) && SEQ_GT(cur->end, sack.end)) { /* * ACKs some data in middle of a hole; need to * split current hole */ if (tp->snd_numholes >= TCP_SACKHOLE_LIMIT) goto done; temp = (struct sackhole *) pool_get(&sackhl_pool, PR_NOWAIT); if (temp == NULL) goto done; /* ENOBUFS */ temp->next = cur->next; temp->start = sack.end; temp->end = cur->end; temp->dups = cur->dups; temp->rxmit = SEQ_MAX(cur->rxmit, temp->start); cur->end = sack.start; cur->rxmit = SEQ_MIN(cur->rxmit, cur->end); cur->dups++; if (((sack.end - cur->end)/tp->t_maxseg) >= tcprexmtthresh) cur->dups = tcprexmtthresh; cur->next = temp; p = temp; cur = p->next; tp->snd_numholes++; } } /* At this point, p points to the last hole on the list */ if (SEQ_LT(tp->rcv_lastsack, sack.start)) { /* * Need to append new hole at end. * Last hole is p (and it's not NULL). */ if (tp->snd_numholes >= TCP_SACKHOLE_LIMIT) goto done; temp = (struct sackhole *) pool_get(&sackhl_pool, PR_NOWAIT); if (temp == NULL) goto done; /* ENOBUFS */ temp->start = tp->rcv_lastsack; temp->end = sack.start; temp->dups = min(tcprexmtthresh, ((sack.end - sack.start)/tp->t_maxseg)); if (temp->dups < 1) temp->dups = 1; temp->rxmit = temp->start; temp->next = 0; p->next = temp; tp->rcv_lastsack = sack.end; tp->snd_numholes++; } } done: return; } /* * Delete stale (i.e, cumulatively ack'd) holes. Hole is deleted only if * it is completely acked; otherwise, tcp_sack_option(), called from * tcp_dooptions(), will fix up the hole. */ void tcp_del_sackholes(struct tcpcb *tp, struct tcphdr *th) { if (tp->sack_enable && tp->t_state != TCPS_LISTEN) { /* max because this could be an older ack just arrived */ tcp_seq lastack = SEQ_GT(th->th_ack, tp->snd_una) ? th->th_ack : tp->snd_una; struct sackhole *cur = tp->snd_holes; struct sackhole *prev; while (cur) if (SEQ_LEQ(cur->end, lastack)) { prev = cur; cur = cur->next; pool_put(&sackhl_pool, prev); tp->snd_numholes--; } else if (SEQ_LT(cur->start, lastack)) { cur->start = lastack; if (SEQ_LT(cur->rxmit, cur->start)) cur->rxmit = cur->start; break; } else break; tp->snd_holes = cur; } } /* * Delete all receiver-side SACK information. */ void tcp_clean_sackreport(struct tcpcb *tp) { int i; tp->rcv_numsacks = 0; for (i = 0; i < MAX_SACK_BLKS; i++) tp->sackblks[i].start = tp->sackblks[i].end=0; } /* * Partial ack handling within a sack recovery episode. When a partial ack * arrives, turn off retransmission timer, deflate the window, do not clear * tp->t_dupacks. */ void tcp_sack_partialack(struct tcpcb *tp, struct tcphdr *th) { /* Turn off retx. timer (will start again next segment) */ TCP_TIMER_DISARM(tp, TCPT_REXMT); tp->t_rtttime = 0; /* * Partial window deflation. This statement relies on the * fact that tp->snd_una has not been updated yet. */ if (tp->snd_cwnd > (th->th_ack - tp->snd_una)) { tp->snd_cwnd -= th->th_ack - tp->snd_una; tp->snd_cwnd += tp->t_maxseg; } else tp->snd_cwnd = tp->t_maxseg; tp->snd_cwnd += tp->t_maxseg; tp->t_flags |= TF_NEEDOUTPUT; } /* * Pull out of band byte out of a segment so * it doesn't appear in the user's data queue. * It is still reflected in the segment length for * sequencing purposes. */ void tcp_pulloutofband(struct socket *so, u_int urgent, struct mbuf *m, int off) { int cnt = off + urgent - 1; while (cnt >= 0) { if (m->m_len > cnt) { char *cp = mtod(m, caddr_t) + cnt; struct tcpcb *tp = sototcpcb(so); tp->t_iobc = *cp; tp->t_oobflags |= TCPOOB_HAVEDATA; memmove(cp, cp + 1, m->m_len - cnt - 1); m->m_len--; return; } cnt -= m->m_len; m = m->m_next; if (m == NULL) break; } panic("tcp_pulloutofband"); } /* * Collect new round-trip time estimate * and update averages and current timeout. */ void tcp_xmit_timer(struct tcpcb *tp, int rtt) { short delta; short rttmin; if (rtt < 0) rtt = 0; else if (rtt > TCP_RTT_MAX) rtt = TCP_RTT_MAX; tcpstat_inc(tcps_rttupdated); if (tp->t_srtt != 0) { /* * delta is fixed point with 2 (TCP_RTT_BASE_SHIFT) bits * after the binary point (scaled by 4), whereas * srtt is stored as fixed point with 5 bits after the * binary point (i.e., scaled by 32). The following magic * is equivalent to the smoothing algorithm in rfc793 with * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed * point). */ delta = (rtt << TCP_RTT_BASE_SHIFT) - (tp->t_srtt >> TCP_RTT_SHIFT); if ((tp->t_srtt += delta) <= 0) tp->t_srtt = 1 << TCP_RTT_BASE_SHIFT; /* * We accumulate a smoothed rtt variance (actually, a * smoothed mean difference), then set the retransmit * timer to smoothed rtt + 4 times the smoothed variance. * rttvar is stored as fixed point with 4 bits after the * binary point (scaled by 16). The following is * equivalent to rfc793 smoothing with an alpha of .75 * (rttvar = rttvar*3/4 + |delta| / 4). This replaces * rfc793's wired-in beta. */ if (delta < 0) delta = -delta; delta -= (tp->t_rttvar >> TCP_RTTVAR_SHIFT); if ((tp->t_rttvar += delta) <= 0) tp->t_rttvar = 1 << TCP_RTT_BASE_SHIFT; } else { /* * No rtt measurement yet - use the unsmoothed rtt. * Set the variance to half the rtt (so our first * retransmit happens at 3*rtt). */ tp->t_srtt = (rtt + 1) << (TCP_RTT_SHIFT + TCP_RTT_BASE_SHIFT); tp->t_rttvar = (rtt + 1) << (TCP_RTTVAR_SHIFT + TCP_RTT_BASE_SHIFT - 1); } tp->t_rtttime = 0; tp->t_rxtshift = 0; /* * the retransmit should happen at rtt + 4 * rttvar. * Because of the way we do the smoothing, srtt and rttvar * will each average +1/2 tick of bias. When we compute * the retransmit timer, we want 1/2 tick of rounding and * 1 extra tick because of +-1/2 tick uncertainty in the * firing of the timer. The bias will give us exactly the * 1.5 tick we need. But, because the bias is * statistical, we have to test that we don't drop below * the minimum feasible timer (which is 2 ticks). */ rttmin = min(max(rtt + 2, tp->t_rttmin), TCPTV_REXMTMAX); TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp), rttmin, TCPTV_REXMTMAX); /* * We received an ack for a packet that wasn't retransmitted; * it is probably safe to discard any error indications we've * received recently. This isn't quite right, but close enough * for now (a route might have failed after we sent a segment, * and the return path might not be symmetrical). */ tp->t_softerror = 0; } /* * Determine a reasonable value for maxseg size. * If the route is known, check route for mtu. * If none, use an mss that can be handled on the outgoing * interface without forcing IP to fragment; if bigger than * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES * to utilize large mbufs. If no route is found, route has no mtu, * or the destination isn't local, use a default, hopefully conservative * size (usually 512 or the default IP max size, but no more than the mtu * of the interface), as we can't discover anything about intervening * gateways or networks. We also initialize the congestion/slow start * window to be a single segment if the destination isn't local. * While looking at the routing entry, we also initialize other path-dependent * parameters from pre-set or cached values in the routing entry. * * Also take into account the space needed for options that we * send regularly. Make maxseg shorter by that amount to assure * that we can send maxseg amount of data even when the options * are present. Store the upper limit of the length of options plus * data in maxopd. * * NOTE: offer == -1 indicates that the maxseg size changed due to * Path MTU discovery. */ int tcp_mss(struct tcpcb *tp, int offer) { struct rtentry *rt; struct ifnet *ifp = NULL; int mss, mssopt; int iphlen; struct inpcb *inp; inp = tp->t_inpcb; mssopt = mss = tcp_mssdflt; rt = in_pcbrtentry(inp); if (rt == NULL) goto out; ifp = if_get(rt->rt_ifidx); if (ifp == NULL) goto out; switch (tp->pf) { #ifdef INET6 case AF_INET6: iphlen = sizeof(struct ip6_hdr); break; #endif case AF_INET: iphlen = sizeof(struct ip); break; default: /* the family does not support path MTU discovery */ goto out; } /* * if there's an mtu associated with the route and we support * path MTU discovery for the underlying protocol family, use it. */ if (rt->rt_mtu) { /* * One may wish to lower MSS to take into account options, * especially security-related options. */ if (tp->pf == AF_INET6 && rt->rt_mtu < IPV6_MMTU) { /* * RFC2460 section 5, last paragraph: if path MTU is * smaller than 1280, use 1280 as packet size and * attach fragment header. */ mss = IPV6_MMTU - iphlen - sizeof(struct ip6_frag) - sizeof(struct tcphdr); } else { mss = rt->rt_mtu - iphlen - sizeof(struct tcphdr); } } else if (ifp->if_flags & IFF_LOOPBACK) { mss = ifp->if_mtu - iphlen - sizeof(struct tcphdr); } else if (tp->pf == AF_INET) { if (ip_mtudisc) mss = ifp->if_mtu - iphlen - sizeof(struct tcphdr); } #ifdef INET6 else if (tp->pf == AF_INET6) { /* * for IPv6, path MTU discovery is always turned on, * or the node must use packet size <= 1280. */ mss = ifp->if_mtu - iphlen - sizeof(struct tcphdr); } #endif /* INET6 */ /* Calculate the value that we offer in TCPOPT_MAXSEG */ if (offer != -1) { mssopt = ifp->if_mtu - iphlen - sizeof(struct tcphdr); mssopt = max(tcp_mssdflt, mssopt); } out: if_put(ifp); /* * The current mss, t_maxseg, is initialized to the default value. * If we compute a smaller value, reduce the current mss. * If we compute a larger value, return it for use in sending * a max seg size option, but don't store it for use * unless we received an offer at least that large from peer. * * However, do not accept offers lower than the minimum of * the interface MTU and 216. */ if (offer > 0) tp->t_peermss = offer; if (tp->t_peermss) mss = min(mss, max(tp->t_peermss, 216)); /* sanity - at least max opt. space */ mss = max(mss, 64); /* * maxopd stores the maximum length of data AND options * in a segment; maxseg is the amount of data in a normal * segment. We need to store this value (maxopd) apart * from maxseg, because now every segment carries options * and thus we normally have somewhat less data in segments. */ tp->t_maxopd = mss; if ((tp->t_flags & (TF_REQ_TSTMP|TF_NOOPT)) == TF_REQ_TSTMP && (tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP) mss -= TCPOLEN_TSTAMP_APPA; #ifdef TCP_SIGNATURE if (tp->t_flags & TF_SIGNATURE) mss -= TCPOLEN_SIGLEN; #endif if (offer == -1) { /* mss changed due to Path MTU discovery */ tp->t_flags &= ~TF_PMTUD_PEND; tp->t_pmtud_mtu_sent = 0; tp->t_pmtud_mss_acked = 0; if (mss < tp->t_maxseg) { /* * Follow suggestion in RFC 2414 to reduce the * congestion window by the ratio of the old * segment size to the new segment size. */ tp->snd_cwnd = ulmax((tp->snd_cwnd / tp->t_maxseg) * mss, mss); } } else if (tcp_do_rfc3390 == 2) { /* increase initial window */ tp->snd_cwnd = ulmin(10 * mss, ulmax(2 * mss, 14600)); } else if (tcp_do_rfc3390) { /* increase initial window */ tp->snd_cwnd = ulmin(4 * mss, ulmax(2 * mss, 4380)); } else tp->snd_cwnd = mss; tp->t_maxseg = mss; return (offer != -1 ? mssopt : mss); } u_int tcp_hdrsz(struct tcpcb *tp) { u_int hlen; switch (tp->pf) { #ifdef INET6 case AF_INET6: hlen = sizeof(struct ip6_hdr); break; #endif case AF_INET: hlen = sizeof(struct ip); break; default: hlen = 0; break; } hlen += sizeof(struct tcphdr); if ((tp->t_flags & (TF_REQ_TSTMP|TF_NOOPT)) == TF_REQ_TSTMP && (tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP) hlen += TCPOLEN_TSTAMP_APPA; #ifdef TCP_SIGNATURE if (tp->t_flags & TF_SIGNATURE) hlen += TCPOLEN_SIGLEN; #endif return (hlen); } /* * Set connection variables based on the effective MSS. * We are passed the TCPCB for the actual connection. If we * are the server, we are called by the compressed state engine * when the 3-way handshake is complete. If we are the client, * we are called when we receive the SYN,ACK from the server. * * NOTE: The t_maxseg value must be initialized in the TCPCB * before this routine is called! */ void tcp_mss_update(struct tcpcb *tp) { int mss; u_long bufsize; struct rtentry *rt; struct socket *so; so = tp->t_inpcb->inp_socket; mss = tp->t_maxseg; rt = in_pcbrtentry(tp->t_inpcb); if (rt == NULL) return; bufsize = so->so_snd.sb_hiwat; if (bufsize < mss) { mss = bufsize; /* Update t_maxseg and t_maxopd */ tcp_mss(tp, mss); } else { bufsize = roundup(bufsize, mss); if (bufsize > sb_max) bufsize = sb_max; (void)sbreserve(so, &so->so_snd, bufsize); } bufsize = so->so_rcv.sb_hiwat; if (bufsize > mss) { bufsize = roundup(bufsize, mss); if (bufsize > sb_max) bufsize = sb_max; (void)sbreserve(so, &so->so_rcv, bufsize); } } /* * When a partial ack arrives, force the retransmission of the * next unacknowledged segment. Do not clear tp->t_dupacks. * By setting snd_nxt to ti_ack, this forces retransmission timer * to be started again. */ void tcp_newreno_partialack(struct tcpcb *tp, struct tcphdr *th) { /* * snd_una has not been updated and the socket send buffer * not yet drained of the acked data, so we have to leave * snd_una as it was to get the correct data offset in * tcp_output(). */ tcp_seq onxt = tp->snd_nxt; u_long ocwnd = tp->snd_cwnd; TCP_TIMER_DISARM(tp, TCPT_REXMT); tp->t_rtttime = 0; tp->snd_nxt = th->th_ack; /* * Set snd_cwnd to one segment beyond acknowledged offset * (tp->snd_una not yet updated when this function is called) */ tp->snd_cwnd = tp->t_maxseg + (th->th_ack - tp->snd_una); (void)tcp_output(tp); tp->snd_cwnd = ocwnd; if (SEQ_GT(onxt, tp->snd_nxt)) tp->snd_nxt = onxt; /* * Partial window deflation. Relies on fact that tp->snd_una * not updated yet. */ if (tp->snd_cwnd > th->th_ack - tp->snd_una) tp->snd_cwnd -= th->th_ack - tp->snd_una; else tp->snd_cwnd = 0; tp->snd_cwnd += tp->t_maxseg; } int tcp_mss_adv(struct mbuf *m, int af) { int mss = 0; int iphlen; struct ifnet *ifp = NULL; if (m && (m->m_flags & M_PKTHDR)) ifp = if_get(m->m_pkthdr.ph_ifidx); switch (af) { case AF_INET: if (ifp != NULL) mss = ifp->if_mtu; iphlen = sizeof(struct ip); break; #ifdef INET6 case AF_INET6: if (ifp != NULL) mss = ifp->if_mtu; iphlen = sizeof(struct ip6_hdr); break; #endif default: unhandled_af(af); } if_put(ifp); mss = mss - iphlen - sizeof(struct tcphdr); return (max(mss, tcp_mssdflt)); } /* * TCP compressed state engine. Currently used to hold compressed * state for SYN_RECEIVED. */ /* syn hash parameters */ int tcp_syn_hash_size = TCP_SYN_HASH_SIZE; int tcp_syn_cache_limit = TCP_SYN_HASH_SIZE*TCP_SYN_BUCKET_SIZE; int tcp_syn_bucket_limit = 3*TCP_SYN_BUCKET_SIZE; int tcp_syn_use_limit = 100000; struct syn_cache_set tcp_syn_cache[2]; int tcp_syn_cache_active; #define SYN_HASH(sa, sp, dp, rand) \ (((sa)->s_addr ^ (rand)[0]) * \ (((((u_int32_t)(dp))<<16) + ((u_int32_t)(sp))) ^ (rand)[4])) #ifndef INET6 #define SYN_HASHALL(hash, src, dst, rand) \ do { \ hash = SYN_HASH(&satosin(src)->sin_addr, \ satosin(src)->sin_port, \ satosin(dst)->sin_port, (rand)); \ } while (/*CONSTCOND*/ 0) #else #define SYN_HASH6(sa, sp, dp, rand) \ (((sa)->s6_addr32[0] ^ (rand)[0]) * \ ((sa)->s6_addr32[1] ^ (rand)[1]) * \ ((sa)->s6_addr32[2] ^ (rand)[2]) * \ ((sa)->s6_addr32[3] ^ (rand)[3]) * \ (((((u_int32_t)(dp))<<16) + ((u_int32_t)(sp))) ^ (rand)[4])) #define SYN_HASHALL(hash, src, dst, rand) \ do { \ switch ((src)->sa_family) { \ case AF_INET: \ hash = SYN_HASH(&satosin(src)->sin_addr, \ satosin(src)->sin_port, \ satosin(dst)->sin_port, (rand)); \ break; \ case AF_INET6: \ hash = SYN_HASH6(&satosin6(src)->sin6_addr, \ satosin6(src)->sin6_port, \ satosin6(dst)->sin6_port, (rand)); \ break; \ default: \ hash = 0; \ } \ } while (/*CONSTCOND*/0) #endif /* INET6 */ void syn_cache_rm(struct syn_cache *sc) { sc->sc_flags |= SCF_DEAD; TAILQ_REMOVE(&sc->sc_buckethead->sch_bucket, sc, sc_bucketq); sc->sc_tp = NULL; LIST_REMOVE(sc, sc_tpq); sc->sc_buckethead->sch_length--; timeout_del(&sc->sc_timer); sc->sc_set->scs_count--; } void syn_cache_put(struct syn_cache *sc) { m_free(sc->sc_ipopts); if (sc->sc_route4.ro_rt != NULL) { rtfree(sc->sc_route4.ro_rt); sc->sc_route4.ro_rt = NULL; } timeout_set(&sc->sc_timer, syn_cache_reaper, sc); timeout_add(&sc->sc_timer, 0); } struct pool syn_cache_pool; /* * We don't estimate RTT with SYNs, so each packet starts with the default * RTT and each timer step has a fixed timeout value. */ #define SYN_CACHE_TIMER_ARM(sc) \ do { \ TCPT_RANGESET((sc)->sc_rxtcur, \ TCPTV_SRTTDFLT * tcp_backoff[(sc)->sc_rxtshift], TCPTV_MIN, \ TCPTV_REXMTMAX); \ if (!timeout_initialized(&(sc)->sc_timer)) \ timeout_set_proc(&(sc)->sc_timer, syn_cache_timer, (sc)); \ timeout_add(&(sc)->sc_timer, (sc)->sc_rxtcur * (hz / PR_SLOWHZ)); \ } while (/*CONSTCOND*/0) #define SYN_CACHE_TIMESTAMP(sc) tcp_now + (sc)->sc_modulate void syn_cache_init(void) { int i; /* Initialize the hash buckets. */ tcp_syn_cache[0].scs_buckethead = mallocarray(tcp_syn_hash_size, sizeof(struct syn_cache_head), M_SYNCACHE, M_WAITOK|M_ZERO); tcp_syn_cache[1].scs_buckethead = mallocarray(tcp_syn_hash_size, sizeof(struct syn_cache_head), M_SYNCACHE, M_WAITOK|M_ZERO); tcp_syn_cache[0].scs_size = tcp_syn_hash_size; tcp_syn_cache[1].scs_size = tcp_syn_hash_size; for (i = 0; i < tcp_syn_hash_size; i++) { TAILQ_INIT(&tcp_syn_cache[0].scs_buckethead[i].sch_bucket); TAILQ_INIT(&tcp_syn_cache[1].scs_buckethead[i].sch_bucket); } /* Initialize the syn cache pool. */ pool_init(&syn_cache_pool, sizeof(struct syn_cache), 0, IPL_SOFTNET, 0, "syncache", NULL); } void syn_cache_insert(struct syn_cache *sc, struct tcpcb *tp) { struct syn_cache_set *set = &tcp_syn_cache[tcp_syn_cache_active]; struct syn_cache_head *scp; struct syn_cache *sc2; int i; NET_ASSERT_LOCKED(); /* * If there are no entries in the hash table, reinitialize * the hash secrets. To avoid useless cache swaps and * reinitialization, use it until the limit is reached. * An emtpy cache is also the oportunity to resize the hash. */ if (set->scs_count == 0 && set->scs_use <= 0) { set->scs_use = tcp_syn_use_limit; if (set->scs_size != tcp_syn_hash_size) { scp = mallocarray(tcp_syn_hash_size, sizeof(struct syn_cache_head), M_SYNCACHE, M_NOWAIT|M_ZERO); if (scp == NULL) { /* Try again next time. */ set->scs_use = 0; } else { free(set->scs_buckethead, M_SYNCACHE, set->scs_size * sizeof(struct syn_cache_head)); set->scs_buckethead = scp; set->scs_size = tcp_syn_hash_size; for (i = 0; i < tcp_syn_hash_size; i++) TAILQ_INIT(&scp[i].sch_bucket); } } arc4random_buf(set->scs_random, sizeof(set->scs_random)); tcpstat_inc(tcps_sc_seedrandom); } SYN_HASHALL(sc->sc_hash, &sc->sc_src.sa, &sc->sc_dst.sa, set->scs_random); scp = &set->scs_buckethead[sc->sc_hash % set->scs_size]; sc->sc_buckethead = scp; /* * Make sure that we don't overflow the per-bucket * limit or the total cache size limit. */ if (scp->sch_length >= tcp_syn_bucket_limit) { tcpstat_inc(tcps_sc_bucketoverflow); /* * Someone might attack our bucket hash function. Reseed * with random as soon as the passive syn cache gets empty. */ set->scs_use = 0; /* * The bucket is full. Toss the oldest element in the * bucket. This will be the first entry in the bucket. */ sc2 = TAILQ_FIRST(&scp->sch_bucket); #ifdef DIAGNOSTIC /* * This should never happen; we should always find an * entry in our bucket. */ if (sc2 == NULL) panic("%s: bucketoverflow: impossible", __func__); #endif syn_cache_rm(sc2); syn_cache_put(sc2); } else if (set->scs_count >= tcp_syn_cache_limit) { struct syn_cache_head *scp2, *sce; tcpstat_inc(tcps_sc_overflowed); /* * The cache is full. Toss the oldest entry in the * first non-empty bucket we can find. * * XXX We would really like to toss the oldest * entry in the cache, but we hope that this * condition doesn't happen very often. */ scp2 = scp; if (TAILQ_EMPTY(&scp2->sch_bucket)) { sce = &set->scs_buckethead[set->scs_size]; for (++scp2; scp2 != scp; scp2++) { if (scp2 >= sce) scp2 = &set->scs_buckethead[0]; if (! TAILQ_EMPTY(&scp2->sch_bucket)) break; } #ifdef DIAGNOSTIC /* * This should never happen; we should always find a * non-empty bucket. */ if (scp2 == scp) panic("%s: cacheoverflow: impossible", __func__); #endif } sc2 = TAILQ_FIRST(&scp2->sch_bucket); syn_cache_rm(sc2); syn_cache_put(sc2); } /* * Initialize the entry's timer. */ sc->sc_rxttot = 0; sc->sc_rxtshift = 0; SYN_CACHE_TIMER_ARM(sc); /* Link it from tcpcb entry */ LIST_INSERT_HEAD(&tp->t_sc, sc, sc_tpq); /* Put it into the bucket. */ TAILQ_INSERT_TAIL(&scp->sch_bucket, sc, sc_bucketq); scp->sch_length++; sc->sc_set = set; set->scs_count++; set->scs_use--; tcpstat_inc(tcps_sc_added); /* * If the active cache has exceeded its use limit and * the passive syn cache is empty, exchange their roles. */ if (set->scs_use <= 0 && tcp_syn_cache[!tcp_syn_cache_active].scs_count == 0) tcp_syn_cache_active = !tcp_syn_cache_active; } /* * Walk the timer queues, looking for SYN,ACKs that need to be retransmitted. * If we have retransmitted an entry the maximum number of times, expire * that entry. */ void syn_cache_timer(void *arg) { struct syn_cache *sc = arg; NET_LOCK(); if (sc->sc_flags & SCF_DEAD) goto out; if (__predict_false(sc->sc_rxtshift == TCP_MAXRXTSHIFT)) { /* Drop it -- too many retransmissions. */ goto dropit; } /* * Compute the total amount of time this entry has * been on a queue. If this entry has been on longer * than the keep alive timer would allow, expire it. */ sc->sc_rxttot += sc->sc_rxtcur; if (sc->sc_rxttot >= tcptv_keep_init) goto dropit; tcpstat_inc(tcps_sc_retransmitted); (void) syn_cache_respond(sc, NULL); /* Advance the timer back-off. */ sc->sc_rxtshift++; SYN_CACHE_TIMER_ARM(sc); out: NET_UNLOCK(); return; dropit: tcpstat_inc(tcps_sc_timed_out); syn_cache_rm(sc); syn_cache_put(sc); NET_UNLOCK(); } void syn_cache_reaper(void *arg) { struct syn_cache *sc = arg; pool_put(&syn_cache_pool, (sc)); return; } /* * Remove syn cache created by the specified tcb entry, * because this does not make sense to keep them * (if there's no tcb entry, syn cache entry will never be used) */ void syn_cache_cleanup(struct tcpcb *tp) { struct syn_cache *sc, *nsc; NET_ASSERT_LOCKED(); LIST_FOREACH_SAFE(sc, &tp->t_sc, sc_tpq, nsc) { #ifdef DIAGNOSTIC if (sc->sc_tp != tp) panic("invalid sc_tp in syn_cache_cleanup"); #endif syn_cache_rm(sc); syn_cache_put(sc); } /* just for safety */ LIST_INIT(&tp->t_sc); } /* * Find an entry in the syn cache. */ struct syn_cache * syn_cache_lookup(struct sockaddr *src, struct sockaddr *dst, struct syn_cache_head **headp, u_int rtableid) { struct syn_cache_set *sets[2]; struct syn_cache *sc; struct syn_cache_head *scp; u_int32_t hash; int i; NET_ASSERT_LOCKED(); /* Check the active cache first, the passive cache is likely emtpy. */ sets[0] = &tcp_syn_cache[tcp_syn_cache_active]; sets[1] = &tcp_syn_cache[!tcp_syn_cache_active]; for (i = 0; i < 2; i++) { if (sets[i]->scs_count == 0) continue; SYN_HASHALL(hash, src, dst, sets[i]->scs_random); scp = &sets[i]->scs_buckethead[hash % sets[i]->scs_size]; *headp = scp; TAILQ_FOREACH(sc, &scp->sch_bucket, sc_bucketq) { if (sc->sc_hash != hash) continue; if (!bcmp(&sc->sc_src, src, src->sa_len) && !bcmp(&sc->sc_dst, dst, dst->sa_len) && rtable_l2(rtableid) == rtable_l2(sc->sc_rtableid)) return (sc); } } return (NULL); } /* * This function gets called when we receive an ACK for a * socket in the LISTEN state. We look up the connection * in the syn cache, and if its there, we pull it out of * the cache and turn it into a full-blown connection in * the SYN-RECEIVED state. * * The return values may not be immediately obvious, and their effects * can be subtle, so here they are: * * NULL SYN was not found in cache; caller should drop the * packet and send an RST. * * -1 We were unable to create the new connection, and are * aborting it. An ACK,RST is being sent to the peer * (unless we got screwey sequence numbners; see below), * because the 3-way handshake has been completed. Caller * should not free the mbuf, since we may be using it. If * we are not, we will free it. * * Otherwise, the return value is a pointer to the new socket * associated with the connection. */ struct socket * syn_cache_get(struct sockaddr *src, struct sockaddr *dst, struct tcphdr *th, u_int hlen, u_int tlen, struct socket *so, struct mbuf *m) { struct syn_cache *sc; struct syn_cache_head *scp; struct inpcb *inp, *oldinp; struct tcpcb *tp = NULL; struct mbuf *am; struct socket *oso; NET_ASSERT_LOCKED(); sc = syn_cache_lookup(src, dst, &scp, sotoinpcb(so)->inp_rtableid); if (sc == NULL) return (NULL); /* * Verify the sequence and ack numbers. Try getting the correct * response again. */ if ((th->th_ack != sc->sc_iss + 1) || SEQ_LEQ(th->th_seq, sc->sc_irs) || SEQ_GT(th->th_seq, sc->sc_irs + 1 + sc->sc_win)) { (void) syn_cache_respond(sc, m); return ((struct socket *)(-1)); } /* Remove this cache entry */ syn_cache_rm(sc); /* * Ok, create the full blown connection, and set things up * as they would have been set up if we had created the * connection when the SYN arrived. If we can't create * the connection, abort it. */ oso = so; so = sonewconn(so, SS_ISCONNECTED); if (so == NULL) goto resetandabort; oldinp = sotoinpcb(oso); inp = sotoinpcb(so); #ifdef IPSEC /* * We need to copy the required security levels * from the old pcb. Ditto for any other * IPsec-related information. */ memcpy(inp->inp_seclevel, oldinp->inp_seclevel, sizeof(oldinp->inp_seclevel)); #endif /* IPSEC */ #ifdef INET6 /* * inp still has the OLD in_pcb stuff, set the * v6-related flags on the new guy, too. */ inp->inp_flags |= (oldinp->inp_flags & INP_IPV6); if (inp->inp_flags & INP_IPV6) { inp->inp_ipv6.ip6_hlim = oldinp->inp_ipv6.ip6_hlim; inp->inp_hops = oldinp->inp_hops; } else #endif /* INET6 */ { inp->inp_ip.ip_ttl = oldinp->inp_ip.ip_ttl; } #if NPF > 0 if (m->m_pkthdr.pf.flags & PF_TAG_DIVERTED) { struct pf_divert *divert; divert = pf_find_divert(m); KASSERT(divert != NULL); inp->inp_rtableid = divert->rdomain; } else #endif /* inherit rtable from listening socket */ inp->inp_rtableid = sc->sc_rtableid; inp->inp_lport = th->th_dport; switch (src->sa_family) { #ifdef INET6 case AF_INET6: inp->inp_laddr6 = satosin6(dst)->sin6_addr; break; #endif /* INET6 */ case AF_INET: inp->inp_laddr = satosin(dst)->sin_addr; inp->inp_options = ip_srcroute(m); if (inp->inp_options == NULL) { inp->inp_options = sc->sc_ipopts; sc->sc_ipopts = NULL; } break; } in_pcbrehash(inp); /* * Give the new socket our cached route reference. */ if (src->sa_family == AF_INET) inp->inp_route = sc->sc_route4; /* struct assignment */ #ifdef INET6 else inp->inp_route6 = sc->sc_route6; #endif sc->sc_route4.ro_rt = NULL; am = m_get(M_DONTWAIT, MT_SONAME); /* XXX */ if (am == NULL) goto resetandabort; am->m_len = src->sa_len; memcpy(mtod(am, caddr_t), src, src->sa_len); if (in_pcbconnect(inp, am)) { (void) m_free(am); goto resetandabort; } (void) m_free(am); tp = intotcpcb(inp); tp->t_flags = sototcpcb(oso)->t_flags & (TF_NOPUSH|TF_NODELAY); if (sc->sc_request_r_scale != 15) { tp->requested_s_scale = sc->sc_requested_s_scale; tp->request_r_scale = sc->sc_request_r_scale; tp->t_flags |= TF_REQ_SCALE|TF_RCVD_SCALE; } if (sc->sc_flags & SCF_TIMESTAMP) tp->t_flags |= TF_REQ_TSTMP|TF_RCVD_TSTMP; tp->t_template = tcp_template(tp); if (tp->t_template == 0) { tp = tcp_drop(tp, ENOBUFS); /* destroys socket */ so = NULL; goto abort; } tp->sack_enable = sc->sc_flags & SCF_SACK_PERMIT; tp->ts_modulate = sc->sc_modulate; tp->ts_recent = sc->sc_timestamp; tp->iss = sc->sc_iss; tp->irs = sc->sc_irs; tcp_sendseqinit(tp); tp->snd_last = tp->snd_una; #ifdef TCP_ECN if (sc->sc_flags & SCF_ECN_PERMIT) { tp->t_flags |= TF_ECN_PERMIT; tcpstat_inc(tcps_ecn_accepts); } #endif if (sc->sc_flags & SCF_SACK_PERMIT) tp->t_flags |= TF_SACK_PERMIT; #ifdef TCP_SIGNATURE if (sc->sc_flags & SCF_SIGNATURE) tp->t_flags |= TF_SIGNATURE; #endif tcp_rcvseqinit(tp); tp->t_state = TCPS_SYN_RECEIVED; tp->t_rcvtime = tcp_now; TCP_TIMER_ARM(tp, TCPT_KEEP, tcptv_keep_init); tcpstat_inc(tcps_accepts); tcp_mss(tp, sc->sc_peermaxseg); /* sets t_maxseg */ if (sc->sc_peermaxseg) tcp_mss_update(tp); /* Reset initial window to 1 segment for retransmit */ if (sc->sc_rxtshift > 0) tp->snd_cwnd = tp->t_maxseg; tp->snd_wl1 = sc->sc_irs; tp->rcv_up = sc->sc_irs + 1; /* * This is what whould have happened in tcp_output() when * the SYN,ACK was sent. */ tp->snd_up = tp->snd_una; tp->snd_max = tp->snd_nxt = tp->iss+1; TCP_TIMER_ARM(tp, TCPT_REXMT, tp->t_rxtcur); if (sc->sc_win > 0 && SEQ_GT(tp->rcv_nxt + sc->sc_win, tp->rcv_adv)) tp->rcv_adv = tp->rcv_nxt + sc->sc_win; tp->last_ack_sent = tp->rcv_nxt; tcpstat_inc(tcps_sc_completed); syn_cache_put(sc); return (so); resetandabort: tcp_respond(NULL, mtod(m, caddr_t), th, (tcp_seq)0, th->th_ack, TH_RST, m->m_pkthdr.ph_rtableid); abort: m_freem(m); if (so != NULL) (void) soabort(so); syn_cache_put(sc); tcpstat_inc(tcps_sc_aborted); return ((struct socket *)(-1)); } /* * This function is called when we get a RST for a * non-existent connection, so that we can see if the * connection is in the syn cache. If it is, zap it. */ void syn_cache_reset(struct sockaddr *src, struct sockaddr *dst, struct tcphdr *th, u_int rtableid) { struct syn_cache *sc; struct syn_cache_head *scp; NET_ASSERT_LOCKED(); if ((sc = syn_cache_lookup(src, dst, &scp, rtableid)) == NULL) return; if (SEQ_LT(th->th_seq, sc->sc_irs) || SEQ_GT(th->th_seq, sc->sc_irs + 1)) return; syn_cache_rm(sc); tcpstat_inc(tcps_sc_reset); syn_cache_put(sc); } void syn_cache_unreach(struct sockaddr *src, struct sockaddr *dst, struct tcphdr *th, u_int rtableid) { struct syn_cache *sc; struct syn_cache_head *scp; NET_ASSERT_LOCKED(); if ((sc = syn_cache_lookup(src, dst, &scp, rtableid)) == NULL) return; /* If the sequence number != sc_iss, then it's a bogus ICMP msg */ if (ntohl (th->th_seq) != sc->sc_iss) { return; } /* * If we've retransmitted 3 times and this is our second error, * we remove the entry. Otherwise, we allow it to continue on. * This prevents us from incorrectly nuking an entry during a * spurious network outage. * * See tcp_notify(). */ if ((sc->sc_flags & SCF_UNREACH) == 0 || sc->sc_rxtshift < 3) { sc->sc_flags |= SCF_UNREACH; return; } syn_cache_rm(sc); tcpstat_inc(tcps_sc_unreach); syn_cache_put(sc); } /* * Given a LISTEN socket and an inbound SYN request, add * this to the syn cache, and send back a segment: * <SEQ=ISS><ACK=RCV_NXT><CTL=SYN,ACK> * to the source. * * IMPORTANT NOTE: We do _NOT_ ACK data that might accompany the SYN. * Doing so would require that we hold onto the data and deliver it * to the application. However, if we are the target of a SYN-flood * DoS attack, an attacker could send data which would eventually * consume all available buffer space if it were ACKed. By not ACKing * the data, we avoid this DoS scenario. */ int syn_cache_add(struct sockaddr *src, struct sockaddr *dst, struct tcphdr *th, u_int iphlen, struct socket *so, struct mbuf *m, u_char *optp, int optlen, struct tcp_opt_info *oi, tcp_seq *issp) { struct tcpcb tb, *tp; long win; struct syn_cache *sc; struct syn_cache_head *scp; struct mbuf *ipopts; tp = sototcpcb(so); /* * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN * * Note this check is performed in tcp_input() very early on. */ /* * Initialize some local state. */ win = sbspace(so, &so->so_rcv); if (win > TCP_MAXWIN) win = TCP_MAXWIN; bzero(&tb, sizeof(tb)); #ifdef TCP_SIGNATURE if (optp || (tp->t_flags & TF_SIGNATURE)) { #else if (optp) { #endif tb.pf = tp->pf; tb.sack_enable = tp->sack_enable; tb.t_flags = tcp_do_rfc1323 ? (TF_REQ_SCALE|TF_REQ_TSTMP) : 0; #ifdef TCP_SIGNATURE if (tp->t_flags & TF_SIGNATURE) tb.t_flags |= TF_SIGNATURE; #endif tb.t_state = TCPS_LISTEN; if (tcp_dooptions(&tb, optp, optlen, th, m, iphlen, oi, sotoinpcb(so)->inp_rtableid)) return (-1); } switch (src->sa_family) { case AF_INET: /* * Remember the IP options, if any. */ ipopts = ip_srcroute(m); break; default: ipopts = NULL; } /* * See if we already have an entry for this connection. * If we do, resend the SYN,ACK. We do not count this * as a retransmission (XXX though maybe we should). */ sc = syn_cache_lookup(src, dst, &scp, sotoinpcb(so)->inp_rtableid); if (sc != NULL) { tcpstat_inc(tcps_sc_dupesyn); if (ipopts) { /* * If we were remembering a previous source route, * forget it and use the new one we've been given. */ m_free(sc->sc_ipopts); sc->sc_ipopts = ipopts; } sc->sc_timestamp = tb.ts_recent; if (syn_cache_respond(sc, m) == 0) { tcpstat_inc(tcps_sndacks); tcpstat_inc(tcps_sndtotal); } return (0); } sc = pool_get(&syn_cache_pool, PR_NOWAIT|PR_ZERO); if (sc == NULL) { m_free(ipopts); return (-1); } /* * Fill in the cache, and put the necessary IP and TCP * options into the reply. */ memcpy(&sc->sc_src, src, src->sa_len); memcpy(&sc->sc_dst, dst, dst->sa_len); sc->sc_rtableid = sotoinpcb(so)->inp_rtableid; sc->sc_flags = 0; sc->sc_ipopts = ipopts; sc->sc_irs = th->th_seq; sc->sc_iss = issp ? *issp : arc4random(); sc->sc_peermaxseg = oi->maxseg; sc->sc_ourmaxseg = tcp_mss_adv(m, sc->sc_src.sa.sa_family); sc->sc_win = win; sc->sc_timestamp = tb.ts_recent; if ((tb.t_flags & (TF_REQ_TSTMP|TF_RCVD_TSTMP)) == (TF_REQ_TSTMP|TF_RCVD_TSTMP)) { sc->sc_flags |= SCF_TIMESTAMP; sc->sc_modulate = arc4random(); } if ((tb.t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) == (TF_RCVD_SCALE|TF_REQ_SCALE)) { sc->sc_requested_s_scale = tb.requested_s_scale; sc->sc_request_r_scale = 0; /* * Pick the smallest possible scaling factor that * will still allow us to scale up to sb_max. * * We do this because there are broken firewalls that * will corrupt the window scale option, leading to * the other endpoint believing that our advertised * window is unscaled. At scale factors larger than * 5 the unscaled window will drop below 1500 bytes, * leading to serious problems when traversing these * broken firewalls. * * With the default sbmax of 256K, a scale factor * of 3 will be chosen by this algorithm. Those who * choose a larger sbmax should watch out * for the compatiblity problems mentioned above. * * RFC1323: The Window field in a SYN (i.e., a <SYN> * or <SYN,ACK>) segment itself is never scaled. */ while (sc->sc_request_r_scale < TCP_MAX_WINSHIFT && (TCP_MAXWIN << sc->sc_request_r_scale) < sb_max) sc->sc_request_r_scale++; } else { sc->sc_requested_s_scale = 15; sc->sc_request_r_scale = 15; } #ifdef TCP_ECN /* * if both ECE and CWR flag bits are set, peer is ECN capable. */ if (tcp_do_ecn && (th->th_flags & (TH_ECE|TH_CWR)) == (TH_ECE|TH_CWR)) sc->sc_flags |= SCF_ECN_PERMIT; #endif /* * Set SCF_SACK_PERMIT if peer did send a SACK_PERMITTED option * (i.e., if tcp_dooptions() did set TF_SACK_PERMIT). */ if (tb.sack_enable && (tb.t_flags & TF_SACK_PERMIT)) sc->sc_flags |= SCF_SACK_PERMIT; #ifdef TCP_SIGNATURE if (tb.t_flags & TF_SIGNATURE) sc->sc_flags |= SCF_SIGNATURE; #endif sc->sc_tp = tp; if (syn_cache_respond(sc, m) == 0) { syn_cache_insert(sc, tp); tcpstat_inc(tcps_sndacks); tcpstat_inc(tcps_sndtotal); } else { syn_cache_put(sc); tcpstat_inc(tcps_sc_dropped); } return (0); } int syn_cache_respond(struct syn_cache *sc, struct mbuf *m) { u_int8_t *optp; int optlen, error; u_int16_t tlen; struct ip *ip = NULL; #ifdef INET6 struct ip6_hdr *ip6 = NULL; #endif struct tcphdr *th; u_int hlen; struct inpcb *inp; switch (sc->sc_src.sa.sa_family) { case AF_INET: hlen = sizeof(struct ip); break; #ifdef INET6 case AF_INET6: hlen = sizeof(struct ip6_hdr); break; #endif default: m_freem(m); return (EAFNOSUPPORT); } /* Compute the size of the TCP options. */ optlen = 4 + (sc->sc_request_r_scale != 15 ? 4 : 0) + ((sc->sc_flags & SCF_SACK_PERMIT) ? 4 : 0) + #ifdef TCP_SIGNATURE ((sc->sc_flags & SCF_SIGNATURE) ? TCPOLEN_SIGLEN : 0) + #endif ((sc->sc_flags & SCF_TIMESTAMP) ? TCPOLEN_TSTAMP_APPA : 0); tlen = hlen + sizeof(struct tcphdr) + optlen; /* * Create the IP+TCP header from scratch. */ m_freem(m); #ifdef DIAGNOSTIC if (max_linkhdr + tlen > MCLBYTES) return (ENOBUFS); #endif MGETHDR(m, M_DONTWAIT, MT_DATA); if (m && max_linkhdr + tlen > MHLEN) { MCLGET(m, M_DONTWAIT); if ((m->m_flags & M_EXT) == 0) { m_freem(m); m = NULL; } } if (m == NULL) return (ENOBUFS); /* Fixup the mbuf. */ m->m_data += max_linkhdr; m->m_len = m->m_pkthdr.len = tlen; m->m_pkthdr.ph_ifidx = 0; m->m_pkthdr.ph_rtableid = sc->sc_rtableid; memset(mtod(m, u_char *), 0, tlen); switch (sc->sc_src.sa.sa_family) { case AF_INET: ip = mtod(m, struct ip *); ip->ip_dst = sc->sc_src.sin.sin_addr; ip->ip_src = sc->sc_dst.sin.sin_addr; ip->ip_p = IPPROTO_TCP; th = (struct tcphdr *)(ip + 1); th->th_dport = sc->sc_src.sin.sin_port; th->th_sport = sc->sc_dst.sin.sin_port; break; #ifdef INET6 case AF_INET6: ip6 = mtod(m, struct ip6_hdr *); ip6->ip6_dst = sc->sc_src.sin6.sin6_addr; ip6->ip6_src = sc->sc_dst.sin6.sin6_addr; ip6->ip6_nxt = IPPROTO_TCP; /* ip6_plen will be updated in ip6_output() */ th = (struct tcphdr *)(ip6 + 1); th->th_dport = sc->sc_src.sin6.sin6_port; th->th_sport = sc->sc_dst.sin6.sin6_port; break; #endif default: unhandled_af(sc->sc_src.sa.sa_family); } th->th_seq = htonl(sc->sc_iss); th->th_ack = htonl(sc->sc_irs + 1); th->th_off = (sizeof(struct tcphdr) + optlen) >> 2; th->th_flags = TH_SYN|TH_ACK; #ifdef TCP_ECN /* Set ECE for SYN-ACK if peer supports ECN. */ if (tcp_do_ecn && (sc->sc_flags & SCF_ECN_PERMIT)) th->th_flags |= TH_ECE; #endif th->th_win = htons(sc->sc_win); /* th_sum already 0 */ /* th_urp already 0 */ /* Tack on the TCP options. */ optp = (u_int8_t *)(th + 1); *optp++ = TCPOPT_MAXSEG; *optp++ = 4; *optp++ = (sc->sc_ourmaxseg >> 8) & 0xff; *optp++ = sc->sc_ourmaxseg & 0xff; /* Include SACK_PERMIT_HDR option if peer has already done so. */ if (sc->sc_flags & SCF_SACK_PERMIT) { *((u_int32_t *)optp) = htonl(TCPOPT_SACK_PERMIT_HDR); optp += 4; } if (sc->sc_request_r_scale != 15) { *((u_int32_t *)optp) = htonl(TCPOPT_NOP << 24 | TCPOPT_WINDOW << 16 | TCPOLEN_WINDOW << 8 | sc->sc_request_r_scale); optp += 4; } if (sc->sc_flags & SCF_TIMESTAMP) { u_int32_t *lp = (u_int32_t *)(optp); /* Form timestamp option as shown in appendix A of RFC 1323. */ *lp++ = htonl(TCPOPT_TSTAMP_HDR); *lp++ = htonl(SYN_CACHE_TIMESTAMP(sc)); *lp = htonl(sc->sc_timestamp); optp += TCPOLEN_TSTAMP_APPA; } #ifdef TCP_SIGNATURE if (sc->sc_flags & SCF_SIGNATURE) { union sockaddr_union src, dst; struct tdb *tdb; bzero(&src, sizeof(union sockaddr_union)); bzero(&dst, sizeof(union sockaddr_union)); src.sa.sa_len = sc->sc_src.sa.sa_len; src.sa.sa_family = sc->sc_src.sa.sa_family; dst.sa.sa_len = sc->sc_dst.sa.sa_len; dst.sa.sa_family = sc->sc_dst.sa.sa_family; switch (sc->sc_src.sa.sa_family) { case 0: /*default to PF_INET*/ case AF_INET: src.sin.sin_addr = mtod(m, struct ip *)->ip_src; dst.sin.sin_addr = mtod(m, struct ip *)->ip_dst; break; #ifdef INET6 case AF_INET6: src.sin6.sin6_addr = mtod(m, struct ip6_hdr *)->ip6_src; dst.sin6.sin6_addr = mtod(m, struct ip6_hdr *)->ip6_dst; break; #endif /* INET6 */ } tdb = gettdbbysrcdst(rtable_l2(sc->sc_rtableid), 0, &src, &dst, IPPROTO_TCP); if (tdb == NULL) { m_freem(m); return (EPERM); } /* Send signature option */ *(optp++) = TCPOPT_SIGNATURE; *(optp++) = TCPOLEN_SIGNATURE; if (tcp_signature(tdb, sc->sc_src.sa.sa_family, m, th, hlen, 0, optp) < 0) { m_freem(m); return (EINVAL); } optp += 16; /* Pad options list to the next 32 bit boundary and * terminate it. */ *optp++ = TCPOPT_NOP; *optp++ = TCPOPT_EOL; } #endif /* TCP_SIGNATURE */ /* Compute the packet's checksum. */ switch (sc->sc_src.sa.sa_family) { case AF_INET: ip->ip_len = htons(tlen - hlen); th->th_sum = 0; th->th_sum = in_cksum(m, tlen); break; #ifdef INET6 case AF_INET6: ip6->ip6_plen = htons(tlen - hlen); th->th_sum = 0; th->th_sum = in6_cksum(m, IPPROTO_TCP, hlen, tlen - hlen); break; #endif } /* use IPsec policy and ttl from listening socket, on SYN ACK */ inp = sc->sc_tp ? sc->sc_tp->t_inpcb : NULL; /* * Fill in some straggling IP bits. Note the stack expects * ip_len to be in host order, for convenience. */ switch (sc->sc_src.sa.sa_family) { case AF_INET: ip->ip_len = htons(tlen); ip->ip_ttl = inp ? inp->inp_ip.ip_ttl : ip_defttl; if (inp != NULL) ip->ip_tos = inp->inp_ip.ip_tos; break; #ifdef INET6 case AF_INET6: ip6->ip6_vfc &= ~IPV6_VERSION_MASK; ip6->ip6_vfc |= IPV6_VERSION; ip6->ip6_plen = htons(tlen - hlen); /* ip6_hlim will be initialized afterwards */ /* leave flowlabel = 0, it is legal and require no state mgmt */ break; #endif } switch (sc->sc_src.sa.sa_family) { case AF_INET: error = ip_output(m, sc->sc_ipopts, &sc->sc_route4, (ip_mtudisc ? IP_MTUDISC : 0), NULL, inp, 0); break; #ifdef INET6 case AF_INET6: ip6->ip6_hlim = in6_selecthlim(inp); error = ip6_output(m, NULL /*XXX*/, &sc->sc_route6, 0, NULL, NULL); break; #endif default: error = EAFNOSUPPORT; break; } return (error); }
./CrossVul/dataset_final_sorted/CWE-20/c/good_1420_1
crossvul-cpp_data_good_2753_0
#include <linux/kernel.h> #include <linux/skbuff.h> #include <linux/export.h> #include <linux/ip.h> #include <linux/ipv6.h> #include <linux/if_vlan.h> #include <net/ip.h> #include <net/ipv6.h> #include <linux/igmp.h> #include <linux/icmp.h> #include <linux/sctp.h> #include <linux/dccp.h> #include <linux/if_tunnel.h> #include <linux/if_pppox.h> #include <linux/ppp_defs.h> #include <linux/stddef.h> #include <linux/if_ether.h> #include <linux/mpls.h> #include <net/flow_dissector.h> #include <scsi/fc/fc_fcoe.h> static bool skb_flow_dissector_uses_key(struct flow_dissector *flow_dissector, enum flow_dissector_key_id key_id) { return flow_dissector->used_keys & (1 << key_id); } static void skb_flow_dissector_set_key(struct flow_dissector *flow_dissector, enum flow_dissector_key_id key_id) { flow_dissector->used_keys |= (1 << key_id); } static void *skb_flow_dissector_target(struct flow_dissector *flow_dissector, enum flow_dissector_key_id key_id, void *target_container) { return ((char *) target_container) + flow_dissector->offset[key_id]; } void skb_flow_dissector_init(struct flow_dissector *flow_dissector, const struct flow_dissector_key *key, unsigned int key_count) { unsigned int i; memset(flow_dissector, 0, sizeof(*flow_dissector)); for (i = 0; i < key_count; i++, key++) { /* User should make sure that every key target offset is withing * boundaries of unsigned short. */ BUG_ON(key->offset > USHRT_MAX); BUG_ON(skb_flow_dissector_uses_key(flow_dissector, key->key_id)); skb_flow_dissector_set_key(flow_dissector, key->key_id); flow_dissector->offset[key->key_id] = key->offset; } /* Ensure that the dissector always includes control and basic key. * That way we are able to avoid handling lack of these in fast path. */ BUG_ON(!skb_flow_dissector_uses_key(flow_dissector, FLOW_DISSECTOR_KEY_CONTROL)); BUG_ON(!skb_flow_dissector_uses_key(flow_dissector, FLOW_DISSECTOR_KEY_BASIC)); } EXPORT_SYMBOL(skb_flow_dissector_init); /** * __skb_flow_get_ports - extract the upper layer ports and return them * @skb: sk_buff to extract the ports from * @thoff: transport header offset * @ip_proto: protocol for which to get port offset * @data: raw buffer pointer to the packet, if NULL use skb->data * @hlen: packet header length, if @data is NULL use skb_headlen(skb) * * The function will try to retrieve the ports at offset thoff + poff where poff * is the protocol port offset returned from proto_ports_offset */ __be32 __skb_flow_get_ports(const struct sk_buff *skb, int thoff, u8 ip_proto, void *data, int hlen) { int poff = proto_ports_offset(ip_proto); if (!data) { data = skb->data; hlen = skb_headlen(skb); } if (poff >= 0) { __be32 *ports, _ports; ports = __skb_header_pointer(skb, thoff + poff, sizeof(_ports), data, hlen, &_ports); if (ports) return *ports; } return 0; } EXPORT_SYMBOL(__skb_flow_get_ports); /** * __skb_flow_dissect - extract the flow_keys struct and return it * @skb: sk_buff to extract the flow from, can be NULL if the rest are specified * @flow_dissector: list of keys to dissect * @target_container: target structure to put dissected values into * @data: raw buffer pointer to the packet, if NULL use skb->data * @proto: protocol for which to get the flow, if @data is NULL use skb->protocol * @nhoff: network header offset, if @data is NULL use skb_network_offset(skb) * @hlen: packet header length, if @data is NULL use skb_headlen(skb) * * The function will try to retrieve individual keys into target specified * by flow_dissector from either the skbuff or a raw buffer specified by the * rest parameters. * * Caller must take care of zeroing target container memory. */ bool __skb_flow_dissect(const struct sk_buff *skb, struct flow_dissector *flow_dissector, void *target_container, void *data, __be16 proto, int nhoff, int hlen) { struct flow_dissector_key_control *key_control; struct flow_dissector_key_basic *key_basic; struct flow_dissector_key_addrs *key_addrs; struct flow_dissector_key_ports *key_ports; struct flow_dissector_key_tags *key_tags; struct flow_dissector_key_keyid *key_keyid; u8 ip_proto = 0; bool ret = false; if (!data) { data = skb->data; proto = skb->protocol; nhoff = skb_network_offset(skb); hlen = skb_headlen(skb); } /* It is ensured by skb_flow_dissector_init() that control key will * be always present. */ key_control = skb_flow_dissector_target(flow_dissector, FLOW_DISSECTOR_KEY_CONTROL, target_container); /* It is ensured by skb_flow_dissector_init() that basic key will * be always present. */ key_basic = skb_flow_dissector_target(flow_dissector, FLOW_DISSECTOR_KEY_BASIC, target_container); if (skb_flow_dissector_uses_key(flow_dissector, FLOW_DISSECTOR_KEY_ETH_ADDRS)) { struct ethhdr *eth = eth_hdr(skb); struct flow_dissector_key_eth_addrs *key_eth_addrs; key_eth_addrs = skb_flow_dissector_target(flow_dissector, FLOW_DISSECTOR_KEY_ETH_ADDRS, target_container); memcpy(key_eth_addrs, &eth->h_dest, sizeof(*key_eth_addrs)); } again: switch (proto) { case htons(ETH_P_IP): { const struct iphdr *iph; struct iphdr _iph; ip: iph = __skb_header_pointer(skb, nhoff, sizeof(_iph), data, hlen, &_iph); if (!iph || iph->ihl < 5) goto out_bad; nhoff += iph->ihl * 4; ip_proto = iph->protocol; if (ip_is_fragment(iph)) ip_proto = 0; if (!skb_flow_dissector_uses_key(flow_dissector, FLOW_DISSECTOR_KEY_IPV4_ADDRS)) break; key_addrs = skb_flow_dissector_target(flow_dissector, FLOW_DISSECTOR_KEY_IPV4_ADDRS, target_container); memcpy(&key_addrs->v4addrs, &iph->saddr, sizeof(key_addrs->v4addrs)); key_control->addr_type = FLOW_DISSECTOR_KEY_IPV4_ADDRS; break; } case htons(ETH_P_IPV6): { const struct ipv6hdr *iph; struct ipv6hdr _iph; __be32 flow_label; ipv6: iph = __skb_header_pointer(skb, nhoff, sizeof(_iph), data, hlen, &_iph); if (!iph) goto out_bad; ip_proto = iph->nexthdr; nhoff += sizeof(struct ipv6hdr); if (skb_flow_dissector_uses_key(flow_dissector, FLOW_DISSECTOR_KEY_IPV6_ADDRS)) { struct flow_dissector_key_ipv6_addrs *key_ipv6_addrs; key_ipv6_addrs = skb_flow_dissector_target(flow_dissector, FLOW_DISSECTOR_KEY_IPV6_ADDRS, target_container); memcpy(key_ipv6_addrs, &iph->saddr, sizeof(*key_ipv6_addrs)); key_control->addr_type = FLOW_DISSECTOR_KEY_IPV6_ADDRS; } flow_label = ip6_flowlabel(iph); if (flow_label) { if (skb_flow_dissector_uses_key(flow_dissector, FLOW_DISSECTOR_KEY_FLOW_LABEL)) { key_tags = skb_flow_dissector_target(flow_dissector, FLOW_DISSECTOR_KEY_FLOW_LABEL, target_container); key_tags->flow_label = ntohl(flow_label); } } break; } case htons(ETH_P_8021AD): case htons(ETH_P_8021Q): { const struct vlan_hdr *vlan; struct vlan_hdr _vlan; vlan = __skb_header_pointer(skb, nhoff, sizeof(_vlan), data, hlen, &_vlan); if (!vlan) goto out_bad; if (skb_flow_dissector_uses_key(flow_dissector, FLOW_DISSECTOR_KEY_VLANID)) { key_tags = skb_flow_dissector_target(flow_dissector, FLOW_DISSECTOR_KEY_VLANID, target_container); key_tags->vlan_id = skb_vlan_tag_get_id(skb); } proto = vlan->h_vlan_encapsulated_proto; nhoff += sizeof(*vlan); goto again; } case htons(ETH_P_PPP_SES): { struct { struct pppoe_hdr hdr; __be16 proto; } *hdr, _hdr; hdr = __skb_header_pointer(skb, nhoff, sizeof(_hdr), data, hlen, &_hdr); if (!hdr) goto out_bad; proto = hdr->proto; nhoff += PPPOE_SES_HLEN; switch (proto) { case htons(PPP_IP): goto ip; case htons(PPP_IPV6): goto ipv6; default: goto out_bad; } } case htons(ETH_P_TIPC): { struct { __be32 pre[3]; __be32 srcnode; } *hdr, _hdr; hdr = __skb_header_pointer(skb, nhoff, sizeof(_hdr), data, hlen, &_hdr); if (!hdr) goto out_bad; if (skb_flow_dissector_uses_key(flow_dissector, FLOW_DISSECTOR_KEY_TIPC_ADDRS)) { key_addrs = skb_flow_dissector_target(flow_dissector, FLOW_DISSECTOR_KEY_TIPC_ADDRS, target_container); key_addrs->tipcaddrs.srcnode = hdr->srcnode; key_control->addr_type = FLOW_DISSECTOR_KEY_TIPC_ADDRS; } goto out_good; } case htons(ETH_P_MPLS_UC): case htons(ETH_P_MPLS_MC): { struct mpls_label *hdr, _hdr[2]; mpls: hdr = __skb_header_pointer(skb, nhoff, sizeof(_hdr), data, hlen, &_hdr); if (!hdr) goto out_bad; if ((ntohl(hdr[0].entry) & MPLS_LS_LABEL_MASK) >> MPLS_LS_LABEL_SHIFT == MPLS_LABEL_ENTROPY) { if (skb_flow_dissector_uses_key(flow_dissector, FLOW_DISSECTOR_KEY_MPLS_ENTROPY)) { key_keyid = skb_flow_dissector_target(flow_dissector, FLOW_DISSECTOR_KEY_MPLS_ENTROPY, target_container); key_keyid->keyid = hdr[1].entry & htonl(MPLS_LS_LABEL_MASK); } goto out_good; } goto out_good; } case htons(ETH_P_FCOE): key_control->thoff = (u16)(nhoff + FCOE_HEADER_LEN); /* fall through */ default: goto out_bad; } ip_proto_again: switch (ip_proto) { case IPPROTO_GRE: { struct gre_hdr { __be16 flags; __be16 proto; } *hdr, _hdr; hdr = __skb_header_pointer(skb, nhoff, sizeof(_hdr), data, hlen, &_hdr); if (!hdr) goto out_bad; /* * Only look inside GRE if version zero and no * routing */ if (hdr->flags & (GRE_VERSION | GRE_ROUTING)) break; proto = hdr->proto; nhoff += 4; if (hdr->flags & GRE_CSUM) nhoff += 4; if (hdr->flags & GRE_KEY) { const __be32 *keyid; __be32 _keyid; keyid = __skb_header_pointer(skb, nhoff, sizeof(_keyid), data, hlen, &_keyid); if (!keyid) goto out_bad; if (skb_flow_dissector_uses_key(flow_dissector, FLOW_DISSECTOR_KEY_GRE_KEYID)) { key_keyid = skb_flow_dissector_target(flow_dissector, FLOW_DISSECTOR_KEY_GRE_KEYID, target_container); key_keyid->keyid = *keyid; } nhoff += 4; } if (hdr->flags & GRE_SEQ) nhoff += 4; if (proto == htons(ETH_P_TEB)) { const struct ethhdr *eth; struct ethhdr _eth; eth = __skb_header_pointer(skb, nhoff, sizeof(_eth), data, hlen, &_eth); if (!eth) goto out_bad; proto = eth->h_proto; nhoff += sizeof(*eth); } goto again; } case NEXTHDR_HOP: case NEXTHDR_ROUTING: case NEXTHDR_DEST: { u8 _opthdr[2], *opthdr; if (proto != htons(ETH_P_IPV6)) break; opthdr = __skb_header_pointer(skb, nhoff, sizeof(_opthdr), data, hlen, &_opthdr); if (!opthdr) goto out_bad; ip_proto = opthdr[0]; nhoff += (opthdr[1] + 1) << 3; goto ip_proto_again; } case IPPROTO_IPIP: proto = htons(ETH_P_IP); goto ip; case IPPROTO_IPV6: proto = htons(ETH_P_IPV6); goto ipv6; case IPPROTO_MPLS: proto = htons(ETH_P_MPLS_UC); goto mpls; default: break; } if (skb_flow_dissector_uses_key(flow_dissector, FLOW_DISSECTOR_KEY_PORTS)) { key_ports = skb_flow_dissector_target(flow_dissector, FLOW_DISSECTOR_KEY_PORTS, target_container); key_ports->ports = __skb_flow_get_ports(skb, nhoff, ip_proto, data, hlen); } out_good: ret = true; out_bad: key_basic->n_proto = proto; key_basic->ip_proto = ip_proto; key_control->thoff = (u16)nhoff; return ret; } EXPORT_SYMBOL(__skb_flow_dissect); static u32 hashrnd __read_mostly; static __always_inline void __flow_hash_secret_init(void) { net_get_random_once(&hashrnd, sizeof(hashrnd)); } static __always_inline u32 __flow_hash_words(u32 *words, u32 length, u32 keyval) { return jhash2(words, length, keyval); } static inline void *flow_keys_hash_start(struct flow_keys *flow) { BUILD_BUG_ON(FLOW_KEYS_HASH_OFFSET % sizeof(u32)); return (void *)flow + FLOW_KEYS_HASH_OFFSET; } static inline size_t flow_keys_hash_length(struct flow_keys *flow) { size_t diff = FLOW_KEYS_HASH_OFFSET + sizeof(flow->addrs); BUILD_BUG_ON((sizeof(*flow) - FLOW_KEYS_HASH_OFFSET) % sizeof(u32)); BUILD_BUG_ON(offsetof(typeof(*flow), addrs) != sizeof(*flow) - sizeof(flow->addrs)); switch (flow->control.addr_type) { case FLOW_DISSECTOR_KEY_IPV4_ADDRS: diff -= sizeof(flow->addrs.v4addrs); break; case FLOW_DISSECTOR_KEY_IPV6_ADDRS: diff -= sizeof(flow->addrs.v6addrs); break; case FLOW_DISSECTOR_KEY_TIPC_ADDRS: diff -= sizeof(flow->addrs.tipcaddrs); break; } return (sizeof(*flow) - diff) / sizeof(u32); } __be32 flow_get_u32_src(const struct flow_keys *flow) { switch (flow->control.addr_type) { case FLOW_DISSECTOR_KEY_IPV4_ADDRS: return flow->addrs.v4addrs.src; case FLOW_DISSECTOR_KEY_IPV6_ADDRS: return (__force __be32)ipv6_addr_hash( &flow->addrs.v6addrs.src); case FLOW_DISSECTOR_KEY_TIPC_ADDRS: return flow->addrs.tipcaddrs.srcnode; default: return 0; } } EXPORT_SYMBOL(flow_get_u32_src); __be32 flow_get_u32_dst(const struct flow_keys *flow) { switch (flow->control.addr_type) { case FLOW_DISSECTOR_KEY_IPV4_ADDRS: return flow->addrs.v4addrs.dst; case FLOW_DISSECTOR_KEY_IPV6_ADDRS: return (__force __be32)ipv6_addr_hash( &flow->addrs.v6addrs.dst); default: return 0; } } EXPORT_SYMBOL(flow_get_u32_dst); static inline void __flow_hash_consistentify(struct flow_keys *keys) { int addr_diff, i; switch (keys->control.addr_type) { case FLOW_DISSECTOR_KEY_IPV4_ADDRS: addr_diff = (__force u32)keys->addrs.v4addrs.dst - (__force u32)keys->addrs.v4addrs.src; if ((addr_diff < 0) || (addr_diff == 0 && ((__force u16)keys->ports.dst < (__force u16)keys->ports.src))) { swap(keys->addrs.v4addrs.src, keys->addrs.v4addrs.dst); swap(keys->ports.src, keys->ports.dst); } break; case FLOW_DISSECTOR_KEY_IPV6_ADDRS: addr_diff = memcmp(&keys->addrs.v6addrs.dst, &keys->addrs.v6addrs.src, sizeof(keys->addrs.v6addrs.dst)); if ((addr_diff < 0) || (addr_diff == 0 && ((__force u16)keys->ports.dst < (__force u16)keys->ports.src))) { for (i = 0; i < 4; i++) swap(keys->addrs.v6addrs.src.s6_addr32[i], keys->addrs.v6addrs.dst.s6_addr32[i]); swap(keys->ports.src, keys->ports.dst); } break; } } static inline u32 __flow_hash_from_keys(struct flow_keys *keys, u32 keyval) { u32 hash; __flow_hash_consistentify(keys); hash = __flow_hash_words((u32 *)flow_keys_hash_start(keys), flow_keys_hash_length(keys), keyval); if (!hash) hash = 1; return hash; } u32 flow_hash_from_keys(struct flow_keys *keys) { __flow_hash_secret_init(); return __flow_hash_from_keys(keys, hashrnd); } EXPORT_SYMBOL(flow_hash_from_keys); static inline u32 ___skb_get_hash(const struct sk_buff *skb, struct flow_keys *keys, u32 keyval) { if (!skb_flow_dissect_flow_keys(skb, keys)) return 0; return __flow_hash_from_keys(keys, keyval); } struct _flow_keys_digest_data { __be16 n_proto; u8 ip_proto; u8 padding; __be32 ports; __be32 src; __be32 dst; }; void make_flow_keys_digest(struct flow_keys_digest *digest, const struct flow_keys *flow) { struct _flow_keys_digest_data *data = (struct _flow_keys_digest_data *)digest; BUILD_BUG_ON(sizeof(*data) > sizeof(*digest)); memset(digest, 0, sizeof(*digest)); data->n_proto = flow->basic.n_proto; data->ip_proto = flow->basic.ip_proto; data->ports = flow->ports.ports; data->src = flow->addrs.v4addrs.src; data->dst = flow->addrs.v4addrs.dst; } EXPORT_SYMBOL(make_flow_keys_digest); /** * __skb_get_hash: calculate a flow hash * @skb: sk_buff to calculate flow hash from * * This function calculates a flow hash based on src/dst addresses * and src/dst port numbers. Sets hash in skb to non-zero hash value * on success, zero indicates no valid hash. Also, sets l4_hash in skb * if hash is a canonical 4-tuple hash over transport ports. */ void __skb_get_hash(struct sk_buff *skb) { struct flow_keys keys; u32 hash; __flow_hash_secret_init(); hash = ___skb_get_hash(skb, &keys, hashrnd); if (!hash) return; __skb_set_sw_hash(skb, hash, flow_keys_have_l4(&keys)); } EXPORT_SYMBOL(__skb_get_hash); __u32 skb_get_hash_perturb(const struct sk_buff *skb, u32 perturb) { struct flow_keys keys; return ___skb_get_hash(skb, &keys, perturb); } EXPORT_SYMBOL(skb_get_hash_perturb); __u32 __skb_get_hash_flowi6(struct sk_buff *skb, struct flowi6 *fl6) { struct flow_keys keys; memset(&keys, 0, sizeof(keys)); memcpy(&keys.addrs.v6addrs.src, &fl6->saddr, sizeof(keys.addrs.v6addrs.src)); memcpy(&keys.addrs.v6addrs.dst, &fl6->daddr, sizeof(keys.addrs.v6addrs.dst)); keys.control.addr_type = FLOW_DISSECTOR_KEY_IPV6_ADDRS; keys.ports.src = fl6->fl6_sport; keys.ports.dst = fl6->fl6_dport; keys.keyid.keyid = fl6->fl6_gre_key; keys.tags.flow_label = (__force u32)fl6->flowlabel; keys.basic.ip_proto = fl6->flowi6_proto; __skb_set_sw_hash(skb, flow_hash_from_keys(&keys), flow_keys_have_l4(&keys)); return skb->hash; } EXPORT_SYMBOL(__skb_get_hash_flowi6); __u32 __skb_get_hash_flowi4(struct sk_buff *skb, struct flowi4 *fl4) { struct flow_keys keys; memset(&keys, 0, sizeof(keys)); keys.addrs.v4addrs.src = fl4->saddr; keys.addrs.v4addrs.dst = fl4->daddr; keys.control.addr_type = FLOW_DISSECTOR_KEY_IPV4_ADDRS; keys.ports.src = fl4->fl4_sport; keys.ports.dst = fl4->fl4_dport; keys.keyid.keyid = fl4->fl4_gre_key; keys.basic.ip_proto = fl4->flowi4_proto; __skb_set_sw_hash(skb, flow_hash_from_keys(&keys), flow_keys_have_l4(&keys)); return skb->hash; } EXPORT_SYMBOL(__skb_get_hash_flowi4); u32 __skb_get_poff(const struct sk_buff *skb, void *data, const struct flow_keys *keys, int hlen) { u32 poff = keys->control.thoff; switch (keys->basic.ip_proto) { case IPPROTO_TCP: { /* access doff as u8 to avoid unaligned access */ const u8 *doff; u8 _doff; doff = __skb_header_pointer(skb, poff + 12, sizeof(_doff), data, hlen, &_doff); if (!doff) return poff; poff += max_t(u32, sizeof(struct tcphdr), (*doff & 0xF0) >> 2); break; } case IPPROTO_UDP: case IPPROTO_UDPLITE: poff += sizeof(struct udphdr); break; /* For the rest, we do not really care about header * extensions at this point for now. */ case IPPROTO_ICMP: poff += sizeof(struct icmphdr); break; case IPPROTO_ICMPV6: poff += sizeof(struct icmp6hdr); break; case IPPROTO_IGMP: poff += sizeof(struct igmphdr); break; case IPPROTO_DCCP: poff += sizeof(struct dccp_hdr); break; case IPPROTO_SCTP: poff += sizeof(struct sctphdr); break; } return poff; } /** * skb_get_poff - get the offset to the payload * @skb: sk_buff to get the payload offset from * * The function will get the offset to the payload as far as it could * be dissected. The main user is currently BPF, so that we can dynamically * truncate packets without needing to push actual payload to the user * space and can analyze headers only, instead. */ u32 skb_get_poff(const struct sk_buff *skb) { struct flow_keys keys; if (!skb_flow_dissect_flow_keys(skb, &keys)) return 0; return __skb_get_poff(skb, skb->data, &keys, skb_headlen(skb)); } static const struct flow_dissector_key flow_keys_dissector_keys[] = { { .key_id = FLOW_DISSECTOR_KEY_CONTROL, .offset = offsetof(struct flow_keys, control), }, { .key_id = FLOW_DISSECTOR_KEY_BASIC, .offset = offsetof(struct flow_keys, basic), }, { .key_id = FLOW_DISSECTOR_KEY_IPV4_ADDRS, .offset = offsetof(struct flow_keys, addrs.v4addrs), }, { .key_id = FLOW_DISSECTOR_KEY_IPV6_ADDRS, .offset = offsetof(struct flow_keys, addrs.v6addrs), }, { .key_id = FLOW_DISSECTOR_KEY_TIPC_ADDRS, .offset = offsetof(struct flow_keys, addrs.tipcaddrs), }, { .key_id = FLOW_DISSECTOR_KEY_PORTS, .offset = offsetof(struct flow_keys, ports), }, { .key_id = FLOW_DISSECTOR_KEY_VLANID, .offset = offsetof(struct flow_keys, tags), }, { .key_id = FLOW_DISSECTOR_KEY_FLOW_LABEL, .offset = offsetof(struct flow_keys, tags), }, { .key_id = FLOW_DISSECTOR_KEY_GRE_KEYID, .offset = offsetof(struct flow_keys, keyid), }, }; static const struct flow_dissector_key flow_keys_buf_dissector_keys[] = { { .key_id = FLOW_DISSECTOR_KEY_CONTROL, .offset = offsetof(struct flow_keys, control), }, { .key_id = FLOW_DISSECTOR_KEY_BASIC, .offset = offsetof(struct flow_keys, basic), }, }; struct flow_dissector flow_keys_dissector __read_mostly; EXPORT_SYMBOL(flow_keys_dissector); struct flow_dissector flow_keys_buf_dissector __read_mostly; static int __init init_default_flow_dissectors(void) { skb_flow_dissector_init(&flow_keys_dissector, flow_keys_dissector_keys, ARRAY_SIZE(flow_keys_dissector_keys)); skb_flow_dissector_init(&flow_keys_buf_dissector, flow_keys_buf_dissector_keys, ARRAY_SIZE(flow_keys_buf_dissector_keys)); return 0; } late_initcall_sync(init_default_flow_dissectors);
./CrossVul/dataset_final_sorted/CWE-20/c/good_2753_0
crossvul-cpp_data_bad_4900_2
/* vi:set ts=8 sts=4 sw=4 noet: * * VIM - Vi IMproved by Bram Moolenaar * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. * See README.txt for an overview of the Vim source code. */ #include "vim.h" #ifdef AMIGA # include <time.h> /* for time() */ #endif /* * Vim originated from Stevie version 3.6 (Fish disk 217) by GRWalter (Fred) * It has been changed beyond recognition since then. * * Differences between version 7.4 and 8.x can be found with ":help version8". * Differences between version 6.4 and 7.x can be found with ":help version7". * Differences between version 5.8 and 6.x can be found with ":help version6". * Differences between version 4.x and 5.x can be found with ":help version5". * Differences between version 3.0 and 4.x can be found with ":help version4". * All the remarks about older versions have been removed, they are not very * interesting. */ #include "version.h" char *Version = VIM_VERSION_SHORT; static char *mediumVersion = VIM_VERSION_MEDIUM; #if defined(HAVE_DATE_TIME) || defined(PROTO) # if (defined(VMS) && defined(VAXC)) || defined(PROTO) char longVersion[sizeof(VIM_VERSION_LONG_DATE) + sizeof(__DATE__) + sizeof(__TIME__) + 3]; void make_version(void) { /* * Construct the long version string. Necessary because * VAX C can't catenate strings in the preprocessor. */ strcpy(longVersion, VIM_VERSION_LONG_DATE); strcat(longVersion, __DATE__); strcat(longVersion, " "); strcat(longVersion, __TIME__); strcat(longVersion, ")"); } # else char *longVersion = VIM_VERSION_LONG_DATE __DATE__ " " __TIME__ ")"; # endif #else char *longVersion = VIM_VERSION_LONG; #endif static void list_features(void); static void version_msg(char *s); static char *(features[]) = { #ifdef HAVE_ACL "+acl", #else "-acl", #endif #ifdef AMIGA /* only for Amiga systems */ # ifdef FEAT_ARP "+ARP", # else "-ARP", # endif #endif #ifdef FEAT_ARABIC "+arabic", #else "-arabic", #endif #ifdef FEAT_AUTOCMD "+autocmd", #else "-autocmd", #endif #ifdef FEAT_BEVAL "+balloon_eval", #else "-balloon_eval", #endif #ifdef FEAT_BROWSE "+browse", #else "-browse", #endif #ifdef NO_BUILTIN_TCAPS "-builtin_terms", #endif #ifdef SOME_BUILTIN_TCAPS "+builtin_terms", #endif #ifdef ALL_BUILTIN_TCAPS "++builtin_terms", #endif #ifdef FEAT_BYTEOFF "+byte_offset", #else "-byte_offset", #endif #ifdef FEAT_JOB_CHANNEL "+channel", #else "-channel", #endif #ifdef FEAT_CINDENT "+cindent", #else "-cindent", #endif #ifdef FEAT_CLIENTSERVER "+clientserver", #else "-clientserver", #endif #ifdef FEAT_CLIPBOARD "+clipboard", #else "-clipboard", #endif #ifdef FEAT_CMDL_COMPL "+cmdline_compl", #else "-cmdline_compl", #endif #ifdef FEAT_CMDHIST "+cmdline_hist", #else "-cmdline_hist", #endif #ifdef FEAT_CMDL_INFO "+cmdline_info", #else "-cmdline_info", #endif #ifdef FEAT_COMMENTS "+comments", #else "-comments", #endif #ifdef FEAT_CONCEAL "+conceal", #else "-conceal", #endif #ifdef FEAT_CRYPT "+cryptv", #else "-cryptv", #endif #ifdef FEAT_CSCOPE "+cscope", #else "-cscope", #endif #ifdef FEAT_CURSORBIND "+cursorbind", #else "-cursorbind", #endif #ifdef CURSOR_SHAPE "+cursorshape", #else "-cursorshape", #endif #if defined(FEAT_CON_DIALOG) && defined(FEAT_GUI_DIALOG) "+dialog_con_gui", #else # if defined(FEAT_CON_DIALOG) "+dialog_con", # else # if defined(FEAT_GUI_DIALOG) "+dialog_gui", # else "-dialog", # endif # endif #endif #ifdef FEAT_DIFF "+diff", #else "-diff", #endif #ifdef FEAT_DIGRAPHS "+digraphs", #else "-digraphs", #endif #ifdef FEAT_GUI_W32 # ifdef FEAT_DIRECTX "+directx", # else "-directx", # endif #endif #ifdef FEAT_DND "+dnd", #else "-dnd", #endif #ifdef EBCDIC "+ebcdic", #else "-ebcdic", #endif #ifdef FEAT_EMACS_TAGS "+emacs_tags", #else "-emacs_tags", #endif #ifdef FEAT_EVAL "+eval", #else "-eval", #endif "+ex_extra", #ifdef FEAT_SEARCH_EXTRA "+extra_search", #else "-extra_search", #endif #ifdef FEAT_FKMAP "+farsi", #else "-farsi", #endif #ifdef FEAT_SEARCHPATH "+file_in_path", #else "-file_in_path", #endif #ifdef FEAT_FIND_ID "+find_in_path", #else "-find_in_path", #endif #ifdef FEAT_FLOAT "+float", #else "-float", #endif #ifdef FEAT_FOLDING "+folding", #else "-folding", #endif #ifdef FEAT_FOOTER "+footer", #else "-footer", #endif /* only interesting on Unix systems */ #if !defined(USE_SYSTEM) && defined(UNIX) "+fork()", #endif #ifdef FEAT_GETTEXT # ifdef DYNAMIC_GETTEXT "+gettext/dyn", # else "+gettext", # endif #else "-gettext", #endif #ifdef FEAT_HANGULIN "+hangul_input", #else "-hangul_input", #endif #if (defined(HAVE_ICONV_H) && defined(USE_ICONV)) || defined(DYNAMIC_ICONV) # ifdef DYNAMIC_ICONV "+iconv/dyn", # else "+iconv", # endif #else "-iconv", #endif #ifdef FEAT_INS_EXPAND "+insert_expand", #else "-insert_expand", #endif #ifdef FEAT_JOB_CHANNEL "+job", #else "-job", #endif #ifdef FEAT_JUMPLIST "+jumplist", #else "-jumplist", #endif #ifdef FEAT_KEYMAP "+keymap", #else "-keymap", #endif #ifdef FEAT_EVAL "+lambda", #else "-lambda", #endif #ifdef FEAT_LANGMAP "+langmap", #else "-langmap", #endif #ifdef FEAT_LIBCALL "+libcall", #else "-libcall", #endif #ifdef FEAT_LINEBREAK "+linebreak", #else "-linebreak", #endif #ifdef FEAT_LISP "+lispindent", #else "-lispindent", #endif #ifdef FEAT_LISTCMDS "+listcmds", #else "-listcmds", #endif #ifdef FEAT_LOCALMAP "+localmap", #else "-localmap", #endif #ifdef FEAT_LUA # ifdef DYNAMIC_LUA "+lua/dyn", # else "+lua", # endif #else "-lua", #endif #ifdef FEAT_MENU "+menu", #else "-menu", #endif #ifdef FEAT_SESSION "+mksession", #else "-mksession", #endif #ifdef FEAT_MODIFY_FNAME "+modify_fname", #else "-modify_fname", #endif #ifdef FEAT_MOUSE "+mouse", # ifdef FEAT_MOUSESHAPE "+mouseshape", # else "-mouseshape", # endif # else "-mouse", #endif #if defined(UNIX) || defined(VMS) # ifdef FEAT_MOUSE_DEC "+mouse_dec", # else "-mouse_dec", # endif # ifdef FEAT_MOUSE_GPM "+mouse_gpm", # else "-mouse_gpm", # endif # ifdef FEAT_MOUSE_JSB "+mouse_jsbterm", # else "-mouse_jsbterm", # endif # ifdef FEAT_MOUSE_NET "+mouse_netterm", # else "-mouse_netterm", # endif #endif #ifdef __QNX__ # ifdef FEAT_MOUSE_PTERM "+mouse_pterm", # else "-mouse_pterm", # endif #endif #if defined(UNIX) || defined(VMS) # ifdef FEAT_MOUSE_SGR "+mouse_sgr", # else "-mouse_sgr", # endif # ifdef FEAT_SYSMOUSE "+mouse_sysmouse", # else "-mouse_sysmouse", # endif # ifdef FEAT_MOUSE_URXVT "+mouse_urxvt", # else "-mouse_urxvt", # endif # ifdef FEAT_MOUSE_XTERM "+mouse_xterm", # else "-mouse_xterm", # endif #endif #ifdef FEAT_MBYTE_IME # ifdef DYNAMIC_IME "+multi_byte_ime/dyn", # else "+multi_byte_ime", # endif #else # ifdef FEAT_MBYTE "+multi_byte", # else "-multi_byte", # endif #endif #ifdef FEAT_MULTI_LANG "+multi_lang", #else "-multi_lang", #endif #ifdef FEAT_MZSCHEME # ifdef DYNAMIC_MZSCHEME "+mzscheme/dyn", # else "+mzscheme", # endif #else "-mzscheme", #endif #ifdef FEAT_NETBEANS_INTG "+netbeans_intg", #else "-netbeans_intg", #endif #ifdef FEAT_NUM64 "+num64", #else "-num64", #endif #ifdef FEAT_GUI_W32 # ifdef FEAT_OLE "+ole", # else "-ole", # endif #endif "+packages", #ifdef FEAT_PATH_EXTRA "+path_extra", #else "-path_extra", #endif #ifdef FEAT_PERL # ifdef DYNAMIC_PERL "+perl/dyn", # else "+perl", # endif #else "-perl", #endif #ifdef FEAT_PERSISTENT_UNDO "+persistent_undo", #else "-persistent_undo", #endif #ifdef FEAT_PRINTER # ifdef FEAT_POSTSCRIPT "+postscript", # else "-postscript", # endif "+printer", #else "-printer", #endif #ifdef FEAT_PROFILE "+profile", #else "-profile", #endif #ifdef FEAT_PYTHON # ifdef DYNAMIC_PYTHON "+python/dyn", # else "+python", # endif #else "-python", #endif #ifdef FEAT_PYTHON3 # ifdef DYNAMIC_PYTHON3 "+python3/dyn", # else "+python3", # endif #else "-python3", #endif #ifdef FEAT_QUICKFIX "+quickfix", #else "-quickfix", #endif #ifdef FEAT_RELTIME "+reltime", #else "-reltime", #endif #ifdef FEAT_RIGHTLEFT "+rightleft", #else "-rightleft", #endif #ifdef FEAT_RUBY # ifdef DYNAMIC_RUBY "+ruby/dyn", # else "+ruby", # endif #else "-ruby", #endif #ifdef FEAT_SCROLLBIND "+scrollbind", #else "-scrollbind", #endif #ifdef FEAT_SIGNS "+signs", #else "-signs", #endif #ifdef FEAT_SMARTINDENT "+smartindent", #else "-smartindent", #endif #ifdef STARTUPTIME "+startuptime", #else "-startuptime", #endif #ifdef FEAT_STL_OPT "+statusline", #else "-statusline", #endif #ifdef FEAT_SUN_WORKSHOP "+sun_workshop", #else "-sun_workshop", #endif #ifdef FEAT_SYN_HL "+syntax", #else "-syntax", #endif /* only interesting on Unix systems */ #if defined(USE_SYSTEM) && defined(UNIX) "+system()", #endif #ifdef FEAT_TAG_BINS "+tag_binary", #else "-tag_binary", #endif #ifdef FEAT_TAG_OLDSTATIC "+tag_old_static", #else "-tag_old_static", #endif #ifdef FEAT_TAG_ANYWHITE "+tag_any_white", #else "-tag_any_white", #endif #ifdef FEAT_TCL # ifdef DYNAMIC_TCL "+tcl/dyn", # else "+tcl", # endif #else "-tcl", #endif #ifdef FEAT_TERMGUICOLORS "+termguicolors", #else "-termguicolors", #endif #if defined(UNIX) /* only Unix can have terminfo instead of termcap */ # ifdef TERMINFO "+terminfo", # else "-terminfo", # endif #else /* unix always includes termcap support */ # ifdef HAVE_TGETENT "+tgetent", # else "-tgetent", # endif #endif #ifdef FEAT_TERMRESPONSE "+termresponse", #else "-termresponse", #endif #ifdef FEAT_TEXTOBJ "+textobjects", #else "-textobjects", #endif #ifdef FEAT_TIMERS "+timers", #else "-timers", #endif #ifdef FEAT_TITLE "+title", #else "-title", #endif #ifdef FEAT_TOOLBAR "+toolbar", #else "-toolbar", #endif #ifdef FEAT_USR_CMDS "+user_commands", #else "-user_commands", #endif #ifdef FEAT_WINDOWS "+vertsplit", #else "-vertsplit", #endif #ifdef FEAT_VIRTUALEDIT "+virtualedit", #else "-virtualedit", #endif "+visual", #ifdef FEAT_VISUALEXTRA "+visualextra", #else "-visualextra", #endif #ifdef FEAT_VIMINFO "+viminfo", #else "-viminfo", #endif #ifdef FEAT_VREPLACE "+vreplace", #else "-vreplace", #endif #ifdef FEAT_WILDIGN "+wildignore", #else "-wildignore", #endif #ifdef FEAT_WILDMENU "+wildmenu", #else "-wildmenu", #endif #ifdef FEAT_WINDOWS "+windows", #else "-windows", #endif #ifdef FEAT_WRITEBACKUP "+writebackup", #else "-writebackup", #endif #if defined(UNIX) || defined(VMS) # ifdef FEAT_X11 "+X11", # else "-X11", # endif #endif #ifdef FEAT_XFONTSET "+xfontset", #else "-xfontset", #endif #ifdef FEAT_XIM "+xim", #else "-xim", #endif #ifdef WIN3264 # ifdef FEAT_XPM_W32 "+xpm_w32", # else "-xpm_w32", # endif #else # ifdef HAVE_XPM "+xpm", # else "-xpm", # endif #endif #if defined(UNIX) || defined(VMS) # ifdef USE_XSMP_INTERACT "+xsmp_interact", # else # ifdef USE_XSMP "+xsmp", # else "-xsmp", # endif # endif # ifdef FEAT_XCLIPBOARD "+xterm_clipboard", # else "-xterm_clipboard", # endif #endif #ifdef FEAT_XTERM_SAVE "+xterm_save", #else "-xterm_save", #endif NULL }; static int included_patches[] = { /* Add new patch number below this line */ /**/ 55, /**/ 54, /**/ 53, /**/ 52, /**/ 51, /**/ 50, /**/ 49, /**/ 48, /**/ 47, /**/ 46, /**/ 45, /**/ 44, /**/ 43, /**/ 42, /**/ 41, /**/ 40, /**/ 39, /**/ 38, /**/ 37, /**/ 36, /**/ 35, /**/ 34, /**/ 33, /**/ 32, /**/ 31, /**/ 30, /**/ 29, /**/ 28, /**/ 27, /**/ 26, /**/ 25, /**/ 24, /**/ 23, /**/ 22, /**/ 21, /**/ 20, /**/ 19, /**/ 18, /**/ 17, /**/ 16, /**/ 15, /**/ 14, /**/ 13, /**/ 12, /**/ 11, /**/ 10, /**/ 9, /**/ 8, /**/ 7, /**/ 6, /**/ 5, /**/ 4, /**/ 3, /**/ 2, /**/ 1, /**/ 0 }; /* * Place to put a short description when adding a feature with a patch. * Keep it short, e.g.,: "relative numbers", "persistent undo". * Also add a comment marker to separate the lines. * See the official Vim patches for the diff format: It must use a context of * one line only. Create it by hand or use "diff -C2" and edit the patch. */ static char *(extra_patches[]) = { /* Add your patch description below this line */ /**/ NULL }; int highest_patch(void) { int i; int h = 0; for (i = 0; included_patches[i] != 0; ++i) if (included_patches[i] > h) h = included_patches[i]; return h; } #if defined(FEAT_EVAL) || defined(PROTO) /* * Return TRUE if patch "n" has been included. */ int has_patch(int n) { int i; for (i = 0; included_patches[i] != 0; ++i) if (included_patches[i] == n) return TRUE; return FALSE; } #endif void ex_version(exarg_T *eap) { /* * Ignore a ":version 9.99" command. */ if (*eap->arg == NUL) { msg_putchar('\n'); list_version(); } } /* * List all features aligned in columns, dictionary style. */ static void list_features(void) { int i; int ncol; int nrow; int nfeat = 0; int width = 0; /* Find the length of the longest feature name, use that + 1 as the column * width */ for (i = 0; features[i] != NULL; ++i) { int l = (int)STRLEN(features[i]); if (l > width) width = l; ++nfeat; } width += 1; if (Columns < width) { /* Not enough screen columns - show one per line */ for (i = 0; features[i] != NULL; ++i) { version_msg(features[i]); if (msg_col > 0) msg_putchar('\n'); } return; } /* The rightmost column doesn't need a separator. * Sacrifice it to fit in one more column if possible. */ ncol = (int) (Columns + 1) / width; nrow = nfeat / ncol + (nfeat % ncol ? 1 : 0); /* i counts columns then rows. idx counts rows then columns. */ for (i = 0; !got_int && i < nrow * ncol; ++i) { int idx = (i / ncol) + (i % ncol) * nrow; if (idx < nfeat) { int last_col = (i + 1) % ncol == 0; msg_puts((char_u *)features[idx]); if (last_col) { if (msg_col > 0) msg_putchar('\n'); } else { while (msg_col % width) msg_putchar(' '); } } else { if (msg_col > 0) msg_putchar('\n'); } } } void list_version(void) { int i; int first; char *s = ""; /* * When adding features here, don't forget to update the list of * internal variables in eval.c! */ MSG(longVersion); #ifdef WIN3264 # ifdef FEAT_GUI_W32 # ifdef _WIN64 MSG_PUTS(_("\nMS-Windows 64-bit GUI version")); # else MSG_PUTS(_("\nMS-Windows 32-bit GUI version")); # endif # ifdef FEAT_OLE MSG_PUTS(_(" with OLE support")); # endif # else # ifdef _WIN64 MSG_PUTS(_("\nMS-Windows 64-bit console version")); # else MSG_PUTS(_("\nMS-Windows 32-bit console version")); # endif # endif #endif #ifdef MACOS # ifdef MACOS_X # ifdef MACOS_X_UNIX MSG_PUTS(_("\nMacOS X (unix) version")); # else MSG_PUTS(_("\nMacOS X version")); # endif #else MSG_PUTS(_("\nMacOS version")); # endif #endif #ifdef VMS MSG_PUTS(_("\nOpenVMS version")); # ifdef HAVE_PATHDEF if (*compiled_arch != NUL) { MSG_PUTS(" - "); MSG_PUTS(compiled_arch); } # endif #endif /* Print the list of patch numbers if there is at least one. */ /* Print a range when patches are consecutive: "1-10, 12, 15-40, 42-45" */ if (included_patches[0] != 0) { MSG_PUTS(_("\nIncluded patches: ")); first = -1; /* find last one */ for (i = 0; included_patches[i] != 0; ++i) ; while (--i >= 0) { if (first < 0) first = included_patches[i]; if (i == 0 || included_patches[i - 1] != included_patches[i] + 1) { MSG_PUTS(s); s = ", "; msg_outnum((long)first); if (first != included_patches[i]) { MSG_PUTS("-"); msg_outnum((long)included_patches[i]); } first = -1; } } } /* Print the list of extra patch descriptions if there is at least one. */ if (extra_patches[0] != NULL) { MSG_PUTS(_("\nExtra patches: ")); s = ""; for (i = 0; extra_patches[i] != NULL; ++i) { MSG_PUTS(s); s = ", "; MSG_PUTS(extra_patches[i]); } } #ifdef MODIFIED_BY MSG_PUTS("\n"); MSG_PUTS(_("Modified by ")); MSG_PUTS(MODIFIED_BY); #endif #ifdef HAVE_PATHDEF if (*compiled_user != NUL || *compiled_sys != NUL) { MSG_PUTS(_("\nCompiled ")); if (*compiled_user != NUL) { MSG_PUTS(_("by ")); MSG_PUTS(compiled_user); } if (*compiled_sys != NUL) { MSG_PUTS("@"); MSG_PUTS(compiled_sys); } } #endif #ifdef FEAT_HUGE MSG_PUTS(_("\nHuge version ")); #else # ifdef FEAT_BIG MSG_PUTS(_("\nBig version ")); # else # ifdef FEAT_NORMAL MSG_PUTS(_("\nNormal version ")); # else # ifdef FEAT_SMALL MSG_PUTS(_("\nSmall version ")); # else MSG_PUTS(_("\nTiny version ")); # endif # endif # endif #endif #ifndef FEAT_GUI MSG_PUTS(_("without GUI.")); #else # ifdef FEAT_GUI_GTK # ifdef USE_GTK3 MSG_PUTS(_("with GTK3 GUI.")); # else # ifdef FEAT_GUI_GNOME MSG_PUTS(_("with GTK2-GNOME GUI.")); # else MSG_PUTS(_("with GTK2 GUI.")); # endif # endif # else # ifdef FEAT_GUI_MOTIF MSG_PUTS(_("with X11-Motif GUI.")); # else # ifdef FEAT_GUI_ATHENA # ifdef FEAT_GUI_NEXTAW MSG_PUTS(_("with X11-neXtaw GUI.")); # else MSG_PUTS(_("with X11-Athena GUI.")); # endif # else # ifdef FEAT_GUI_PHOTON MSG_PUTS(_("with Photon GUI.")); # else # if defined(MSWIN) MSG_PUTS(_("with GUI.")); # else # if defined(TARGET_API_MAC_CARBON) && TARGET_API_MAC_CARBON MSG_PUTS(_("with Carbon GUI.")); # else # if defined(TARGET_API_MAC_OSX) && TARGET_API_MAC_OSX MSG_PUTS(_("with Cocoa GUI.")); # else # if defined(MACOS) MSG_PUTS(_("with (classic) GUI.")); # endif # endif # endif # endif # endif # endif # endif # endif #endif version_msg(_(" Features included (+) or not (-):\n")); list_features(); #ifdef SYS_VIMRC_FILE version_msg(_(" system vimrc file: \"")); version_msg(SYS_VIMRC_FILE); version_msg("\"\n"); #endif #ifdef USR_VIMRC_FILE version_msg(_(" user vimrc file: \"")); version_msg(USR_VIMRC_FILE); version_msg("\"\n"); #endif #ifdef USR_VIMRC_FILE2 version_msg(_(" 2nd user vimrc file: \"")); version_msg(USR_VIMRC_FILE2); version_msg("\"\n"); #endif #ifdef USR_VIMRC_FILE3 version_msg(_(" 3rd user vimrc file: \"")); version_msg(USR_VIMRC_FILE3); version_msg("\"\n"); #endif #ifdef USR_EXRC_FILE version_msg(_(" user exrc file: \"")); version_msg(USR_EXRC_FILE); version_msg("\"\n"); #endif #ifdef USR_EXRC_FILE2 version_msg(_(" 2nd user exrc file: \"")); version_msg(USR_EXRC_FILE2); version_msg("\"\n"); #endif #ifdef FEAT_GUI # ifdef SYS_GVIMRC_FILE version_msg(_(" system gvimrc file: \"")); version_msg(SYS_GVIMRC_FILE); version_msg("\"\n"); # endif version_msg(_(" user gvimrc file: \"")); version_msg(USR_GVIMRC_FILE); version_msg("\"\n"); # ifdef USR_GVIMRC_FILE2 version_msg(_("2nd user gvimrc file: \"")); version_msg(USR_GVIMRC_FILE2); version_msg("\"\n"); # endif # ifdef USR_GVIMRC_FILE3 version_msg(_("3rd user gvimrc file: \"")); version_msg(USR_GVIMRC_FILE3); version_msg("\"\n"); # endif #endif version_msg(_(" defaults file: \"")); version_msg(VIM_DEFAULTS_FILE); version_msg("\"\n"); #ifdef FEAT_GUI # ifdef SYS_MENU_FILE version_msg(_(" system menu file: \"")); version_msg(SYS_MENU_FILE); version_msg("\"\n"); # endif #endif #ifdef HAVE_PATHDEF if (*default_vim_dir != NUL) { version_msg(_(" fall-back for $VIM: \"")); version_msg((char *)default_vim_dir); version_msg("\"\n"); } if (*default_vimruntime_dir != NUL) { version_msg(_(" f-b for $VIMRUNTIME: \"")); version_msg((char *)default_vimruntime_dir); version_msg("\"\n"); } version_msg(_("Compilation: ")); version_msg((char *)all_cflags); version_msg("\n"); #ifdef VMS if (*compiler_version != NUL) { version_msg(_("Compiler: ")); version_msg((char *)compiler_version); version_msg("\n"); } #endif version_msg(_("Linking: ")); version_msg((char *)all_lflags); #endif #ifdef DEBUG version_msg("\n"); version_msg(_(" DEBUG BUILD")); #endif } /* * Output a string for the version message. If it's going to wrap, output a * newline, unless the message is too long to fit on the screen anyway. */ static void version_msg(char *s) { int len = (int)STRLEN(s); if (!got_int && len < (int)Columns && msg_col + len >= (int)Columns && *s != '\n') msg_putchar('\n'); if (!got_int) MSG_PUTS(s); } static void do_intro_line(int row, char_u *mesg, int add_version, int attr); /* * Show the intro message when not editing a file. */ void maybe_intro_message(void) { if (bufempty() && curbuf->b_fname == NULL #ifdef FEAT_WINDOWS && firstwin->w_next == NULL #endif && vim_strchr(p_shm, SHM_INTRO) == NULL) intro_message(FALSE); } /* * Give an introductory message about Vim. * Only used when starting Vim on an empty file, without a file name. * Or with the ":intro" command (for Sven :-). */ void intro_message( int colon) /* TRUE for ":intro" */ { int i; int row; int blanklines; int sponsor; char *p; static char *(lines[]) = { N_("VIM - Vi IMproved"), "", N_("version "), N_("by Bram Moolenaar et al."), #ifdef MODIFIED_BY " ", #endif N_("Vim is open source and freely distributable"), "", N_("Help poor children in Uganda!"), N_("type :help iccf<Enter> for information "), "", N_("type :q<Enter> to exit "), N_("type :help<Enter> or <F1> for on-line help"), N_("type :help version8<Enter> for version info"), NULL, "", N_("Running in Vi compatible mode"), N_("type :set nocp<Enter> for Vim defaults"), N_("type :help cp-default<Enter> for info on this"), }; #ifdef FEAT_GUI static char *(gui_lines[]) = { NULL, NULL, NULL, NULL, #ifdef MODIFIED_BY NULL, #endif NULL, NULL, NULL, N_("menu Help->Orphans for information "), NULL, N_("Running modeless, typed text is inserted"), N_("menu Edit->Global Settings->Toggle Insert Mode "), N_(" for two modes "), NULL, NULL, NULL, N_("menu Edit->Global Settings->Toggle Vi Compatible"), N_(" for Vim defaults "), }; #endif /* blanklines = screen height - # message lines */ blanklines = (int)Rows - ((sizeof(lines) / sizeof(char *)) - 1); if (!p_cp) blanklines += 4; /* add 4 for not showing "Vi compatible" message */ #ifdef FEAT_WINDOWS /* Don't overwrite a statusline. Depends on 'cmdheight'. */ if (p_ls > 1) blanklines -= Rows - topframe->fr_height; #endif if (blanklines < 0) blanklines = 0; /* Show the sponsor and register message one out of four times, the Uganda * message two out of four times. */ sponsor = (int)time(NULL); sponsor = ((sponsor & 2) == 0) - ((sponsor & 4) == 0); /* start displaying the message lines after half of the blank lines */ row = blanklines / 2; if ((row >= 2 && Columns >= 50) || colon) { for (i = 0; i < (int)(sizeof(lines) / sizeof(char *)); ++i) { p = lines[i]; #ifdef FEAT_GUI if (p_im && gui.in_use && gui_lines[i] != NULL) p = gui_lines[i]; #endif if (p == NULL) { if (!p_cp) break; continue; } if (sponsor != 0) { if (strstr(p, "children") != NULL) p = sponsor < 0 ? N_("Sponsor Vim development!") : N_("Become a registered Vim user!"); else if (strstr(p, "iccf") != NULL) p = sponsor < 0 ? N_("type :help sponsor<Enter> for information ") : N_("type :help register<Enter> for information "); else if (strstr(p, "Orphans") != NULL) p = N_("menu Help->Sponsor/Register for information "); } if (*p != NUL) do_intro_line(row, (char_u *)_(p), i == 2, 0); ++row; } } /* Make the wait-return message appear just below the text. */ if (colon) msg_row = row; } static void do_intro_line( int row, char_u *mesg, int add_version, int attr) { char_u vers[20]; int col; char_u *p; int l; int clen; #ifdef MODIFIED_BY # define MODBY_LEN 150 char_u modby[MODBY_LEN]; if (*mesg == ' ') { vim_strncpy(modby, (char_u *)_("Modified by "), MODBY_LEN - 1); l = (int)STRLEN(modby); vim_strncpy(modby + l, (char_u *)MODIFIED_BY, MODBY_LEN - l - 1); mesg = modby; } #endif /* Center the message horizontally. */ col = vim_strsize(mesg); if (add_version) { STRCPY(vers, mediumVersion); if (highest_patch()) { /* Check for 9.9x or 9.9xx, alpha/beta version */ if (isalpha((int)vers[3])) { int len = (isalpha((int)vers[4])) ? 5 : 4; sprintf((char *)vers + len, ".%d%s", highest_patch(), mediumVersion + len); } else sprintf((char *)vers + 3, ".%d", highest_patch()); } col += (int)STRLEN(vers); } col = (Columns - col) / 2; if (col < 0) col = 0; /* Split up in parts to highlight <> items differently. */ for (p = mesg; *p != NUL; p += l) { clen = 0; for (l = 0; p[l] != NUL && (l == 0 || (p[l] != '<' && p[l - 1] != '>')); ++l) { #ifdef FEAT_MBYTE if (has_mbyte) { clen += ptr2cells(p + l); l += (*mb_ptr2len)(p + l) - 1; } else #endif clen += byte2cells(p[l]); } screen_puts_len(p, l, row, col, *p == '<' ? hl_attr(HLF_8) : attr); col += clen; } /* Add the version number to the version line. */ if (add_version) screen_puts(vers, row, col, 0); } /* * ":intro": clear screen, display intro screen and wait for return. */ void ex_intro(exarg_T *eap UNUSED) { screenclear(); intro_message(TRUE); wait_return(TRUE); }
./CrossVul/dataset_final_sorted/CWE-20/c/bad_4900_2
crossvul-cpp_data_bad_1718_1
/* $OpenBSD: monitor_wrap.c,v 1.85 2015/05/01 03:23:51 djm Exp $ */ /* * Copyright 2002 Niels Provos <provos@citi.umich.edu> * Copyright 2002 Markus Friedl <markus@openbsd.org> * 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 ``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 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 "includes.h" #include <sys/types.h> #include <sys/uio.h> #include <errno.h> #include <pwd.h> #include <signal.h> #include <stdarg.h> #include <stdio.h> #include <string.h> #include <unistd.h> #ifdef WITH_OPENSSL #include <openssl/bn.h> #include <openssl/dh.h> #include <openssl/evp.h> #endif #include "openbsd-compat/sys-queue.h" #include "xmalloc.h" #include "ssh.h" #ifdef WITH_OPENSSL #include "dh.h" #endif #include "buffer.h" #include "key.h" #include "cipher.h" #include "kex.h" #include "hostfile.h" #include "auth.h" #include "auth-options.h" #include "packet.h" #include "mac.h" #include "log.h" #ifdef TARGET_OS_MAC /* XXX Broken krb5 headers on Mac */ #undef TARGET_OS_MAC #include "zlib.h" #define TARGET_OS_MAC 1 #else #include "zlib.h" #endif #include "monitor.h" #ifdef GSSAPI #include "ssh-gss.h" #endif #include "monitor_wrap.h" #include "atomicio.h" #include "monitor_fdpass.h" #include "misc.h" #include "uuencode.h" #include "channels.h" #include "session.h" #include "servconf.h" #include "roaming.h" #include "ssherr.h" /* Imports */ extern int compat20; extern z_stream incoming_stream; extern z_stream outgoing_stream; extern struct monitor *pmonitor; extern Buffer loginmsg; extern ServerOptions options; void mm_log_handler(LogLevel level, const char *msg, void *ctx) { Buffer log_msg; struct monitor *mon = (struct monitor *)ctx; if (mon->m_log_sendfd == -1) fatal("%s: no log channel", __func__); buffer_init(&log_msg); /* * Placeholder for packet length. Will be filled in with the actual * packet length once the packet has been constucted. This saves * fragile math. */ buffer_put_int(&log_msg, 0); buffer_put_int(&log_msg, level); buffer_put_cstring(&log_msg, msg); put_u32(buffer_ptr(&log_msg), buffer_len(&log_msg) - 4); if (atomicio(vwrite, mon->m_log_sendfd, buffer_ptr(&log_msg), buffer_len(&log_msg)) != buffer_len(&log_msg)) fatal("%s: write: %s", __func__, strerror(errno)); buffer_free(&log_msg); } int mm_is_monitor(void) { /* * m_pid is only set in the privileged part, and * points to the unprivileged child. */ return (pmonitor && pmonitor->m_pid > 0); } void mm_request_send(int sock, enum monitor_reqtype type, Buffer *m) { u_int mlen = buffer_len(m); u_char buf[5]; debug3("%s entering: type %d", __func__, type); put_u32(buf, mlen + 1); buf[4] = (u_char) type; /* 1st byte of payload is mesg-type */ if (atomicio(vwrite, sock, buf, sizeof(buf)) != sizeof(buf)) fatal("%s: write: %s", __func__, strerror(errno)); if (atomicio(vwrite, sock, buffer_ptr(m), mlen) != mlen) fatal("%s: write: %s", __func__, strerror(errno)); } void mm_request_receive(int sock, Buffer *m) { u_char buf[4]; u_int msg_len; debug3("%s entering", __func__); if (atomicio(read, sock, buf, sizeof(buf)) != sizeof(buf)) { if (errno == EPIPE) cleanup_exit(255); fatal("%s: read: %s", __func__, strerror(errno)); } msg_len = get_u32(buf); if (msg_len > 256 * 1024) fatal("%s: read: bad msg_len %d", __func__, msg_len); buffer_clear(m); buffer_append_space(m, msg_len); if (atomicio(read, sock, buffer_ptr(m), msg_len) != msg_len) fatal("%s: read: %s", __func__, strerror(errno)); } void mm_request_receive_expect(int sock, enum monitor_reqtype type, Buffer *m) { u_char rtype; debug3("%s entering: type %d", __func__, type); mm_request_receive(sock, m); rtype = buffer_get_char(m); if (rtype != type) fatal("%s: read: rtype %d != type %d", __func__, rtype, type); } #ifdef WITH_OPENSSL DH * mm_choose_dh(int min, int nbits, int max) { BIGNUM *p, *g; int success = 0; Buffer m; buffer_init(&m); buffer_put_int(&m, min); buffer_put_int(&m, nbits); buffer_put_int(&m, max); mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_MODULI, &m); debug3("%s: waiting for MONITOR_ANS_MODULI", __func__); mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_MODULI, &m); success = buffer_get_char(&m); if (success == 0) fatal("%s: MONITOR_ANS_MODULI failed", __func__); if ((p = BN_new()) == NULL) fatal("%s: BN_new failed", __func__); if ((g = BN_new()) == NULL) fatal("%s: BN_new failed", __func__); buffer_get_bignum2(&m, p); buffer_get_bignum2(&m, g); debug3("%s: remaining %d", __func__, buffer_len(&m)); buffer_free(&m); return (dh_new_group(g, p)); } #endif int mm_key_sign(Key *key, u_char **sigp, u_int *lenp, const u_char *data, u_int datalen) { struct kex *kex = *pmonitor->m_pkex; Buffer m; debug3("%s entering", __func__); buffer_init(&m); buffer_put_int(&m, kex->host_key_index(key, 0, active_state)); buffer_put_string(&m, data, datalen); mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_SIGN, &m); debug3("%s: waiting for MONITOR_ANS_SIGN", __func__); mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_SIGN, &m); *sigp = buffer_get_string(&m, lenp); buffer_free(&m); return (0); } struct passwd * mm_getpwnamallow(const char *username) { Buffer m; struct passwd *pw; u_int len, i; ServerOptions *newopts; debug3("%s entering", __func__); buffer_init(&m); buffer_put_cstring(&m, username); mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_PWNAM, &m); debug3("%s: waiting for MONITOR_ANS_PWNAM", __func__); mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_PWNAM, &m); if (buffer_get_char(&m) == 0) { pw = NULL; goto out; } pw = buffer_get_string(&m, &len); if (len != sizeof(struct passwd)) fatal("%s: struct passwd size mismatch", __func__); pw->pw_name = buffer_get_string(&m, NULL); pw->pw_passwd = buffer_get_string(&m, NULL); #ifdef HAVE_STRUCT_PASSWD_PW_GECOS pw->pw_gecos = buffer_get_string(&m, NULL); #endif #ifdef HAVE_STRUCT_PASSWD_PW_CLASS pw->pw_class = buffer_get_string(&m, NULL); #endif pw->pw_dir = buffer_get_string(&m, NULL); pw->pw_shell = buffer_get_string(&m, NULL); out: /* copy options block as a Match directive may have changed some */ newopts = buffer_get_string(&m, &len); if (len != sizeof(*newopts)) fatal("%s: option block size mismatch", __func__); #define M_CP_STROPT(x) do { \ if (newopts->x != NULL) \ newopts->x = buffer_get_string(&m, NULL); \ } while (0) #define M_CP_STRARRAYOPT(x, nx) do { \ for (i = 0; i < newopts->nx; i++) \ newopts->x[i] = buffer_get_string(&m, NULL); \ } while (0) /* See comment in servconf.h */ COPY_MATCH_STRING_OPTS(); #undef M_CP_STROPT #undef M_CP_STRARRAYOPT copy_set_server_options(&options, newopts, 1); free(newopts); buffer_free(&m); return (pw); } char * mm_auth2_read_banner(void) { Buffer m; char *banner; debug3("%s entering", __func__); buffer_init(&m); mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_AUTH2_READ_BANNER, &m); buffer_clear(&m); mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_AUTH2_READ_BANNER, &m); banner = buffer_get_string(&m, NULL); buffer_free(&m); /* treat empty banner as missing banner */ if (strlen(banner) == 0) { free(banner); banner = NULL; } return (banner); } /* Inform the privileged process about service and style */ void mm_inform_authserv(char *service, char *style) { Buffer m; debug3("%s entering", __func__); buffer_init(&m); buffer_put_cstring(&m, service); buffer_put_cstring(&m, style ? style : ""); mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_AUTHSERV, &m); buffer_free(&m); } /* Do the password authentication */ int mm_auth_password(Authctxt *authctxt, char *password) { Buffer m; int authenticated = 0; debug3("%s entering", __func__); buffer_init(&m); buffer_put_cstring(&m, password); mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_AUTHPASSWORD, &m); debug3("%s: waiting for MONITOR_ANS_AUTHPASSWORD", __func__); mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_AUTHPASSWORD, &m); authenticated = buffer_get_int(&m); buffer_free(&m); debug3("%s: user %sauthenticated", __func__, authenticated ? "" : "not "); return (authenticated); } int mm_user_key_allowed(struct passwd *pw, Key *key, int pubkey_auth_attempt) { return (mm_key_allowed(MM_USERKEY, NULL, NULL, key, pubkey_auth_attempt)); } int mm_hostbased_key_allowed(struct passwd *pw, char *user, char *host, Key *key) { return (mm_key_allowed(MM_HOSTKEY, user, host, key, 0)); } int mm_auth_rhosts_rsa_key_allowed(struct passwd *pw, char *user, char *host, Key *key) { int ret; key->type = KEY_RSA; /* XXX hack for key_to_blob */ ret = mm_key_allowed(MM_RSAHOSTKEY, user, host, key, 0); key->type = KEY_RSA1; return (ret); } int mm_key_allowed(enum mm_keytype type, char *user, char *host, Key *key, int pubkey_auth_attempt) { Buffer m; u_char *blob; u_int len; int allowed = 0, have_forced = 0; debug3("%s entering", __func__); /* Convert the key to a blob and the pass it over */ if (!key_to_blob(key, &blob, &len)) return (0); buffer_init(&m); buffer_put_int(&m, type); buffer_put_cstring(&m, user ? user : ""); buffer_put_cstring(&m, host ? host : ""); buffer_put_string(&m, blob, len); buffer_put_int(&m, pubkey_auth_attempt); free(blob); mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_KEYALLOWED, &m); debug3("%s: waiting for MONITOR_ANS_KEYALLOWED", __func__); mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_KEYALLOWED, &m); allowed = buffer_get_int(&m); /* fake forced command */ auth_clear_options(); have_forced = buffer_get_int(&m); forced_command = have_forced ? xstrdup("true") : NULL; buffer_free(&m); return (allowed); } /* * This key verify needs to send the key type along, because the * privileged parent makes the decision if the key is allowed * for authentication. */ int mm_key_verify(Key *key, u_char *sig, u_int siglen, u_char *data, u_int datalen) { Buffer m; u_char *blob; u_int len; int verified = 0; debug3("%s entering", __func__); /* Convert the key to a blob and the pass it over */ if (!key_to_blob(key, &blob, &len)) return (0); buffer_init(&m); buffer_put_string(&m, blob, len); buffer_put_string(&m, sig, siglen); buffer_put_string(&m, data, datalen); free(blob); mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_KEYVERIFY, &m); debug3("%s: waiting for MONITOR_ANS_KEYVERIFY", __func__); mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_KEYVERIFY, &m); verified = buffer_get_int(&m); buffer_free(&m); return (verified); } void mm_send_keystate(struct monitor *monitor) { struct ssh *ssh = active_state; /* XXX */ struct sshbuf *m; int r; if ((m = sshbuf_new()) == NULL) fatal("%s: sshbuf_new failed", __func__); if ((r = ssh_packet_get_state(ssh, m)) != 0) fatal("%s: get_state failed: %s", __func__, ssh_err(r)); mm_request_send(monitor->m_recvfd, MONITOR_REQ_KEYEXPORT, m); debug3("%s: Finished sending state", __func__); sshbuf_free(m); } int mm_pty_allocate(int *ptyfd, int *ttyfd, char *namebuf, size_t namebuflen) { Buffer m; char *p, *msg; int success = 0, tmp1 = -1, tmp2 = -1; /* Kludge: ensure there are fds free to receive the pty/tty */ if ((tmp1 = dup(pmonitor->m_recvfd)) == -1 || (tmp2 = dup(pmonitor->m_recvfd)) == -1) { error("%s: cannot allocate fds for pty", __func__); if (tmp1 > 0) close(tmp1); if (tmp2 > 0) close(tmp2); return 0; } close(tmp1); close(tmp2); buffer_init(&m); mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_PTY, &m); debug3("%s: waiting for MONITOR_ANS_PTY", __func__); mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_PTY, &m); success = buffer_get_int(&m); if (success == 0) { debug3("%s: pty alloc failed", __func__); buffer_free(&m); return (0); } p = buffer_get_string(&m, NULL); msg = buffer_get_string(&m, NULL); buffer_free(&m); strlcpy(namebuf, p, namebuflen); /* Possible truncation */ free(p); buffer_append(&loginmsg, msg, strlen(msg)); free(msg); if ((*ptyfd = mm_receive_fd(pmonitor->m_recvfd)) == -1 || (*ttyfd = mm_receive_fd(pmonitor->m_recvfd)) == -1) fatal("%s: receive fds failed", __func__); /* Success */ return (1); } void mm_session_pty_cleanup2(Session *s) { Buffer m; if (s->ttyfd == -1) return; buffer_init(&m); buffer_put_cstring(&m, s->tty); mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_PTYCLEANUP, &m); buffer_free(&m); /* closed dup'ed master */ if (s->ptymaster != -1 && close(s->ptymaster) < 0) error("close(s->ptymaster/%d): %s", s->ptymaster, strerror(errno)); /* unlink pty from session */ s->ttyfd = -1; } #ifdef USE_PAM void mm_start_pam(Authctxt *authctxt) { Buffer m; debug3("%s entering", __func__); if (!options.use_pam) fatal("UsePAM=no, but ended up in %s anyway", __func__); buffer_init(&m); mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_PAM_START, &m); buffer_free(&m); } u_int mm_do_pam_account(void) { Buffer m; u_int ret; char *msg; debug3("%s entering", __func__); if (!options.use_pam) fatal("UsePAM=no, but ended up in %s anyway", __func__); buffer_init(&m); mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_PAM_ACCOUNT, &m); mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_PAM_ACCOUNT, &m); ret = buffer_get_int(&m); msg = buffer_get_string(&m, NULL); buffer_append(&loginmsg, msg, strlen(msg)); free(msg); buffer_free(&m); debug3("%s returning %d", __func__, ret); return (ret); } void * mm_sshpam_init_ctx(Authctxt *authctxt) { Buffer m; int success; debug3("%s", __func__); buffer_init(&m); buffer_put_cstring(&m, authctxt->user); mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_PAM_INIT_CTX, &m); debug3("%s: waiting for MONITOR_ANS_PAM_INIT_CTX", __func__); mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_PAM_INIT_CTX, &m); success = buffer_get_int(&m); if (success == 0) { debug3("%s: pam_init_ctx failed", __func__); buffer_free(&m); return (NULL); } buffer_free(&m); return (authctxt); } int mm_sshpam_query(void *ctx, char **name, char **info, u_int *num, char ***prompts, u_int **echo_on) { Buffer m; u_int i; int ret; debug3("%s", __func__); buffer_init(&m); mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_PAM_QUERY, &m); debug3("%s: waiting for MONITOR_ANS_PAM_QUERY", __func__); mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_PAM_QUERY, &m); ret = buffer_get_int(&m); debug3("%s: pam_query returned %d", __func__, ret); *name = buffer_get_string(&m, NULL); *info = buffer_get_string(&m, NULL); *num = buffer_get_int(&m); if (*num > PAM_MAX_NUM_MSG) fatal("%s: recieved %u PAM messages, expected <= %u", __func__, *num, PAM_MAX_NUM_MSG); *prompts = xcalloc((*num + 1), sizeof(char *)); *echo_on = xcalloc((*num + 1), sizeof(u_int)); for (i = 0; i < *num; ++i) { (*prompts)[i] = buffer_get_string(&m, NULL); (*echo_on)[i] = buffer_get_int(&m); } buffer_free(&m); return (ret); } int mm_sshpam_respond(void *ctx, u_int num, char **resp) { Buffer m; u_int i; int ret; debug3("%s", __func__); buffer_init(&m); buffer_put_int(&m, num); for (i = 0; i < num; ++i) buffer_put_cstring(&m, resp[i]); mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_PAM_RESPOND, &m); debug3("%s: waiting for MONITOR_ANS_PAM_RESPOND", __func__); mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_PAM_RESPOND, &m); ret = buffer_get_int(&m); debug3("%s: pam_respond returned %d", __func__, ret); buffer_free(&m); return (ret); } void mm_sshpam_free_ctx(void *ctxtp) { Buffer m; debug3("%s", __func__); buffer_init(&m); mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_PAM_FREE_CTX, &m); debug3("%s: waiting for MONITOR_ANS_PAM_FREE_CTX", __func__); mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_PAM_FREE_CTX, &m); buffer_free(&m); } #endif /* USE_PAM */ /* Request process termination */ void mm_terminate(void) { Buffer m; buffer_init(&m); mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_TERM, &m); buffer_free(&m); } #ifdef WITH_SSH1 int mm_ssh1_session_key(BIGNUM *num) { int rsafail; Buffer m; buffer_init(&m); buffer_put_bignum2(&m, num); mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_SESSKEY, &m); mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_SESSKEY, &m); rsafail = buffer_get_int(&m); buffer_get_bignum2(&m, num); buffer_free(&m); return (rsafail); } #endif static void mm_chall_setup(char **name, char **infotxt, u_int *numprompts, char ***prompts, u_int **echo_on) { *name = xstrdup(""); *infotxt = xstrdup(""); *numprompts = 1; *prompts = xcalloc(*numprompts, sizeof(char *)); *echo_on = xcalloc(*numprompts, sizeof(u_int)); (*echo_on)[0] = 0; } int mm_bsdauth_query(void *ctx, char **name, char **infotxt, u_int *numprompts, char ***prompts, u_int **echo_on) { Buffer m; u_int success; char *challenge; debug3("%s: entering", __func__); buffer_init(&m); mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_BSDAUTHQUERY, &m); mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_BSDAUTHQUERY, &m); success = buffer_get_int(&m); if (success == 0) { debug3("%s: no challenge", __func__); buffer_free(&m); return (-1); } /* Get the challenge, and format the response */ challenge = buffer_get_string(&m, NULL); buffer_free(&m); mm_chall_setup(name, infotxt, numprompts, prompts, echo_on); (*prompts)[0] = challenge; debug3("%s: received challenge: %s", __func__, challenge); return (0); } int mm_bsdauth_respond(void *ctx, u_int numresponses, char **responses) { Buffer m; int authok; debug3("%s: entering", __func__); if (numresponses != 1) return (-1); buffer_init(&m); buffer_put_cstring(&m, responses[0]); mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_BSDAUTHRESPOND, &m); mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_BSDAUTHRESPOND, &m); authok = buffer_get_int(&m); buffer_free(&m); return ((authok == 0) ? -1 : 0); } #ifdef SKEY int mm_skey_query(void *ctx, char **name, char **infotxt, u_int *numprompts, char ***prompts, u_int **echo_on) { Buffer m; u_int success; char *challenge; debug3("%s: entering", __func__); buffer_init(&m); mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_SKEYQUERY, &m); mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_SKEYQUERY, &m); success = buffer_get_int(&m); if (success == 0) { debug3("%s: no challenge", __func__); buffer_free(&m); return (-1); } /* Get the challenge, and format the response */ challenge = buffer_get_string(&m, NULL); buffer_free(&m); debug3("%s: received challenge: %s", __func__, challenge); mm_chall_setup(name, infotxt, numprompts, prompts, echo_on); xasprintf(*prompts, "%s%s", challenge, SKEY_PROMPT); free(challenge); return (0); } int mm_skey_respond(void *ctx, u_int numresponses, char **responses) { Buffer m; int authok; debug3("%s: entering", __func__); if (numresponses != 1) return (-1); buffer_init(&m); buffer_put_cstring(&m, responses[0]); mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_SKEYRESPOND, &m); mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_SKEYRESPOND, &m); authok = buffer_get_int(&m); buffer_free(&m); return ((authok == 0) ? -1 : 0); } #endif /* SKEY */ void mm_ssh1_session_id(u_char session_id[16]) { Buffer m; int i; debug3("%s entering", __func__); buffer_init(&m); for (i = 0; i < 16; i++) buffer_put_char(&m, session_id[i]); mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_SESSID, &m); buffer_free(&m); } #ifdef WITH_SSH1 int mm_auth_rsa_key_allowed(struct passwd *pw, BIGNUM *client_n, Key **rkey) { Buffer m; Key *key; u_char *blob; u_int blen; int allowed = 0, have_forced = 0; debug3("%s entering", __func__); buffer_init(&m); buffer_put_bignum2(&m, client_n); mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_RSAKEYALLOWED, &m); mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_RSAKEYALLOWED, &m); allowed = buffer_get_int(&m); /* fake forced command */ auth_clear_options(); have_forced = buffer_get_int(&m); forced_command = have_forced ? xstrdup("true") : NULL; if (allowed && rkey != NULL) { blob = buffer_get_string(&m, &blen); if ((key = key_from_blob(blob, blen)) == NULL) fatal("%s: key_from_blob failed", __func__); *rkey = key; free(blob); } buffer_free(&m); return (allowed); } BIGNUM * mm_auth_rsa_generate_challenge(Key *key) { Buffer m; BIGNUM *challenge; u_char *blob; u_int blen; debug3("%s entering", __func__); if ((challenge = BN_new()) == NULL) fatal("%s: BN_new failed", __func__); key->type = KEY_RSA; /* XXX cheat for key_to_blob */ if (key_to_blob(key, &blob, &blen) == 0) fatal("%s: key_to_blob failed", __func__); key->type = KEY_RSA1; buffer_init(&m); buffer_put_string(&m, blob, blen); free(blob); mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_RSACHALLENGE, &m); mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_RSACHALLENGE, &m); buffer_get_bignum2(&m, challenge); buffer_free(&m); return (challenge); } int mm_auth_rsa_verify_response(Key *key, BIGNUM *p, u_char response[16]) { Buffer m; u_char *blob; u_int blen; int success = 0; debug3("%s entering", __func__); key->type = KEY_RSA; /* XXX cheat for key_to_blob */ if (key_to_blob(key, &blob, &blen) == 0) fatal("%s: key_to_blob failed", __func__); key->type = KEY_RSA1; buffer_init(&m); buffer_put_string(&m, blob, blen); buffer_put_string(&m, response, 16); free(blob); mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_RSARESPONSE, &m); mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_RSARESPONSE, &m); success = buffer_get_int(&m); buffer_free(&m); return (success); } #endif #ifdef SSH_AUDIT_EVENTS void mm_audit_event(ssh_audit_event_t event) { Buffer m; debug3("%s entering", __func__); buffer_init(&m); buffer_put_int(&m, event); mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_AUDIT_EVENT, &m); buffer_free(&m); } void mm_audit_run_command(const char *command) { Buffer m; debug3("%s entering command %s", __func__, command); buffer_init(&m); buffer_put_cstring(&m, command); mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_AUDIT_COMMAND, &m); buffer_free(&m); } #endif /* SSH_AUDIT_EVENTS */ #ifdef GSSAPI OM_uint32 mm_ssh_gssapi_server_ctx(Gssctxt **ctx, gss_OID goid) { Buffer m; OM_uint32 major; /* Client doesn't get to see the context */ *ctx = NULL; buffer_init(&m); buffer_put_string(&m, goid->elements, goid->length); mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_GSSSETUP, &m); mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_GSSSETUP, &m); major = buffer_get_int(&m); buffer_free(&m); return (major); } OM_uint32 mm_ssh_gssapi_accept_ctx(Gssctxt *ctx, gss_buffer_desc *in, gss_buffer_desc *out, OM_uint32 *flags) { Buffer m; OM_uint32 major; u_int len; buffer_init(&m); buffer_put_string(&m, in->value, in->length); mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_GSSSTEP, &m); mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_GSSSTEP, &m); major = buffer_get_int(&m); out->value = buffer_get_string(&m, &len); out->length = len; if (flags) *flags = buffer_get_int(&m); buffer_free(&m); return (major); } OM_uint32 mm_ssh_gssapi_checkmic(Gssctxt *ctx, gss_buffer_t gssbuf, gss_buffer_t gssmic) { Buffer m; OM_uint32 major; buffer_init(&m); buffer_put_string(&m, gssbuf->value, gssbuf->length); buffer_put_string(&m, gssmic->value, gssmic->length); mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_GSSCHECKMIC, &m); mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_GSSCHECKMIC, &m); major = buffer_get_int(&m); buffer_free(&m); return(major); } int mm_ssh_gssapi_userok(char *user) { Buffer m; int authenticated = 0; buffer_init(&m); mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_GSSUSEROK, &m); mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_GSSUSEROK, &m); authenticated = buffer_get_int(&m); buffer_free(&m); debug3("%s: user %sauthenticated",__func__, authenticated ? "" : "not "); return (authenticated); } #endif /* GSSAPI */
./CrossVul/dataset_final_sorted/CWE-20/c/bad_1718_1
crossvul-cpp_data_bad_1762_1
/* Request a key from userspace * * Copyright (C) 2004-2007 Red Hat, Inc. All Rights Reserved. * Written by David Howells (dhowells@redhat.com) * * 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. * * See Documentation/security/keys-request-key.txt */ #include <linux/module.h> #include <linux/sched.h> #include <linux/kmod.h> #include <linux/err.h> #include <linux/keyctl.h> #include <linux/slab.h> #include "internal.h" #define key_negative_timeout 60 /* default timeout on a negative key's existence */ /** * complete_request_key - Complete the construction of a key. * @cons: The key construction record. * @error: The success or failute of the construction. * * Complete the attempt to construct a key. The key will be negated * if an error is indicated. The authorisation key will be revoked * unconditionally. */ void complete_request_key(struct key_construction *cons, int error) { kenter("{%d,%d},%d", cons->key->serial, cons->authkey->serial, error); if (error < 0) key_negate_and_link(cons->key, key_negative_timeout, NULL, cons->authkey); else key_revoke(cons->authkey); key_put(cons->key); key_put(cons->authkey); kfree(cons); } EXPORT_SYMBOL(complete_request_key); /* * Initialise a usermode helper that is going to have a specific session * keyring. * * This is called in context of freshly forked kthread before kernel_execve(), * so we can simply install the desired session_keyring at this point. */ static int umh_keys_init(struct subprocess_info *info, struct cred *cred) { struct key *keyring = info->data; return install_session_keyring_to_cred(cred, keyring); } /* * Clean up a usermode helper with session keyring. */ static void umh_keys_cleanup(struct subprocess_info *info) { struct key *keyring = info->data; key_put(keyring); } /* * Call a usermode helper with a specific session keyring. */ static int call_usermodehelper_keys(char *path, char **argv, char **envp, struct key *session_keyring, int wait) { struct subprocess_info *info; info = call_usermodehelper_setup(path, argv, envp, GFP_KERNEL, umh_keys_init, umh_keys_cleanup, session_keyring); if (!info) return -ENOMEM; key_get(session_keyring); return call_usermodehelper_exec(info, wait); } /* * Request userspace finish the construction of a key * - execute "/sbin/request-key <op> <key> <uid> <gid> <keyring> <keyring> <keyring>" */ static int call_sbin_request_key(struct key_construction *cons, const char *op, void *aux) { const struct cred *cred = current_cred(); key_serial_t prkey, sskey; struct key *key = cons->key, *authkey = cons->authkey, *keyring, *session; char *argv[9], *envp[3], uid_str[12], gid_str[12]; char key_str[12], keyring_str[3][12]; char desc[20]; int ret, i; kenter("{%d},{%d},%s", key->serial, authkey->serial, op); ret = install_user_keyrings(); if (ret < 0) goto error_alloc; /* allocate a new session keyring */ sprintf(desc, "_req.%u", key->serial); cred = get_current_cred(); keyring = keyring_alloc(desc, cred->fsuid, cred->fsgid, cred, KEY_POS_ALL | KEY_USR_VIEW | KEY_USR_READ, KEY_ALLOC_QUOTA_OVERRUN, NULL); put_cred(cred); if (IS_ERR(keyring)) { ret = PTR_ERR(keyring); goto error_alloc; } /* attach the auth key to the session keyring */ ret = key_link(keyring, authkey); if (ret < 0) goto error_link; /* record the UID and GID */ sprintf(uid_str, "%d", from_kuid(&init_user_ns, cred->fsuid)); sprintf(gid_str, "%d", from_kgid(&init_user_ns, cred->fsgid)); /* we say which key is under construction */ sprintf(key_str, "%d", key->serial); /* we specify the process's default keyrings */ sprintf(keyring_str[0], "%d", cred->thread_keyring ? cred->thread_keyring->serial : 0); prkey = 0; if (cred->process_keyring) prkey = cred->process_keyring->serial; sprintf(keyring_str[1], "%d", prkey); rcu_read_lock(); session = rcu_dereference(cred->session_keyring); if (!session) session = cred->user->session_keyring; sskey = session->serial; rcu_read_unlock(); sprintf(keyring_str[2], "%d", sskey); /* set up a minimal environment */ i = 0; envp[i++] = "HOME=/"; envp[i++] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin"; envp[i] = NULL; /* set up the argument list */ i = 0; argv[i++] = "/sbin/request-key"; argv[i++] = (char *) op; argv[i++] = key_str; argv[i++] = uid_str; argv[i++] = gid_str; argv[i++] = keyring_str[0]; argv[i++] = keyring_str[1]; argv[i++] = keyring_str[2]; argv[i] = NULL; /* do it */ ret = call_usermodehelper_keys(argv[0], argv, envp, keyring, UMH_WAIT_PROC); kdebug("usermode -> 0x%x", ret); if (ret >= 0) { /* ret is the exit/wait code */ if (test_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags) || key_validate(key) < 0) ret = -ENOKEY; else /* ignore any errors from userspace if the key was * instantiated */ ret = 0; } error_link: key_put(keyring); error_alloc: complete_request_key(cons, ret); kleave(" = %d", ret); return ret; } /* * Call out to userspace for key construction. * * Program failure is ignored in favour of key status. */ static int construct_key(struct key *key, const void *callout_info, size_t callout_len, void *aux, struct key *dest_keyring) { struct key_construction *cons; request_key_actor_t actor; struct key *authkey; int ret; kenter("%d,%p,%zu,%p", key->serial, callout_info, callout_len, aux); cons = kmalloc(sizeof(*cons), GFP_KERNEL); if (!cons) return -ENOMEM; /* allocate an authorisation key */ authkey = request_key_auth_new(key, callout_info, callout_len, dest_keyring); if (IS_ERR(authkey)) { kfree(cons); ret = PTR_ERR(authkey); authkey = NULL; } else { cons->authkey = key_get(authkey); cons->key = key_get(key); /* make the call */ actor = call_sbin_request_key; if (key->type->request_key) actor = key->type->request_key; ret = actor(cons, "create", aux); /* check that the actor called complete_request_key() prior to * returning an error */ WARN_ON(ret < 0 && !test_bit(KEY_FLAG_REVOKED, &authkey->flags)); key_put(authkey); } kleave(" = %d", ret); return ret; } /* * Get the appropriate destination keyring for the request. * * The keyring selected is returned with an extra reference upon it which the * caller must release. */ static void construct_get_dest_keyring(struct key **_dest_keyring) { struct request_key_auth *rka; const struct cred *cred = current_cred(); struct key *dest_keyring = *_dest_keyring, *authkey; kenter("%p", dest_keyring); /* find the appropriate keyring */ if (dest_keyring) { /* the caller supplied one */ key_get(dest_keyring); } else { /* use a default keyring; falling through the cases until we * find one that we actually have */ switch (cred->jit_keyring) { case KEY_REQKEY_DEFL_DEFAULT: case KEY_REQKEY_DEFL_REQUESTOR_KEYRING: if (cred->request_key_auth) { authkey = cred->request_key_auth; down_read(&authkey->sem); rka = authkey->payload.data; if (!test_bit(KEY_FLAG_REVOKED, &authkey->flags)) dest_keyring = key_get(rka->dest_keyring); up_read(&authkey->sem); if (dest_keyring) break; } case KEY_REQKEY_DEFL_THREAD_KEYRING: dest_keyring = key_get(cred->thread_keyring); if (dest_keyring) break; case KEY_REQKEY_DEFL_PROCESS_KEYRING: dest_keyring = key_get(cred->process_keyring); if (dest_keyring) break; case KEY_REQKEY_DEFL_SESSION_KEYRING: rcu_read_lock(); dest_keyring = key_get( rcu_dereference(cred->session_keyring)); rcu_read_unlock(); if (dest_keyring) break; case KEY_REQKEY_DEFL_USER_SESSION_KEYRING: dest_keyring = key_get(cred->user->session_keyring); break; case KEY_REQKEY_DEFL_USER_KEYRING: dest_keyring = key_get(cred->user->uid_keyring); break; case KEY_REQKEY_DEFL_GROUP_KEYRING: default: BUG(); } } *_dest_keyring = dest_keyring; kleave(" [dk %d]", key_serial(dest_keyring)); return; } /* * Allocate a new key in under-construction state and attempt to link it in to * the requested keyring. * * May return a key that's already under construction instead if there was a * race between two thread calling request_key(). */ static int construct_alloc_key(struct keyring_search_context *ctx, struct key *dest_keyring, unsigned long flags, struct key_user *user, struct key **_key) { struct assoc_array_edit *edit; struct key *key; key_perm_t perm; key_ref_t key_ref; int ret; kenter("%s,%s,,,", ctx->index_key.type->name, ctx->index_key.description); *_key = NULL; mutex_lock(&user->cons_lock); perm = KEY_POS_VIEW | KEY_POS_SEARCH | KEY_POS_LINK | KEY_POS_SETATTR; perm |= KEY_USR_VIEW; if (ctx->index_key.type->read) perm |= KEY_POS_READ; if (ctx->index_key.type == &key_type_keyring || ctx->index_key.type->update) perm |= KEY_POS_WRITE; key = key_alloc(ctx->index_key.type, ctx->index_key.description, ctx->cred->fsuid, ctx->cred->fsgid, ctx->cred, perm, flags); if (IS_ERR(key)) goto alloc_failed; set_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags); if (dest_keyring) { ret = __key_link_begin(dest_keyring, &ctx->index_key, &edit); if (ret < 0) goto link_prealloc_failed; } /* attach the key to the destination keyring under lock, but we do need * to do another check just in case someone beat us to it whilst we * waited for locks */ mutex_lock(&key_construction_mutex); key_ref = search_process_keyrings(ctx); if (!IS_ERR(key_ref)) goto key_already_present; if (dest_keyring) __key_link(key, &edit); mutex_unlock(&key_construction_mutex); if (dest_keyring) __key_link_end(dest_keyring, &ctx->index_key, edit); mutex_unlock(&user->cons_lock); *_key = key; kleave(" = 0 [%d]", key_serial(key)); return 0; /* the key is now present - we tell the caller that we found it by * returning -EINPROGRESS */ key_already_present: key_put(key); mutex_unlock(&key_construction_mutex); key = key_ref_to_ptr(key_ref); if (dest_keyring) { ret = __key_link_check_live_key(dest_keyring, key); if (ret == 0) __key_link(key, &edit); __key_link_end(dest_keyring, &ctx->index_key, edit); if (ret < 0) goto link_check_failed; } mutex_unlock(&user->cons_lock); *_key = key; kleave(" = -EINPROGRESS [%d]", key_serial(key)); return -EINPROGRESS; link_check_failed: mutex_unlock(&user->cons_lock); key_put(key); kleave(" = %d [linkcheck]", ret); return ret; link_prealloc_failed: mutex_unlock(&user->cons_lock); key_put(key); kleave(" = %d [prelink]", ret); return ret; alloc_failed: mutex_unlock(&user->cons_lock); kleave(" = %ld", PTR_ERR(key)); return PTR_ERR(key); } /* * Commence key construction. */ static struct key *construct_key_and_link(struct keyring_search_context *ctx, const char *callout_info, size_t callout_len, void *aux, struct key *dest_keyring, unsigned long flags) { struct key_user *user; struct key *key; int ret; kenter(""); user = key_user_lookup(current_fsuid()); if (!user) return ERR_PTR(-ENOMEM); construct_get_dest_keyring(&dest_keyring); ret = construct_alloc_key(ctx, dest_keyring, flags, user, &key); key_user_put(user); if (ret == 0) { ret = construct_key(key, callout_info, callout_len, aux, dest_keyring); if (ret < 0) { kdebug("cons failed"); goto construction_failed; } } else if (ret == -EINPROGRESS) { ret = 0; } else { goto couldnt_alloc_key; } key_put(dest_keyring); kleave(" = key %d", key_serial(key)); return key; construction_failed: key_negate_and_link(key, key_negative_timeout, NULL, NULL); key_put(key); couldnt_alloc_key: key_put(dest_keyring); kleave(" = %d", ret); return ERR_PTR(ret); } /** * request_key_and_link - Request a key and cache it in a keyring. * @type: The type of key we want. * @description: The searchable description of the key. * @callout_info: The data to pass to the instantiation upcall (or NULL). * @callout_len: The length of callout_info. * @aux: Auxiliary data for the upcall. * @dest_keyring: Where to cache the key. * @flags: Flags to key_alloc(). * * A key matching the specified criteria is searched for in the process's * keyrings and returned with its usage count incremented if found. Otherwise, * if callout_info is not NULL, a key will be allocated and some service * (probably in userspace) will be asked to instantiate it. * * If successfully found or created, the key will be linked to the destination * keyring if one is provided. * * Returns a pointer to the key if successful; -EACCES, -ENOKEY, -EKEYREVOKED * or -EKEYEXPIRED if an inaccessible, negative, revoked or expired key was * found; -ENOKEY if no key was found and no @callout_info was given; -EDQUOT * if insufficient key quota was available to create a new key; or -ENOMEM if * insufficient memory was available. * * If the returned key was created, then it may still be under construction, * and wait_for_key_construction() should be used to wait for that to complete. */ struct key *request_key_and_link(struct key_type *type, const char *description, const void *callout_info, size_t callout_len, void *aux, struct key *dest_keyring, unsigned long flags) { struct keyring_search_context ctx = { .index_key.type = type, .index_key.description = description, .cred = current_cred(), .match_data.cmp = key_default_cmp, .match_data.raw_data = description, .match_data.lookup_type = KEYRING_SEARCH_LOOKUP_DIRECT, .flags = (KEYRING_SEARCH_DO_STATE_CHECK | KEYRING_SEARCH_SKIP_EXPIRED), }; struct key *key; key_ref_t key_ref; int ret; kenter("%s,%s,%p,%zu,%p,%p,%lx", ctx.index_key.type->name, ctx.index_key.description, callout_info, callout_len, aux, dest_keyring, flags); if (type->match_preparse) { ret = type->match_preparse(&ctx.match_data); if (ret < 0) { key = ERR_PTR(ret); goto error; } } /* search all the process keyrings for a key */ key_ref = search_process_keyrings(&ctx); if (!IS_ERR(key_ref)) { key = key_ref_to_ptr(key_ref); if (dest_keyring) { construct_get_dest_keyring(&dest_keyring); ret = key_link(dest_keyring, key); key_put(dest_keyring); if (ret < 0) { key_put(key); key = ERR_PTR(ret); goto error_free; } } } else if (PTR_ERR(key_ref) != -EAGAIN) { key = ERR_CAST(key_ref); } else { /* the search failed, but the keyrings were searchable, so we * should consult userspace if we can */ key = ERR_PTR(-ENOKEY); if (!callout_info) goto error_free; key = construct_key_and_link(&ctx, callout_info, callout_len, aux, dest_keyring, flags); } error_free: if (type->match_free) type->match_free(&ctx.match_data); error: kleave(" = %p", key); return key; } /** * wait_for_key_construction - Wait for construction of a key to complete * @key: The key being waited for. * @intr: Whether to wait interruptibly. * * Wait for a key to finish being constructed. * * Returns 0 if successful; -ERESTARTSYS if the wait was interrupted; -ENOKEY * if the key was negated; or -EKEYREVOKED or -EKEYEXPIRED if the key was * revoked or expired. */ int wait_for_key_construction(struct key *key, bool intr) { int ret; ret = wait_on_bit(&key->flags, KEY_FLAG_USER_CONSTRUCT, intr ? TASK_INTERRUPTIBLE : TASK_UNINTERRUPTIBLE); if (ret) return -ERESTARTSYS; if (test_bit(KEY_FLAG_NEGATIVE, &key->flags)) { smp_rmb(); return key->type_data.reject_error; } return key_validate(key); } EXPORT_SYMBOL(wait_for_key_construction); /** * request_key - Request a key and wait for construction * @type: Type of key. * @description: The searchable description of the key. * @callout_info: The data to pass to the instantiation upcall (or NULL). * * As for request_key_and_link() except that it does not add the returned key * to a keyring if found, new keys are always allocated in the user's quota, * the callout_info must be a NUL-terminated string and no auxiliary data can * be passed. * * Furthermore, it then works as wait_for_key_construction() to wait for the * completion of keys undergoing construction with a non-interruptible wait. */ struct key *request_key(struct key_type *type, const char *description, const char *callout_info) { struct key *key; size_t callout_len = 0; int ret; if (callout_info) callout_len = strlen(callout_info); key = request_key_and_link(type, description, callout_info, callout_len, NULL, NULL, KEY_ALLOC_IN_QUOTA); if (!IS_ERR(key)) { ret = wait_for_key_construction(key, false); if (ret < 0) { key_put(key); return ERR_PTR(ret); } } return key; } EXPORT_SYMBOL(request_key); /** * request_key_with_auxdata - Request a key with auxiliary data for the upcaller * @type: The type of key we want. * @description: The searchable description of the key. * @callout_info: The data to pass to the instantiation upcall (or NULL). * @callout_len: The length of callout_info. * @aux: Auxiliary data for the upcall. * * As for request_key_and_link() except that it does not add the returned key * to a keyring if found and new keys are always allocated in the user's quota. * * Furthermore, it then works as wait_for_key_construction() to wait for the * completion of keys undergoing construction with a non-interruptible wait. */ struct key *request_key_with_auxdata(struct key_type *type, const char *description, const void *callout_info, size_t callout_len, void *aux) { struct key *key; int ret; key = request_key_and_link(type, description, callout_info, callout_len, aux, NULL, KEY_ALLOC_IN_QUOTA); if (!IS_ERR(key)) { ret = wait_for_key_construction(key, false); if (ret < 0) { key_put(key); return ERR_PTR(ret); } } return key; } EXPORT_SYMBOL(request_key_with_auxdata); /* * request_key_async - Request a key (allow async construction) * @type: Type of key. * @description: The searchable description of the key. * @callout_info: The data to pass to the instantiation upcall (or NULL). * @callout_len: The length of callout_info. * * As for request_key_and_link() except that it does not add the returned key * to a keyring if found, new keys are always allocated in the user's quota and * no auxiliary data can be passed. * * The caller should call wait_for_key_construction() to wait for the * completion of the returned key if it is still undergoing construction. */ struct key *request_key_async(struct key_type *type, const char *description, const void *callout_info, size_t callout_len) { return request_key_and_link(type, description, callout_info, callout_len, NULL, NULL, KEY_ALLOC_IN_QUOTA); } EXPORT_SYMBOL(request_key_async); /* * request a key with auxiliary data for the upcaller (allow async construction) * @type: Type of key. * @description: The searchable description of the key. * @callout_info: The data to pass to the instantiation upcall (or NULL). * @callout_len: The length of callout_info. * @aux: Auxiliary data for the upcall. * * As for request_key_and_link() except that it does not add the returned key * to a keyring if found and new keys are always allocated in the user's quota. * * The caller should call wait_for_key_construction() to wait for the * completion of the returned key if it is still undergoing construction. */ struct key *request_key_async_with_auxdata(struct key_type *type, const char *description, const void *callout_info, size_t callout_len, void *aux) { return request_key_and_link(type, description, callout_info, callout_len, aux, NULL, KEY_ALLOC_IN_QUOTA); } EXPORT_SYMBOL(request_key_async_with_auxdata);
./CrossVul/dataset_final_sorted/CWE-20/c/bad_1762_1
crossvul-cpp_data_good_3070_5
/* * Copyright 1995-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 <stdio.h> #include <stdlib.h> #include <openssl/objects.h> #include <openssl/evp.h> #include <openssl/hmac.h> #include <openssl/ocsp.h> #include <openssl/conf.h> #include <openssl/x509v3.h> #include <openssl/dh.h> #include <openssl/bn.h> #include "ssl_locl.h" #include <openssl/ct.h> #define CHECKLEN(curr, val, limit) \ (((curr) >= (limit)) || (size_t)((limit) - (curr)) < (size_t)(val)) static int tls_decrypt_ticket(SSL *s, const unsigned char *tick, int ticklen, const unsigned char *sess_id, int sesslen, SSL_SESSION **psess); static int ssl_check_clienthello_tlsext_early(SSL *s); static int ssl_check_serverhello_tlsext(SSL *s); SSL3_ENC_METHOD const TLSv1_enc_data = { tls1_enc, tls1_mac, tls1_setup_key_block, tls1_generate_master_secret, tls1_change_cipher_state, tls1_final_finish_mac, TLS1_FINISH_MAC_LENGTH, TLS_MD_CLIENT_FINISH_CONST, TLS_MD_CLIENT_FINISH_CONST_SIZE, TLS_MD_SERVER_FINISH_CONST, TLS_MD_SERVER_FINISH_CONST_SIZE, tls1_alert_code, tls1_export_keying_material, 0, SSL3_HM_HEADER_LENGTH, ssl3_set_handshake_header, ssl3_handshake_write }; SSL3_ENC_METHOD const TLSv1_1_enc_data = { tls1_enc, tls1_mac, tls1_setup_key_block, tls1_generate_master_secret, tls1_change_cipher_state, tls1_final_finish_mac, TLS1_FINISH_MAC_LENGTH, TLS_MD_CLIENT_FINISH_CONST, TLS_MD_CLIENT_FINISH_CONST_SIZE, TLS_MD_SERVER_FINISH_CONST, TLS_MD_SERVER_FINISH_CONST_SIZE, tls1_alert_code, tls1_export_keying_material, SSL_ENC_FLAG_EXPLICIT_IV, SSL3_HM_HEADER_LENGTH, ssl3_set_handshake_header, ssl3_handshake_write }; SSL3_ENC_METHOD const TLSv1_2_enc_data = { tls1_enc, tls1_mac, tls1_setup_key_block, tls1_generate_master_secret, tls1_change_cipher_state, tls1_final_finish_mac, TLS1_FINISH_MAC_LENGTH, TLS_MD_CLIENT_FINISH_CONST, TLS_MD_CLIENT_FINISH_CONST_SIZE, TLS_MD_SERVER_FINISH_CONST, TLS_MD_SERVER_FINISH_CONST_SIZE, tls1_alert_code, tls1_export_keying_material, SSL_ENC_FLAG_EXPLICIT_IV | SSL_ENC_FLAG_SIGALGS | SSL_ENC_FLAG_SHA256_PRF | SSL_ENC_FLAG_TLS1_2_CIPHERS, SSL3_HM_HEADER_LENGTH, ssl3_set_handshake_header, ssl3_handshake_write }; long tls1_default_timeout(void) { /* * 2 hours, the 24 hours mentioned in the TLSv1 spec is way too long for * http, the cache would over fill */ return (60 * 60 * 2); } int tls1_new(SSL *s) { if (!ssl3_new(s)) return (0); s->method->ssl_clear(s); return (1); } void tls1_free(SSL *s) { OPENSSL_free(s->tlsext_session_ticket); ssl3_free(s); } void tls1_clear(SSL *s) { ssl3_clear(s); if (s->method->version == TLS_ANY_VERSION) s->version = TLS_MAX_VERSION; else s->version = s->method->version; } #ifndef OPENSSL_NO_EC typedef struct { int nid; /* Curve NID */ int secbits; /* Bits of security (from SP800-57) */ unsigned int flags; /* Flags: currently just field type */ } tls_curve_info; /* * Table of curve information. * Do not delete entries or reorder this array! It is used as a lookup * table: the index of each entry is one less than the TLS curve id. */ static const tls_curve_info nid_list[] = { {NID_sect163k1, 80, TLS_CURVE_CHAR2}, /* sect163k1 (1) */ {NID_sect163r1, 80, TLS_CURVE_CHAR2}, /* sect163r1 (2) */ {NID_sect163r2, 80, TLS_CURVE_CHAR2}, /* sect163r2 (3) */ {NID_sect193r1, 80, TLS_CURVE_CHAR2}, /* sect193r1 (4) */ {NID_sect193r2, 80, TLS_CURVE_CHAR2}, /* sect193r2 (5) */ {NID_sect233k1, 112, TLS_CURVE_CHAR2}, /* sect233k1 (6) */ {NID_sect233r1, 112, TLS_CURVE_CHAR2}, /* sect233r1 (7) */ {NID_sect239k1, 112, TLS_CURVE_CHAR2}, /* sect239k1 (8) */ {NID_sect283k1, 128, TLS_CURVE_CHAR2}, /* sect283k1 (9) */ {NID_sect283r1, 128, TLS_CURVE_CHAR2}, /* sect283r1 (10) */ {NID_sect409k1, 192, TLS_CURVE_CHAR2}, /* sect409k1 (11) */ {NID_sect409r1, 192, TLS_CURVE_CHAR2}, /* sect409r1 (12) */ {NID_sect571k1, 256, TLS_CURVE_CHAR2}, /* sect571k1 (13) */ {NID_sect571r1, 256, TLS_CURVE_CHAR2}, /* sect571r1 (14) */ {NID_secp160k1, 80, TLS_CURVE_PRIME}, /* secp160k1 (15) */ {NID_secp160r1, 80, TLS_CURVE_PRIME}, /* secp160r1 (16) */ {NID_secp160r2, 80, TLS_CURVE_PRIME}, /* secp160r2 (17) */ {NID_secp192k1, 80, TLS_CURVE_PRIME}, /* secp192k1 (18) */ {NID_X9_62_prime192v1, 80, TLS_CURVE_PRIME}, /* secp192r1 (19) */ {NID_secp224k1, 112, TLS_CURVE_PRIME}, /* secp224k1 (20) */ {NID_secp224r1, 112, TLS_CURVE_PRIME}, /* secp224r1 (21) */ {NID_secp256k1, 128, TLS_CURVE_PRIME}, /* secp256k1 (22) */ {NID_X9_62_prime256v1, 128, TLS_CURVE_PRIME}, /* secp256r1 (23) */ {NID_secp384r1, 192, TLS_CURVE_PRIME}, /* secp384r1 (24) */ {NID_secp521r1, 256, TLS_CURVE_PRIME}, /* secp521r1 (25) */ {NID_brainpoolP256r1, 128, TLS_CURVE_PRIME}, /* brainpoolP256r1 (26) */ {NID_brainpoolP384r1, 192, TLS_CURVE_PRIME}, /* brainpoolP384r1 (27) */ {NID_brainpoolP512r1, 256, TLS_CURVE_PRIME}, /* brainpool512r1 (28) */ {NID_X25519, 128, TLS_CURVE_CUSTOM}, /* X25519 (29) */ }; static const unsigned char ecformats_default[] = { TLSEXT_ECPOINTFORMAT_uncompressed, TLSEXT_ECPOINTFORMAT_ansiX962_compressed_prime, TLSEXT_ECPOINTFORMAT_ansiX962_compressed_char2 }; /* The default curves */ static const unsigned char eccurves_default[] = { 0, 29, /* X25519 (29) */ 0, 23, /* secp256r1 (23) */ 0, 25, /* secp521r1 (25) */ 0, 24, /* secp384r1 (24) */ }; static const unsigned char suiteb_curves[] = { 0, TLSEXT_curve_P_256, 0, TLSEXT_curve_P_384 }; int tls1_ec_curve_id2nid(int curve_id, unsigned int *pflags) { const tls_curve_info *cinfo; /* ECC curves from RFC 4492 and RFC 7027 */ if ((curve_id < 1) || ((unsigned int)curve_id > OSSL_NELEM(nid_list))) return 0; cinfo = nid_list + curve_id - 1; if (pflags) *pflags = cinfo->flags; return cinfo->nid; } int tls1_ec_nid2curve_id(int nid) { size_t i; for (i = 0; i < OSSL_NELEM(nid_list); i++) { if (nid_list[i].nid == nid) return i + 1; } return 0; } /* * Get curves list, if "sess" is set return client curves otherwise * preferred list. * Sets |num_curves| to the number of curves in the list, i.e., * the length of |pcurves| is 2 * num_curves. * Returns 1 on success and 0 if the client curves list has invalid format. * The latter indicates an internal error: we should not be accepting such * lists in the first place. * TODO(emilia): we should really be storing the curves list in explicitly * parsed form instead. (However, this would affect binary compatibility * so cannot happen in the 1.0.x series.) */ static int tls1_get_curvelist(SSL *s, int sess, const unsigned char **pcurves, size_t *num_curves) { size_t pcurveslen = 0; if (sess) { *pcurves = s->session->tlsext_ellipticcurvelist; pcurveslen = s->session->tlsext_ellipticcurvelist_length; } else { /* For Suite B mode only include P-256, P-384 */ switch (tls1_suiteb(s)) { case SSL_CERT_FLAG_SUITEB_128_LOS: *pcurves = suiteb_curves; pcurveslen = sizeof(suiteb_curves); break; case SSL_CERT_FLAG_SUITEB_128_LOS_ONLY: *pcurves = suiteb_curves; pcurveslen = 2; break; case SSL_CERT_FLAG_SUITEB_192_LOS: *pcurves = suiteb_curves + 2; pcurveslen = 2; break; default: *pcurves = s->tlsext_ellipticcurvelist; pcurveslen = s->tlsext_ellipticcurvelist_length; } if (!*pcurves) { *pcurves = eccurves_default; pcurveslen = sizeof(eccurves_default); } } /* We do not allow odd length arrays to enter the system. */ if (pcurveslen & 1) { SSLerr(SSL_F_TLS1_GET_CURVELIST, ERR_R_INTERNAL_ERROR); *num_curves = 0; return 0; } *num_curves = pcurveslen / 2; return 1; } /* See if curve is allowed by security callback */ static int tls_curve_allowed(SSL *s, const unsigned char *curve, int op) { const tls_curve_info *cinfo; if (curve[0]) return 1; if ((curve[1] < 1) || ((size_t)curve[1] > OSSL_NELEM(nid_list))) return 0; cinfo = &nid_list[curve[1] - 1]; # ifdef OPENSSL_NO_EC2M if (cinfo->flags & TLS_CURVE_CHAR2) return 0; # endif return ssl_security(s, op, cinfo->secbits, cinfo->nid, (void *)curve); } /* Check a curve is one of our preferences */ int tls1_check_curve(SSL *s, const unsigned char *p, size_t len) { const unsigned char *curves; size_t num_curves, i; unsigned int suiteb_flags = tls1_suiteb(s); if (len != 3 || p[0] != NAMED_CURVE_TYPE) return 0; /* Check curve matches Suite B preferences */ if (suiteb_flags) { unsigned long cid = s->s3->tmp.new_cipher->id; if (p[1]) return 0; if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256) { if (p[2] != TLSEXT_curve_P_256) return 0; } else if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384) { if (p[2] != TLSEXT_curve_P_384) return 0; } else /* Should never happen */ return 0; } if (!tls1_get_curvelist(s, 0, &curves, &num_curves)) return 0; for (i = 0; i < num_curves; i++, curves += 2) { if (p[1] == curves[0] && p[2] == curves[1]) return tls_curve_allowed(s, p + 1, SSL_SECOP_CURVE_CHECK); } return 0; } /*- * For nmatch >= 0, return the NID of the |nmatch|th shared curve or NID_undef * if there is no match. * For nmatch == -1, return number of matches * For nmatch == -2, return the NID of the curve to use for * an EC tmp key, or NID_undef if there is no match. */ int tls1_shared_curve(SSL *s, int nmatch) { const unsigned char *pref, *supp; size_t num_pref, num_supp, i, j; int k; /* Can't do anything on client side */ if (s->server == 0) return -1; if (nmatch == -2) { if (tls1_suiteb(s)) { /* * For Suite B ciphersuite determines curve: we already know * these are acceptable due to previous checks. */ unsigned long cid = s->s3->tmp.new_cipher->id; if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256) return NID_X9_62_prime256v1; /* P-256 */ if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384) return NID_secp384r1; /* P-384 */ /* Should never happen */ return NID_undef; } /* If not Suite B just return first preference shared curve */ nmatch = 0; } /* * Avoid truncation. tls1_get_curvelist takes an int * but s->options is a long... */ if (!tls1_get_curvelist(s, (s->options & SSL_OP_CIPHER_SERVER_PREFERENCE) != 0, &supp, &num_supp)) /* In practice, NID_undef == 0 but let's be precise. */ return nmatch == -1 ? 0 : NID_undef; if (!tls1_get_curvelist(s, (s->options & SSL_OP_CIPHER_SERVER_PREFERENCE) == 0, &pref, &num_pref)) return nmatch == -1 ? 0 : NID_undef; for (k = 0, i = 0; i < num_pref; i++, pref += 2) { const unsigned char *tsupp = supp; for (j = 0; j < num_supp; j++, tsupp += 2) { if (pref[0] == tsupp[0] && pref[1] == tsupp[1]) { if (!tls_curve_allowed(s, pref, SSL_SECOP_CURVE_SHARED)) continue; if (nmatch == k) { int id = (pref[0] << 8) | pref[1]; return tls1_ec_curve_id2nid(id, NULL); } k++; } } } if (nmatch == -1) return k; /* Out of range (nmatch > k). */ return NID_undef; } int tls1_set_curves(unsigned char **pext, size_t *pextlen, int *curves, size_t ncurves) { unsigned char *clist, *p; size_t i; /* * Bitmap of curves included to detect duplicates: only works while curve * ids < 32 */ unsigned long dup_list = 0; clist = OPENSSL_malloc(ncurves * 2); if (clist == NULL) return 0; for (i = 0, p = clist; i < ncurves; i++) { unsigned long idmask; int id; id = tls1_ec_nid2curve_id(curves[i]); idmask = 1L << id; if (!id || (dup_list & idmask)) { OPENSSL_free(clist); return 0; } dup_list |= idmask; s2n(id, p); } OPENSSL_free(*pext); *pext = clist; *pextlen = ncurves * 2; return 1; } # define MAX_CURVELIST 28 typedef struct { size_t nidcnt; int nid_arr[MAX_CURVELIST]; } nid_cb_st; static int nid_cb(const char *elem, int len, void *arg) { nid_cb_st *narg = arg; size_t i; int nid; char etmp[20]; if (elem == NULL) return 0; if (narg->nidcnt == MAX_CURVELIST) return 0; if (len > (int)(sizeof(etmp) - 1)) return 0; memcpy(etmp, elem, len); etmp[len] = 0; nid = EC_curve_nist2nid(etmp); if (nid == NID_undef) nid = OBJ_sn2nid(etmp); if (nid == NID_undef) nid = OBJ_ln2nid(etmp); if (nid == NID_undef) return 0; for (i = 0; i < narg->nidcnt; i++) if (narg->nid_arr[i] == nid) return 0; narg->nid_arr[narg->nidcnt++] = nid; return 1; } /* Set curves based on a colon separate list */ int tls1_set_curves_list(unsigned char **pext, size_t *pextlen, const char *str) { nid_cb_st ncb; ncb.nidcnt = 0; if (!CONF_parse_list(str, ':', 1, nid_cb, &ncb)) return 0; if (pext == NULL) return 1; return tls1_set_curves(pext, pextlen, ncb.nid_arr, ncb.nidcnt); } /* For an EC key set TLS id and required compression based on parameters */ static int tls1_set_ec_id(unsigned char *curve_id, unsigned char *comp_id, EC_KEY *ec) { int id; const EC_GROUP *grp; if (!ec) return 0; /* Determine if it is a prime field */ grp = EC_KEY_get0_group(ec); if (!grp) return 0; /* Determine curve ID */ id = EC_GROUP_get_curve_name(grp); id = tls1_ec_nid2curve_id(id); /* If no id return error: we don't support arbitrary explicit curves */ if (id == 0) return 0; curve_id[0] = 0; curve_id[1] = (unsigned char)id; if (comp_id) { if (EC_KEY_get0_public_key(ec) == NULL) return 0; if (EC_KEY_get_conv_form(ec) == POINT_CONVERSION_UNCOMPRESSED) { *comp_id = TLSEXT_ECPOINTFORMAT_uncompressed; } else { if ((nid_list[id - 1].flags & TLS_CURVE_TYPE) == TLS_CURVE_PRIME) *comp_id = TLSEXT_ECPOINTFORMAT_ansiX962_compressed_prime; else *comp_id = TLSEXT_ECPOINTFORMAT_ansiX962_compressed_char2; } } return 1; } /* Check an EC key is compatible with extensions */ static int tls1_check_ec_key(SSL *s, unsigned char *curve_id, unsigned char *comp_id) { const unsigned char *pformats, *pcurves; size_t num_formats, num_curves, i; int j; /* * If point formats extension present check it, otherwise everything is * supported (see RFC4492). */ if (comp_id && s->session->tlsext_ecpointformatlist) { pformats = s->session->tlsext_ecpointformatlist; num_formats = s->session->tlsext_ecpointformatlist_length; for (i = 0; i < num_formats; i++, pformats++) { if (*comp_id == *pformats) break; } if (i == num_formats) return 0; } if (!curve_id) return 1; /* Check curve is consistent with client and server preferences */ for (j = 0; j <= 1; j++) { if (!tls1_get_curvelist(s, j, &pcurves, &num_curves)) return 0; if (j == 1 && num_curves == 0) { /* * If we've not received any curves then skip this check. * RFC 4492 does not require the supported elliptic curves extension * so if it is not sent we can just choose any curve. * It is invalid to send an empty list in the elliptic curves * extension, so num_curves == 0 always means no extension. */ break; } for (i = 0; i < num_curves; i++, pcurves += 2) { if (pcurves[0] == curve_id[0] && pcurves[1] == curve_id[1]) break; } if (i == num_curves) return 0; /* For clients can only check sent curve list */ if (!s->server) break; } return 1; } static void tls1_get_formatlist(SSL *s, const unsigned char **pformats, size_t *num_formats) { /* * If we have a custom point format list use it otherwise use default */ if (s->tlsext_ecpointformatlist) { *pformats = s->tlsext_ecpointformatlist; *num_formats = s->tlsext_ecpointformatlist_length; } else { *pformats = ecformats_default; /* For Suite B we don't support char2 fields */ if (tls1_suiteb(s)) *num_formats = sizeof(ecformats_default) - 1; else *num_formats = sizeof(ecformats_default); } } /* * Check cert parameters compatible with extensions: currently just checks EC * certificates have compatible curves and compression. */ static int tls1_check_cert_param(SSL *s, X509 *x, int set_ee_md) { unsigned char comp_id, curve_id[2]; EVP_PKEY *pkey; int rv; pkey = X509_get0_pubkey(x); if (!pkey) return 0; /* If not EC nothing to do */ if (EVP_PKEY_id(pkey) != EVP_PKEY_EC) return 1; rv = tls1_set_ec_id(curve_id, &comp_id, EVP_PKEY_get0_EC_KEY(pkey)); if (!rv) return 0; /* * Can't check curve_id for client certs as we don't have a supported * curves extension. */ rv = tls1_check_ec_key(s, s->server ? curve_id : NULL, &comp_id); if (!rv) return 0; /* * Special case for suite B. We *MUST* sign using SHA256+P-256 or * SHA384+P-384, adjust digest if necessary. */ if (set_ee_md && tls1_suiteb(s)) { int check_md; size_t i; CERT *c = s->cert; if (curve_id[0]) return 0; /* Check to see we have necessary signing algorithm */ if (curve_id[1] == TLSEXT_curve_P_256) check_md = NID_ecdsa_with_SHA256; else if (curve_id[1] == TLSEXT_curve_P_384) check_md = NID_ecdsa_with_SHA384; else return 0; /* Should never happen */ for (i = 0; i < c->shared_sigalgslen; i++) if (check_md == c->shared_sigalgs[i].signandhash_nid) break; if (i == c->shared_sigalgslen) return 0; if (set_ee_md == 2) { if (check_md == NID_ecdsa_with_SHA256) s->s3->tmp.md[SSL_PKEY_ECC] = EVP_sha256(); else s->s3->tmp.md[SSL_PKEY_ECC] = EVP_sha384(); } } return rv; } # ifndef OPENSSL_NO_EC /* * tls1_check_ec_tmp_key - Check EC temporary key compatibility * @s: SSL connection * @cid: Cipher ID we're considering using * * Checks that the kECDHE cipher suite we're considering using * is compatible with the client extensions. * * Returns 0 when the cipher can't be used or 1 when it can. */ int tls1_check_ec_tmp_key(SSL *s, unsigned long cid) { /* * If Suite B, AES128 MUST use P-256 and AES256 MUST use P-384, no other * curves permitted. */ if (tls1_suiteb(s)) { unsigned char curve_id[2]; /* Curve to check determined by ciphersuite */ if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256) curve_id[1] = TLSEXT_curve_P_256; else if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384) curve_id[1] = TLSEXT_curve_P_384; else return 0; curve_id[0] = 0; /* Check this curve is acceptable */ if (!tls1_check_ec_key(s, curve_id, NULL)) return 0; return 1; } /* Need a shared curve */ if (tls1_shared_curve(s, 0)) return 1; return 0; } # endif /* OPENSSL_NO_EC */ #else static int tls1_check_cert_param(SSL *s, X509 *x, int set_ee_md) { return 1; } #endif /* OPENSSL_NO_EC */ /* * List of supported signature algorithms and hashes. Should make this * customisable at some point, for now include everything we support. */ #ifdef OPENSSL_NO_RSA # define tlsext_sigalg_rsa(md) /* */ #else # define tlsext_sigalg_rsa(md) md, TLSEXT_signature_rsa, #endif #ifdef OPENSSL_NO_DSA # define tlsext_sigalg_dsa(md) /* */ #else # define tlsext_sigalg_dsa(md) md, TLSEXT_signature_dsa, #endif #ifdef OPENSSL_NO_EC # define tlsext_sigalg_ecdsa(md)/* */ #else # define tlsext_sigalg_ecdsa(md) md, TLSEXT_signature_ecdsa, #endif #define tlsext_sigalg(md) \ tlsext_sigalg_rsa(md) \ tlsext_sigalg_dsa(md) \ tlsext_sigalg_ecdsa(md) static const unsigned char tls12_sigalgs[] = { tlsext_sigalg(TLSEXT_hash_sha512) tlsext_sigalg(TLSEXT_hash_sha384) tlsext_sigalg(TLSEXT_hash_sha256) tlsext_sigalg(TLSEXT_hash_sha224) tlsext_sigalg(TLSEXT_hash_sha1) #ifndef OPENSSL_NO_GOST TLSEXT_hash_gostr3411, TLSEXT_signature_gostr34102001, TLSEXT_hash_gostr34112012_256, TLSEXT_signature_gostr34102012_256, TLSEXT_hash_gostr34112012_512, TLSEXT_signature_gostr34102012_512 #endif }; #ifndef OPENSSL_NO_EC static const unsigned char suiteb_sigalgs[] = { tlsext_sigalg_ecdsa(TLSEXT_hash_sha256) tlsext_sigalg_ecdsa(TLSEXT_hash_sha384) }; #endif size_t tls12_get_psigalgs(SSL *s, int sent, const unsigned char **psigs) { /* * If Suite B mode use Suite B sigalgs only, ignore any other * preferences. */ #ifndef OPENSSL_NO_EC switch (tls1_suiteb(s)) { case SSL_CERT_FLAG_SUITEB_128_LOS: *psigs = suiteb_sigalgs; return sizeof(suiteb_sigalgs); case SSL_CERT_FLAG_SUITEB_128_LOS_ONLY: *psigs = suiteb_sigalgs; return 2; case SSL_CERT_FLAG_SUITEB_192_LOS: *psigs = suiteb_sigalgs + 2; return 2; } #endif /* If server use client authentication sigalgs if not NULL */ if (s->server == sent && s->cert->client_sigalgs) { *psigs = s->cert->client_sigalgs; return s->cert->client_sigalgslen; } else if (s->cert->conf_sigalgs) { *psigs = s->cert->conf_sigalgs; return s->cert->conf_sigalgslen; } else { *psigs = tls12_sigalgs; return sizeof(tls12_sigalgs); } } /* * Check signature algorithm is consistent with sent supported signature * algorithms and if so return relevant digest. */ int tls12_check_peer_sigalg(const EVP_MD **pmd, SSL *s, const unsigned char *sig, EVP_PKEY *pkey) { const unsigned char *sent_sigs; size_t sent_sigslen, i; int sigalg = tls12_get_sigid(pkey); /* Should never happen */ if (sigalg == -1) return -1; /* Check key type is consistent with signature */ if (sigalg != (int)sig[1]) { SSLerr(SSL_F_TLS12_CHECK_PEER_SIGALG, SSL_R_WRONG_SIGNATURE_TYPE); return 0; } #ifndef OPENSSL_NO_EC if (EVP_PKEY_id(pkey) == EVP_PKEY_EC) { unsigned char curve_id[2], comp_id; /* Check compression and curve matches extensions */ if (!tls1_set_ec_id(curve_id, &comp_id, EVP_PKEY_get0_EC_KEY(pkey))) return 0; if (!s->server && !tls1_check_ec_key(s, curve_id, &comp_id)) { SSLerr(SSL_F_TLS12_CHECK_PEER_SIGALG, SSL_R_WRONG_CURVE); return 0; } /* If Suite B only P-384+SHA384 or P-256+SHA-256 allowed */ if (tls1_suiteb(s)) { if (curve_id[0]) return 0; if (curve_id[1] == TLSEXT_curve_P_256) { if (sig[0] != TLSEXT_hash_sha256) { SSLerr(SSL_F_TLS12_CHECK_PEER_SIGALG, SSL_R_ILLEGAL_SUITEB_DIGEST); return 0; } } else if (curve_id[1] == TLSEXT_curve_P_384) { if (sig[0] != TLSEXT_hash_sha384) { SSLerr(SSL_F_TLS12_CHECK_PEER_SIGALG, SSL_R_ILLEGAL_SUITEB_DIGEST); return 0; } } else return 0; } } else if (tls1_suiteb(s)) return 0; #endif /* Check signature matches a type we sent */ sent_sigslen = tls12_get_psigalgs(s, 1, &sent_sigs); for (i = 0; i < sent_sigslen; i += 2, sent_sigs += 2) { if (sig[0] == sent_sigs[0] && sig[1] == sent_sigs[1]) break; } /* Allow fallback to SHA1 if not strict mode */ if (i == sent_sigslen && (sig[0] != TLSEXT_hash_sha1 || s->cert->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT)) { SSLerr(SSL_F_TLS12_CHECK_PEER_SIGALG, SSL_R_WRONG_SIGNATURE_TYPE); return 0; } *pmd = tls12_get_hash(sig[0]); if (*pmd == NULL) { SSLerr(SSL_F_TLS12_CHECK_PEER_SIGALG, SSL_R_UNKNOWN_DIGEST); return 0; } /* Make sure security callback allows algorithm */ if (!ssl_security(s, SSL_SECOP_SIGALG_CHECK, EVP_MD_size(*pmd) * 4, EVP_MD_type(*pmd), (void *)sig)) { SSLerr(SSL_F_TLS12_CHECK_PEER_SIGALG, SSL_R_WRONG_SIGNATURE_TYPE); return 0; } /* * Store the digest used so applications can retrieve it if they wish. */ s->s3->tmp.peer_md = *pmd; return 1; } /* * Set a mask of disabled algorithms: an algorithm is disabled if it isn't * supported, doesn't appear in supported signature algorithms, isn't supported * by the enabled protocol versions or by the security level. * * This function should only be used for checking which ciphers are supported * by the client. * * Call ssl_cipher_disabled() to check that it's enabled or not. */ void ssl_set_client_disabled(SSL *s) { s->s3->tmp.mask_a = 0; s->s3->tmp.mask_k = 0; ssl_set_sig_mask(&s->s3->tmp.mask_a, s, SSL_SECOP_SIGALG_MASK); ssl_get_client_min_max_version(s, &s->s3->tmp.min_ver, &s->s3->tmp.max_ver); #ifndef OPENSSL_NO_PSK /* with PSK there must be client callback set */ if (!s->psk_client_callback) { s->s3->tmp.mask_a |= SSL_aPSK; s->s3->tmp.mask_k |= SSL_PSK; } #endif /* OPENSSL_NO_PSK */ #ifndef OPENSSL_NO_SRP if (!(s->srp_ctx.srp_Mask & SSL_kSRP)) { s->s3->tmp.mask_a |= SSL_aSRP; s->s3->tmp.mask_k |= SSL_kSRP; } #endif } /* * ssl_cipher_disabled - check that a cipher is disabled or not * @s: SSL connection that you want to use the cipher on * @c: cipher to check * @op: Security check that you want to do * * Returns 1 when it's disabled, 0 when enabled. */ int ssl_cipher_disabled(SSL *s, const SSL_CIPHER *c, int op) { if (c->algorithm_mkey & s->s3->tmp.mask_k || c->algorithm_auth & s->s3->tmp.mask_a) return 1; if (s->s3->tmp.max_ver == 0) return 1; if (!SSL_IS_DTLS(s) && ((c->min_tls > s->s3->tmp.max_ver) || (c->max_tls < s->s3->tmp.min_ver))) return 1; if (SSL_IS_DTLS(s) && (DTLS_VERSION_GT(c->min_dtls, s->s3->tmp.max_ver) || DTLS_VERSION_LT(c->max_dtls, s->s3->tmp.min_ver))) return 1; return !ssl_security(s, op, c->strength_bits, 0, (void *)c); } static int tls_use_ticket(SSL *s) { if (s->options & SSL_OP_NO_TICKET) return 0; return ssl_security(s, SSL_SECOP_TICKET, 0, 0, NULL); } static int compare_uint(const void *p1, const void *p2) { unsigned int u1 = *((const unsigned int *)p1); unsigned int u2 = *((const unsigned int *)p2); if (u1 < u2) return -1; else if (u1 > u2) return 1; else return 0; } /* * Per http://tools.ietf.org/html/rfc5246#section-7.4.1.4, there may not be * more than one extension of the same type in a ClientHello or ServerHello. * This function does an initial scan over the extensions block to filter those * out. It returns 1 if all extensions are unique, and 0 if the extensions * contain duplicates, could not be successfully parsed, or an internal error * occurred. */ static int tls1_check_duplicate_extensions(const PACKET *packet) { PACKET extensions = *packet; size_t num_extensions = 0, i = 0; unsigned int *extension_types = NULL; int ret = 0; /* First pass: count the extensions. */ while (PACKET_remaining(&extensions) > 0) { unsigned int type; PACKET extension; if (!PACKET_get_net_2(&extensions, &type) || !PACKET_get_length_prefixed_2(&extensions, &extension)) { goto done; } num_extensions++; } if (num_extensions <= 1) return 1; extension_types = OPENSSL_malloc(sizeof(unsigned int) * num_extensions); if (extension_types == NULL) { SSLerr(SSL_F_TLS1_CHECK_DUPLICATE_EXTENSIONS, ERR_R_MALLOC_FAILURE); goto done; } /* Second pass: gather the extension types. */ extensions = *packet; for (i = 0; i < num_extensions; i++) { PACKET extension; if (!PACKET_get_net_2(&extensions, &extension_types[i]) || !PACKET_get_length_prefixed_2(&extensions, &extension)) { /* This should not happen. */ SSLerr(SSL_F_TLS1_CHECK_DUPLICATE_EXTENSIONS, ERR_R_INTERNAL_ERROR); goto done; } } if (PACKET_remaining(&extensions) != 0) { SSLerr(SSL_F_TLS1_CHECK_DUPLICATE_EXTENSIONS, ERR_R_INTERNAL_ERROR); goto done; } /* Sort the extensions and make sure there are no duplicates. */ qsort(extension_types, num_extensions, sizeof(unsigned int), compare_uint); for (i = 1; i < num_extensions; i++) { if (extension_types[i - 1] == extension_types[i]) goto done; } ret = 1; done: OPENSSL_free(extension_types); return ret; } unsigned char *ssl_add_clienthello_tlsext(SSL *s, unsigned char *buf, unsigned char *limit, int *al) { int extdatalen = 0; unsigned char *orig = buf; unsigned char *ret = buf; #ifndef OPENSSL_NO_EC /* See if we support any ECC ciphersuites */ int using_ecc = 0; if (s->version >= TLS1_VERSION || SSL_IS_DTLS(s)) { int i; unsigned long alg_k, alg_a; STACK_OF(SSL_CIPHER) *cipher_stack = SSL_get_ciphers(s); for (i = 0; i < sk_SSL_CIPHER_num(cipher_stack); i++) { const SSL_CIPHER *c = sk_SSL_CIPHER_value(cipher_stack, i); alg_k = c->algorithm_mkey; alg_a = c->algorithm_auth; if ((alg_k & (SSL_kECDHE | SSL_kECDHEPSK)) || (alg_a & SSL_aECDSA)) { using_ecc = 1; break; } } } #endif ret += 2; if (ret >= limit) return NULL; /* this really never occurs, but ... */ /* Add RI if renegotiating */ if (s->renegotiate) { int el; if (!ssl_add_clienthello_renegotiate_ext(s, 0, &el, 0)) { SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR); return NULL; } if (CHECKLEN(ret, 4 + el, limit)) return NULL; s2n(TLSEXT_TYPE_renegotiate, ret); s2n(el, ret); if (!ssl_add_clienthello_renegotiate_ext(s, ret, &el, el)) { SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR); return NULL; } ret += el; } /* Only add RI for SSLv3 */ if (s->client_version == SSL3_VERSION) goto done; if (s->tlsext_hostname != NULL) { /* Add TLS extension servername to the Client Hello message */ size_t size_str; /*- * check for enough space. * 4 for the servername type and extension length * 2 for servernamelist length * 1 for the hostname type * 2 for hostname length * + hostname length */ size_str = strlen(s->tlsext_hostname); if (CHECKLEN(ret, 9 + size_str, limit)) return NULL; /* extension type and length */ s2n(TLSEXT_TYPE_server_name, ret); s2n(size_str + 5, ret); /* length of servername list */ s2n(size_str + 3, ret); /* hostname type, length and hostname */ *(ret++) = (unsigned char)TLSEXT_NAMETYPE_host_name; s2n(size_str, ret); memcpy(ret, s->tlsext_hostname, size_str); ret += size_str; } #ifndef OPENSSL_NO_SRP /* Add SRP username if there is one */ if (s->srp_ctx.login != NULL) { /* Add TLS extension SRP username to the * Client Hello message */ size_t login_len = strlen(s->srp_ctx.login); if (login_len > 255 || login_len == 0) { SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR); return NULL; } /*- * check for enough space. * 4 for the srp type type and extension length * 1 for the srp user identity * + srp user identity length */ if (CHECKLEN(ret, 5 + login_len, limit)) return NULL; /* fill in the extension */ s2n(TLSEXT_TYPE_srp, ret); s2n(login_len + 1, ret); (*ret++) = (unsigned char)login_len; memcpy(ret, s->srp_ctx.login, login_len); ret += login_len; } #endif #ifndef OPENSSL_NO_EC if (using_ecc) { /* * Add TLS extension ECPointFormats to the ClientHello message */ const unsigned char *pcurves, *pformats; size_t num_curves, num_formats, curves_list_len; size_t i; unsigned char *etmp; tls1_get_formatlist(s, &pformats, &num_formats); if (num_formats > 255) { SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR); return NULL; } /*- * check for enough space. * 4 bytes for the ec point formats type and extension length * 1 byte for the length of the formats * + formats length */ if (CHECKLEN(ret, 5 + num_formats, limit)) return NULL; s2n(TLSEXT_TYPE_ec_point_formats, ret); /* The point format list has 1-byte length. */ s2n(num_formats + 1, ret); *(ret++) = (unsigned char)num_formats; memcpy(ret, pformats, num_formats); ret += num_formats; /* * Add TLS extension EllipticCurves to the ClientHello message */ pcurves = s->tlsext_ellipticcurvelist; if (!tls1_get_curvelist(s, 0, &pcurves, &num_curves)) return NULL; if (num_curves > 65532 / 2) { SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR); return NULL; } /*- * check for enough space. * 4 bytes for the ec curves type and extension length * 2 bytes for the curve list length * + curve list length */ if (CHECKLEN(ret, 6 + (num_curves * 2), limit)) return NULL; s2n(TLSEXT_TYPE_elliptic_curves, ret); etmp = ret + 4; /* Copy curve ID if supported */ for (i = 0; i < num_curves; i++, pcurves += 2) { if (tls_curve_allowed(s, pcurves, SSL_SECOP_CURVE_SUPPORTED)) { *etmp++ = pcurves[0]; *etmp++ = pcurves[1]; } } curves_list_len = etmp - ret - 4; s2n(curves_list_len + 2, ret); s2n(curves_list_len, ret); ret += curves_list_len; } #endif /* OPENSSL_NO_EC */ if (tls_use_ticket(s)) { size_t ticklen; if (!s->new_session && s->session && s->session->tlsext_tick) ticklen = s->session->tlsext_ticklen; else if (s->session && s->tlsext_session_ticket && s->tlsext_session_ticket->data) { ticklen = s->tlsext_session_ticket->length; s->session->tlsext_tick = OPENSSL_malloc(ticklen); if (s->session->tlsext_tick == NULL) return NULL; memcpy(s->session->tlsext_tick, s->tlsext_session_ticket->data, ticklen); s->session->tlsext_ticklen = ticklen; } else ticklen = 0; if (ticklen == 0 && s->tlsext_session_ticket && s->tlsext_session_ticket->data == NULL) goto skip_ext; /* * Check for enough room 2 for extension type, 2 for len rest for * ticket */ if (CHECKLEN(ret, 4 + ticklen, limit)) return NULL; s2n(TLSEXT_TYPE_session_ticket, ret); s2n(ticklen, ret); if (ticklen > 0) { memcpy(ret, s->session->tlsext_tick, ticklen); ret += ticklen; } } skip_ext: if (SSL_CLIENT_USE_SIGALGS(s)) { size_t salglen; const unsigned char *salg; unsigned char *etmp; salglen = tls12_get_psigalgs(s, 1, &salg); /*- * check for enough space. * 4 bytes for the sigalgs type and extension length * 2 bytes for the sigalg list length * + sigalg list length */ if (CHECKLEN(ret, salglen + 6, limit)) return NULL; s2n(TLSEXT_TYPE_signature_algorithms, ret); etmp = ret; /* Skip over lengths for now */ ret += 4; salglen = tls12_copy_sigalgs(s, ret, salg, salglen); /* Fill in lengths */ s2n(salglen + 2, etmp); s2n(salglen, etmp); ret += salglen; } #ifndef OPENSSL_NO_OCSP if (s->tlsext_status_type == TLSEXT_STATUSTYPE_ocsp) { int i; size_t extlen, idlen; int lentmp; OCSP_RESPID *id; idlen = 0; for (i = 0; i < sk_OCSP_RESPID_num(s->tlsext_ocsp_ids); i++) { id = sk_OCSP_RESPID_value(s->tlsext_ocsp_ids, i); lentmp = i2d_OCSP_RESPID(id, NULL); if (lentmp <= 0) return NULL; idlen += (size_t)lentmp + 2; } if (s->tlsext_ocsp_exts) { lentmp = i2d_X509_EXTENSIONS(s->tlsext_ocsp_exts, NULL); if (lentmp < 0) return NULL; extlen = (size_t)lentmp; } else extlen = 0; if (extlen + idlen > 0xFFF0) return NULL; /* * 2 bytes for status request type * 2 bytes for status request len * 1 byte for OCSP request type * 2 bytes for length of ids * 2 bytes for length of extensions * + length of ids * + length of extensions */ if (CHECKLEN(ret, 9 + idlen + extlen, limit)) return NULL; s2n(TLSEXT_TYPE_status_request, ret); s2n(extlen + idlen + 5, ret); *(ret++) = TLSEXT_STATUSTYPE_ocsp; s2n(idlen, ret); for (i = 0; i < sk_OCSP_RESPID_num(s->tlsext_ocsp_ids); i++) { /* save position of id len */ unsigned char *q = ret; id = sk_OCSP_RESPID_value(s->tlsext_ocsp_ids, i); /* skip over id len */ ret += 2; lentmp = i2d_OCSP_RESPID(id, &ret); /* write id len */ s2n(lentmp, q); } s2n(extlen, ret); if (extlen > 0) i2d_X509_EXTENSIONS(s->tlsext_ocsp_exts, &ret); } #endif #ifndef OPENSSL_NO_HEARTBEATS if (SSL_IS_DTLS(s)) { /* Add Heartbeat extension */ /*- * check for enough space. * 4 bytes for the heartbeat ext type and extension length * 1 byte for the mode */ if (CHECKLEN(ret, 5, limit)) return NULL; s2n(TLSEXT_TYPE_heartbeat, ret); s2n(1, ret); /*- * Set mode: * 1: peer may send requests * 2: peer not allowed to send requests */ if (s->tlsext_heartbeat & SSL_DTLSEXT_HB_DONT_RECV_REQUESTS) *(ret++) = SSL_DTLSEXT_HB_DONT_SEND_REQUESTS; else *(ret++) = SSL_DTLSEXT_HB_ENABLED; } #endif #ifndef OPENSSL_NO_NEXTPROTONEG if (s->ctx->next_proto_select_cb && !s->s3->tmp.finish_md_len) { /* * The client advertises an empty extension to indicate its support * for Next Protocol Negotiation */ /*- * check for enough space. * 4 bytes for the NPN ext type and extension length */ if (CHECKLEN(ret, 4, limit)) return NULL; s2n(TLSEXT_TYPE_next_proto_neg, ret); s2n(0, ret); } #endif /* * finish_md_len is non-zero during a renegotiation, so * this avoids sending ALPN during the renegotiation * (see longer comment below) */ if (s->alpn_client_proto_list && !s->s3->tmp.finish_md_len) { /*- * check for enough space. * 4 bytes for the ALPN type and extension length * 2 bytes for the ALPN protocol list length * + ALPN protocol list length */ if (CHECKLEN(ret, 6 + s->alpn_client_proto_list_len, limit)) return NULL; s2n(TLSEXT_TYPE_application_layer_protocol_negotiation, ret); s2n(2 + s->alpn_client_proto_list_len, ret); s2n(s->alpn_client_proto_list_len, ret); memcpy(ret, s->alpn_client_proto_list, s->alpn_client_proto_list_len); ret += s->alpn_client_proto_list_len; s->s3->alpn_sent = 1; } #ifndef OPENSSL_NO_SRTP if (SSL_IS_DTLS(s) && SSL_get_srtp_profiles(s)) { int el; /* Returns 0 on success!! */ if (ssl_add_clienthello_use_srtp_ext(s, 0, &el, 0)) { SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR); return NULL; } /*- * check for enough space. * 4 bytes for the SRTP type and extension length * + SRTP profiles length */ if (CHECKLEN(ret, 4 + el, limit)) return NULL; s2n(TLSEXT_TYPE_use_srtp, ret); s2n(el, ret); if (ssl_add_clienthello_use_srtp_ext(s, ret, &el, el)) { SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR); return NULL; } ret += el; } #endif custom_ext_init(&s->cert->cli_ext); /* Add custom TLS Extensions to ClientHello */ if (!custom_ext_add(s, 0, &ret, limit, al)) return NULL; /* * In 1.1.0 before 1.1.0c we negotiated EtM with DTLS, then just * silently failed to actually do it. It is fixed in 1.1.1 but to * ease the transition especially from 1.1.0b to 1.1.0c, we just * disable it in 1.1.0. */ if (!SSL_IS_DTLS(s)) { /*- * check for enough space. * 4 bytes for the ETM type and extension length */ if (CHECKLEN(ret, 4, limit)) return NULL; s2n(TLSEXT_TYPE_encrypt_then_mac, ret); s2n(0, ret); } #ifndef OPENSSL_NO_CT if (s->ct_validation_callback != NULL) { /*- * check for enough space. * 4 bytes for the SCT type and extension length */ if (CHECKLEN(ret, 4, limit)) return NULL; s2n(TLSEXT_TYPE_signed_certificate_timestamp, ret); s2n(0, ret); } #endif /*- * check for enough space. * 4 bytes for the EMS type and extension length */ if (CHECKLEN(ret, 4, limit)) return NULL; s2n(TLSEXT_TYPE_extended_master_secret, ret); s2n(0, ret); /* * Add padding to workaround bugs in F5 terminators. See * https://tools.ietf.org/html/draft-agl-tls-padding-03 NB: because this * code works out the length of all existing extensions it MUST always * appear last. */ if (s->options & SSL_OP_TLSEXT_PADDING) { int hlen = ret - (unsigned char *)s->init_buf->data; if (hlen > 0xff && hlen < 0x200) { hlen = 0x200 - hlen; if (hlen >= 4) hlen -= 4; else hlen = 0; /*- * check for enough space. Strictly speaking we know we've already * got enough space because to get here the message size is < 0x200, * but we know that we've allocated far more than that in the buffer * - but for consistency and robustness we're going to check anyway. * * 4 bytes for the padding type and extension length * + padding length */ if (CHECKLEN(ret, 4 + hlen, limit)) return NULL; s2n(TLSEXT_TYPE_padding, ret); s2n(hlen, ret); memset(ret, 0, hlen); ret += hlen; } } done: if ((extdatalen = ret - orig - 2) == 0) return orig; s2n(extdatalen, orig); return ret; } unsigned char *ssl_add_serverhello_tlsext(SSL *s, unsigned char *buf, unsigned char *limit, int *al) { int extdatalen = 0; unsigned char *orig = buf; unsigned char *ret = buf; #ifndef OPENSSL_NO_NEXTPROTONEG int next_proto_neg_seen; #endif #ifndef OPENSSL_NO_EC unsigned long alg_k = s->s3->tmp.new_cipher->algorithm_mkey; unsigned long alg_a = s->s3->tmp.new_cipher->algorithm_auth; int using_ecc = (alg_k & SSL_kECDHE) || (alg_a & SSL_aECDSA); using_ecc = using_ecc && (s->session->tlsext_ecpointformatlist != NULL); #endif ret += 2; if (ret >= limit) return NULL; /* this really never occurs, but ... */ if (s->s3->send_connection_binding) { int el; if (!ssl_add_serverhello_renegotiate_ext(s, 0, &el, 0)) { SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR); return NULL; } /*- * check for enough space. * 4 bytes for the reneg type and extension length * + reneg data length */ if (CHECKLEN(ret, 4 + el, limit)) return NULL; s2n(TLSEXT_TYPE_renegotiate, ret); s2n(el, ret); if (!ssl_add_serverhello_renegotiate_ext(s, ret, &el, el)) { SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR); return NULL; } ret += el; } /* Only add RI for SSLv3 */ if (s->version == SSL3_VERSION) goto done; if (!s->hit && s->servername_done == 1 && s->session->tlsext_hostname != NULL) { /*- * check for enough space. * 4 bytes for the server name type and extension length */ if (CHECKLEN(ret, 4, limit)) return NULL; s2n(TLSEXT_TYPE_server_name, ret); s2n(0, ret); } #ifndef OPENSSL_NO_EC if (using_ecc) { const unsigned char *plist; size_t plistlen; /* * Add TLS extension ECPointFormats to the ServerHello message */ tls1_get_formatlist(s, &plist, &plistlen); if (plistlen > 255) { SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR); return NULL; } /*- * check for enough space. * 4 bytes for the ec points format type and extension length * 1 byte for the points format list length * + length of points format list */ if (CHECKLEN(ret, 5 + plistlen, limit)) return NULL; s2n(TLSEXT_TYPE_ec_point_formats, ret); s2n(plistlen + 1, ret); *(ret++) = (unsigned char)plistlen; memcpy(ret, plist, plistlen); ret += plistlen; } /* * Currently the server should not respond with a SupportedCurves * extension */ #endif /* OPENSSL_NO_EC */ if (s->tlsext_ticket_expected && tls_use_ticket(s)) { /*- * check for enough space. * 4 bytes for the Ticket type and extension length */ if (CHECKLEN(ret, 4, limit)) return NULL; s2n(TLSEXT_TYPE_session_ticket, ret); s2n(0, ret); } else { /* * if we don't add the above TLSEXT, we can't add a session ticket * later */ s->tlsext_ticket_expected = 0; } if (s->tlsext_status_expected) { /*- * check for enough space. * 4 bytes for the Status request type and extension length */ if (CHECKLEN(ret, 4, limit)) return NULL; s2n(TLSEXT_TYPE_status_request, ret); s2n(0, ret); } #ifndef OPENSSL_NO_SRTP if (SSL_IS_DTLS(s) && s->srtp_profile) { int el; /* Returns 0 on success!! */ if (ssl_add_serverhello_use_srtp_ext(s, 0, &el, 0)) { SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR); return NULL; } /*- * check for enough space. * 4 bytes for the SRTP profiles type and extension length * + length of the SRTP profiles list */ if (CHECKLEN(ret, 4 + el, limit)) return NULL; s2n(TLSEXT_TYPE_use_srtp, ret); s2n(el, ret); if (ssl_add_serverhello_use_srtp_ext(s, ret, &el, el)) { SSLerr(SSL_F_SSL_ADD_SERVERHELLO_TLSEXT, ERR_R_INTERNAL_ERROR); return NULL; } ret += el; } #endif if (((s->s3->tmp.new_cipher->id & 0xFFFF) == 0x80 || (s->s3->tmp.new_cipher->id & 0xFFFF) == 0x81) && (SSL_get_options(s) & SSL_OP_CRYPTOPRO_TLSEXT_BUG)) { const unsigned char cryptopro_ext[36] = { 0xfd, 0xe8, /* 65000 */ 0x00, 0x20, /* 32 bytes length */ 0x30, 0x1e, 0x30, 0x08, 0x06, 0x06, 0x2a, 0x85, 0x03, 0x02, 0x02, 0x09, 0x30, 0x08, 0x06, 0x06, 0x2a, 0x85, 0x03, 0x02, 0x02, 0x16, 0x30, 0x08, 0x06, 0x06, 0x2a, 0x85, 0x03, 0x02, 0x02, 0x17 }; /* check for enough space. */ if (CHECKLEN(ret, sizeof(cryptopro_ext), limit)) return NULL; memcpy(ret, cryptopro_ext, sizeof(cryptopro_ext)); ret += sizeof(cryptopro_ext); } #ifndef OPENSSL_NO_HEARTBEATS /* Add Heartbeat extension if we've received one */ if (SSL_IS_DTLS(s) && (s->tlsext_heartbeat & SSL_DTLSEXT_HB_ENABLED)) { /*- * check for enough space. * 4 bytes for the Heartbeat type and extension length * 1 byte for the mode */ if (CHECKLEN(ret, 5, limit)) return NULL; s2n(TLSEXT_TYPE_heartbeat, ret); s2n(1, ret); /*- * Set mode: * 1: peer may send requests * 2: peer not allowed to send requests */ if (s->tlsext_heartbeat & SSL_DTLSEXT_HB_DONT_RECV_REQUESTS) *(ret++) = SSL_DTLSEXT_HB_DONT_SEND_REQUESTS; else *(ret++) = SSL_DTLSEXT_HB_ENABLED; } #endif #ifndef OPENSSL_NO_NEXTPROTONEG next_proto_neg_seen = s->s3->next_proto_neg_seen; s->s3->next_proto_neg_seen = 0; if (next_proto_neg_seen && s->ctx->next_protos_advertised_cb) { const unsigned char *npa; unsigned int npalen; int r; r = s->ctx->next_protos_advertised_cb(s, &npa, &npalen, s-> ctx->next_protos_advertised_cb_arg); if (r == SSL_TLSEXT_ERR_OK) { /*- * check for enough space. * 4 bytes for the NPN type and extension length * + length of protocols list */ if (CHECKLEN(ret, 4 + npalen, limit)) return NULL; s2n(TLSEXT_TYPE_next_proto_neg, ret); s2n(npalen, ret); memcpy(ret, npa, npalen); ret += npalen; s->s3->next_proto_neg_seen = 1; } } #endif if (!custom_ext_add(s, 1, &ret, limit, al)) return NULL; if (s->tlsext_use_etm) { /* * Don't use encrypt_then_mac if AEAD or RC4 might want to disable * for other cases too. */ if (SSL_IS_DTLS(s) || s->s3->tmp.new_cipher->algorithm_mac == SSL_AEAD || s->s3->tmp.new_cipher->algorithm_enc == SSL_RC4 || s->s3->tmp.new_cipher->algorithm_enc == SSL_eGOST2814789CNT || s->s3->tmp.new_cipher->algorithm_enc == SSL_eGOST2814789CNT12) s->tlsext_use_etm = 0; else { /*- * check for enough space. * 4 bytes for the ETM type and extension length */ if (CHECKLEN(ret, 4, limit)) return NULL; s2n(TLSEXT_TYPE_encrypt_then_mac, ret); s2n(0, ret); } } if (s->s3->flags & TLS1_FLAGS_RECEIVED_EXTMS) { /*- * check for enough space. * 4 bytes for the EMS type and extension length */ if (CHECKLEN(ret, 4, limit)) return NULL; s2n(TLSEXT_TYPE_extended_master_secret, ret); s2n(0, ret); } if (s->s3->alpn_selected != NULL) { const unsigned char *selected = s->s3->alpn_selected; size_t len = s->s3->alpn_selected_len; /*- * check for enough space. * 4 bytes for the ALPN type and extension length * 2 bytes for ALPN data length * 1 byte for selected protocol length * + length of the selected protocol */ if (CHECKLEN(ret, 7 + len, limit)) return NULL; s2n(TLSEXT_TYPE_application_layer_protocol_negotiation, ret); s2n(3 + len, ret); s2n(1 + len, ret); *ret++ = len; memcpy(ret, selected, len); ret += len; } done: if ((extdatalen = ret - orig - 2) == 0) return orig; s2n(extdatalen, orig); return ret; } /* * Save the ALPN extension in a ClientHello. * pkt: the contents of the ALPN extension, not including type and length. * al: a pointer to the alert value to send in the event of a failure. * returns: 1 on success, 0 on error. */ static int tls1_alpn_handle_client_hello(SSL *s, PACKET *pkt, int *al) { PACKET protocol_list, save_protocol_list, protocol; *al = SSL_AD_DECODE_ERROR; if (!PACKET_as_length_prefixed_2(pkt, &protocol_list) || PACKET_remaining(&protocol_list) < 2) { return 0; } save_protocol_list = protocol_list; do { /* Protocol names can't be empty. */ if (!PACKET_get_length_prefixed_1(&protocol_list, &protocol) || PACKET_remaining(&protocol) == 0) { return 0; } } while (PACKET_remaining(&protocol_list) != 0); if (!PACKET_memdup(&save_protocol_list, &s->s3->alpn_proposed, &s->s3->alpn_proposed_len)) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } return 1; } /* * Process the ALPN extension in a ClientHello. * al: a pointer to the alert value to send in the event of a failure. * returns 1 on success, 0 on error. */ static int tls1_alpn_handle_client_hello_late(SSL *s, int *al) { const unsigned char *selected = NULL; unsigned char selected_len = 0; if (s->ctx->alpn_select_cb != NULL && s->s3->alpn_proposed != NULL) { int r = s->ctx->alpn_select_cb(s, &selected, &selected_len, s->s3->alpn_proposed, s->s3->alpn_proposed_len, s->ctx->alpn_select_cb_arg); if (r == SSL_TLSEXT_ERR_OK) { OPENSSL_free(s->s3->alpn_selected); s->s3->alpn_selected = OPENSSL_memdup(selected, selected_len); if (s->s3->alpn_selected == NULL) { *al = SSL_AD_INTERNAL_ERROR; return 0; } s->s3->alpn_selected_len = selected_len; #ifndef OPENSSL_NO_NEXTPROTONEG /* ALPN takes precedence over NPN. */ s->s3->next_proto_neg_seen = 0; #endif } else { *al = SSL_AD_NO_APPLICATION_PROTOCOL; return 0; } } return 1; } #ifndef OPENSSL_NO_EC /*- * ssl_check_for_safari attempts to fingerprint Safari using OS X * SecureTransport using the TLS extension block in |pkt|. * Safari, since 10.6, sends exactly these extensions, in this order: * SNI, * elliptic_curves * ec_point_formats * * We wish to fingerprint Safari because they broke ECDHE-ECDSA support in 10.8, * but they advertise support. So enabling ECDHE-ECDSA ciphers breaks them. * Sadly we cannot differentiate 10.6, 10.7 and 10.8.4 (which work), from * 10.8..10.8.3 (which don't work). */ static void ssl_check_for_safari(SSL *s, const PACKET *pkt) { unsigned int type; PACKET sni, tmppkt; size_t ext_len; static const unsigned char kSafariExtensionsBlock[] = { 0x00, 0x0a, /* elliptic_curves extension */ 0x00, 0x08, /* 8 bytes */ 0x00, 0x06, /* 6 bytes of curve ids */ 0x00, 0x17, /* P-256 */ 0x00, 0x18, /* P-384 */ 0x00, 0x19, /* P-521 */ 0x00, 0x0b, /* ec_point_formats */ 0x00, 0x02, /* 2 bytes */ 0x01, /* 1 point format */ 0x00, /* uncompressed */ /* The following is only present in TLS 1.2 */ 0x00, 0x0d, /* signature_algorithms */ 0x00, 0x0c, /* 12 bytes */ 0x00, 0x0a, /* 10 bytes */ 0x05, 0x01, /* SHA-384/RSA */ 0x04, 0x01, /* SHA-256/RSA */ 0x02, 0x01, /* SHA-1/RSA */ 0x04, 0x03, /* SHA-256/ECDSA */ 0x02, 0x03, /* SHA-1/ECDSA */ }; /* Length of the common prefix (first two extensions). */ static const size_t kSafariCommonExtensionsLength = 18; tmppkt = *pkt; if (!PACKET_forward(&tmppkt, 2) || !PACKET_get_net_2(&tmppkt, &type) || !PACKET_get_length_prefixed_2(&tmppkt, &sni)) { return; } if (type != TLSEXT_TYPE_server_name) return; ext_len = TLS1_get_client_version(s) >= TLS1_2_VERSION ? sizeof(kSafariExtensionsBlock) : kSafariCommonExtensionsLength; s->s3->is_probably_safari = PACKET_equal(&tmppkt, kSafariExtensionsBlock, ext_len); } #endif /* !OPENSSL_NO_EC */ /* * Parse ClientHello extensions and stash extension info in various parts of * the SSL object. Verify that there are no duplicate extensions. * * Behaviour upon resumption is extension-specific. If the extension has no * effect during resumption, it is parsed (to verify its format) but otherwise * ignored. * * Consumes the entire packet in |pkt|. Returns 1 on success and 0 on failure. * Upon failure, sets |al| to the appropriate alert. */ static int ssl_scan_clienthello_tlsext(SSL *s, PACKET *pkt, int *al) { unsigned int type; int renegotiate_seen = 0; PACKET extensions; *al = SSL_AD_DECODE_ERROR; s->servername_done = 0; s->tlsext_status_type = -1; #ifndef OPENSSL_NO_NEXTPROTONEG s->s3->next_proto_neg_seen = 0; #endif OPENSSL_free(s->s3->alpn_selected); s->s3->alpn_selected = NULL; s->s3->alpn_selected_len = 0; OPENSSL_free(s->s3->alpn_proposed); s->s3->alpn_proposed = NULL; s->s3->alpn_proposed_len = 0; #ifndef OPENSSL_NO_HEARTBEATS s->tlsext_heartbeat &= ~(SSL_DTLSEXT_HB_ENABLED | SSL_DTLSEXT_HB_DONT_SEND_REQUESTS); #endif #ifndef OPENSSL_NO_EC if (s->options & SSL_OP_SAFARI_ECDHE_ECDSA_BUG) ssl_check_for_safari(s, pkt); #endif /* !OPENSSL_NO_EC */ /* Clear any signature algorithms extension received */ OPENSSL_free(s->s3->tmp.peer_sigalgs); s->s3->tmp.peer_sigalgs = NULL; s->tlsext_use_etm = 0; #ifndef OPENSSL_NO_SRP OPENSSL_free(s->srp_ctx.login); s->srp_ctx.login = NULL; #endif s->srtp_profile = NULL; if (PACKET_remaining(pkt) == 0) goto ri_check; if (!PACKET_as_length_prefixed_2(pkt, &extensions)) return 0; if (!tls1_check_duplicate_extensions(&extensions)) return 0; /* * We parse all extensions to ensure the ClientHello is well-formed but, * unless an extension specifies otherwise, we ignore extensions upon * resumption. */ while (PACKET_get_net_2(&extensions, &type)) { PACKET extension; if (!PACKET_get_length_prefixed_2(&extensions, &extension)) return 0; if (s->tlsext_debug_cb) s->tlsext_debug_cb(s, 0, type, PACKET_data(&extension), PACKET_remaining(&extension), s->tlsext_debug_arg); if (type == TLSEXT_TYPE_renegotiate) { if (!ssl_parse_clienthello_renegotiate_ext(s, &extension, al)) return 0; renegotiate_seen = 1; } else if (s->version == SSL3_VERSION) { } /*- * The servername extension is treated as follows: * * - Only the hostname type is supported with a maximum length of 255. * - The servername is rejected if too long or if it contains zeros, * in which case an fatal alert is generated. * - The servername field is maintained together with the session cache. * - When a session is resumed, the servername call back invoked in order * to allow the application to position itself to the right context. * - The servername is acknowledged if it is new for a session or when * it is identical to a previously used for the same session. * Applications can control the behaviour. They can at any time * set a 'desirable' servername for a new SSL object. This can be the * case for example with HTTPS when a Host: header field is received and * a renegotiation is requested. In this case, a possible servername * presented in the new client hello is only acknowledged if it matches * the value of the Host: field. * - Applications must use SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION * if they provide for changing an explicit servername context for the * session, i.e. when the session has been established with a servername * extension. * - On session reconnect, the servername extension may be absent. * */ else if (type == TLSEXT_TYPE_server_name) { unsigned int servname_type; PACKET sni, hostname; if (!PACKET_as_length_prefixed_2(&extension, &sni) /* ServerNameList must be at least 1 byte long. */ || PACKET_remaining(&sni) == 0) { return 0; } /* * Although the server_name extension was intended to be * extensible to new name types, RFC 4366 defined the * syntax inextensibility and OpenSSL 1.0.x parses it as * such. * RFC 6066 corrected the mistake but adding new name types * is nevertheless no longer feasible, so act as if no other * SNI types can exist, to simplify parsing. * * Also note that the RFC permits only one SNI value per type, * i.e., we can only have a single hostname. */ if (!PACKET_get_1(&sni, &servname_type) || servname_type != TLSEXT_NAMETYPE_host_name || !PACKET_as_length_prefixed_2(&sni, &hostname)) { return 0; } if (!s->hit) { if (PACKET_remaining(&hostname) > TLSEXT_MAXLEN_host_name) { *al = TLS1_AD_UNRECOGNIZED_NAME; return 0; } if (PACKET_contains_zero_byte(&hostname)) { *al = TLS1_AD_UNRECOGNIZED_NAME; return 0; } if (!PACKET_strndup(&hostname, &s->session->tlsext_hostname)) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } s->servername_done = 1; } else { /* * TODO(openssl-team): if the SNI doesn't match, we MUST * fall back to a full handshake. */ s->servername_done = s->session->tlsext_hostname && PACKET_equal(&hostname, s->session->tlsext_hostname, strlen(s->session->tlsext_hostname)); } } #ifndef OPENSSL_NO_SRP else if (type == TLSEXT_TYPE_srp) { PACKET srp_I; if (!PACKET_as_length_prefixed_1(&extension, &srp_I)) return 0; if (PACKET_contains_zero_byte(&srp_I)) return 0; /* * TODO(openssl-team): currently, we re-authenticate the user * upon resumption. Instead, we MUST ignore the login. */ if (!PACKET_strndup(&srp_I, &s->srp_ctx.login)) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } } #endif #ifndef OPENSSL_NO_EC else if (type == TLSEXT_TYPE_ec_point_formats) { PACKET ec_point_format_list; if (!PACKET_as_length_prefixed_1(&extension, &ec_point_format_list) || PACKET_remaining(&ec_point_format_list) == 0) { return 0; } if (!s->hit) { if (!PACKET_memdup(&ec_point_format_list, &s->session->tlsext_ecpointformatlist, &s-> session->tlsext_ecpointformatlist_length)) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } } } else if (type == TLSEXT_TYPE_elliptic_curves) { PACKET elliptic_curve_list; /* Each NamedCurve is 2 bytes and we must have at least 1. */ if (!PACKET_as_length_prefixed_2(&extension, &elliptic_curve_list) || PACKET_remaining(&elliptic_curve_list) == 0 || (PACKET_remaining(&elliptic_curve_list) % 2) != 0) { return 0; } if (!s->hit) { if (!PACKET_memdup(&elliptic_curve_list, &s->session->tlsext_ellipticcurvelist, &s-> session->tlsext_ellipticcurvelist_length)) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } } } #endif /* OPENSSL_NO_EC */ else if (type == TLSEXT_TYPE_session_ticket) { if (s->tls_session_ticket_ext_cb && !s->tls_session_ticket_ext_cb(s, PACKET_data(&extension), PACKET_remaining(&extension), s->tls_session_ticket_ext_cb_arg)) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } } else if (type == TLSEXT_TYPE_signature_algorithms) { PACKET supported_sig_algs; if (!PACKET_as_length_prefixed_2(&extension, &supported_sig_algs) || (PACKET_remaining(&supported_sig_algs) % 2) != 0 || PACKET_remaining(&supported_sig_algs) == 0) { return 0; } if (!s->hit) { if (!tls1_save_sigalgs(s, PACKET_data(&supported_sig_algs), PACKET_remaining(&supported_sig_algs))) { return 0; } } } else if (type == TLSEXT_TYPE_status_request) { if (!PACKET_get_1(&extension, (unsigned int *)&s->tlsext_status_type)) { return 0; } #ifndef OPENSSL_NO_OCSP if (s->tlsext_status_type == TLSEXT_STATUSTYPE_ocsp) { const unsigned char *ext_data; PACKET responder_id_list, exts; if (!PACKET_get_length_prefixed_2 (&extension, &responder_id_list)) return 0; /* * We remove any OCSP_RESPIDs from a previous handshake * to prevent unbounded memory growth - CVE-2016-6304 */ sk_OCSP_RESPID_pop_free(s->tlsext_ocsp_ids, OCSP_RESPID_free); if (PACKET_remaining(&responder_id_list) > 0) { s->tlsext_ocsp_ids = sk_OCSP_RESPID_new_null(); if (s->tlsext_ocsp_ids == NULL) { *al = SSL_AD_INTERNAL_ERROR; return 0; } } else { s->tlsext_ocsp_ids = NULL; } while (PACKET_remaining(&responder_id_list) > 0) { OCSP_RESPID *id; PACKET responder_id; const unsigned char *id_data; if (!PACKET_get_length_prefixed_2(&responder_id_list, &responder_id) || PACKET_remaining(&responder_id) == 0) { return 0; } id_data = PACKET_data(&responder_id); id = d2i_OCSP_RESPID(NULL, &id_data, PACKET_remaining(&responder_id)); if (id == NULL) return 0; if (id_data != PACKET_end(&responder_id)) { OCSP_RESPID_free(id); return 0; } if (!sk_OCSP_RESPID_push(s->tlsext_ocsp_ids, id)) { OCSP_RESPID_free(id); *al = SSL_AD_INTERNAL_ERROR; return 0; } } /* Read in request_extensions */ if (!PACKET_as_length_prefixed_2(&extension, &exts)) return 0; if (PACKET_remaining(&exts) > 0) { ext_data = PACKET_data(&exts); sk_X509_EXTENSION_pop_free(s->tlsext_ocsp_exts, X509_EXTENSION_free); s->tlsext_ocsp_exts = d2i_X509_EXTENSIONS(NULL, &ext_data, PACKET_remaining(&exts)); if (s->tlsext_ocsp_exts == NULL || ext_data != PACKET_end(&exts)) { return 0; } } } else #endif { /* * We don't know what to do with any other type so ignore it. */ s->tlsext_status_type = -1; } } #ifndef OPENSSL_NO_HEARTBEATS else if (SSL_IS_DTLS(s) && type == TLSEXT_TYPE_heartbeat) { unsigned int hbtype; if (!PACKET_get_1(&extension, &hbtype) || PACKET_remaining(&extension)) { *al = SSL_AD_DECODE_ERROR; return 0; } switch (hbtype) { case 0x01: /* Client allows us to send HB requests */ s->tlsext_heartbeat |= SSL_DTLSEXT_HB_ENABLED; break; case 0x02: /* Client doesn't accept HB requests */ s->tlsext_heartbeat |= SSL_DTLSEXT_HB_ENABLED; s->tlsext_heartbeat |= SSL_DTLSEXT_HB_DONT_SEND_REQUESTS; break; default: *al = SSL_AD_ILLEGAL_PARAMETER; return 0; } } #endif #ifndef OPENSSL_NO_NEXTPROTONEG else if (type == TLSEXT_TYPE_next_proto_neg && s->s3->tmp.finish_md_len == 0) { /*- * We shouldn't accept this extension on a * renegotiation. * * s->new_session will be set on renegotiation, but we * probably shouldn't rely that it couldn't be set on * the initial renegotiation too in certain cases (when * there's some other reason to disallow resuming an * earlier session -- the current code won't be doing * anything like that, but this might change). * * A valid sign that there's been a previous handshake * in this connection is if s->s3->tmp.finish_md_len > * 0. (We are talking about a check that will happen * in the Hello protocol round, well before a new * Finished message could have been computed.) */ s->s3->next_proto_neg_seen = 1; } #endif else if (type == TLSEXT_TYPE_application_layer_protocol_negotiation && s->s3->tmp.finish_md_len == 0) { if (!tls1_alpn_handle_client_hello(s, &extension, al)) return 0; } /* session ticket processed earlier */ #ifndef OPENSSL_NO_SRTP else if (SSL_IS_DTLS(s) && SSL_get_srtp_profiles(s) && type == TLSEXT_TYPE_use_srtp) { if (ssl_parse_clienthello_use_srtp_ext(s, &extension, al)) return 0; } #endif else if (type == TLSEXT_TYPE_encrypt_then_mac) s->tlsext_use_etm = 1; /* * Note: extended master secret extension handled in * tls_check_serverhello_tlsext_early() */ /* * If this ClientHello extension was unhandled and this is a * nonresumed connection, check whether the extension is a custom * TLS Extension (has a custom_srv_ext_record), and if so call the * callback and record the extension number so that an appropriate * ServerHello may be later returned. */ else if (!s->hit) { if (custom_ext_parse(s, 1, type, PACKET_data(&extension), PACKET_remaining(&extension), al) <= 0) return 0; } } if (PACKET_remaining(pkt) != 0) { /* * tls1_check_duplicate_extensions should ensure this never happens. */ *al = SSL_AD_INTERNAL_ERROR; return 0; } ri_check: /* Need RI if renegotiating */ if (!renegotiate_seen && s->renegotiate && !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) { *al = SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL_SCAN_CLIENTHELLO_TLSEXT, SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED); return 0; } /* * This function currently has no state to clean up, so it returns directly. * If parsing fails at any point, the function returns early. * The SSL object may be left with partial data from extensions, but it must * then no longer be used, and clearing it up will free the leftovers. */ return 1; } int ssl_parse_clienthello_tlsext(SSL *s, PACKET *pkt) { int al = -1; custom_ext_init(&s->cert->srv_ext); if (ssl_scan_clienthello_tlsext(s, pkt, &al) <= 0) { ssl3_send_alert(s, SSL3_AL_FATAL, al); return 0; } if (ssl_check_clienthello_tlsext_early(s) <= 0) { SSLerr(SSL_F_SSL_PARSE_CLIENTHELLO_TLSEXT, SSL_R_CLIENTHELLO_TLSEXT); return 0; } return 1; } #ifndef OPENSSL_NO_NEXTPROTONEG /* * ssl_next_proto_validate validates a Next Protocol Negotiation block. No * elements of zero length are allowed and the set of elements must exactly * fill the length of the block. */ static char ssl_next_proto_validate(PACKET *pkt) { PACKET tmp_protocol; while (PACKET_remaining(pkt)) { if (!PACKET_get_length_prefixed_1(pkt, &tmp_protocol) || PACKET_remaining(&tmp_protocol) == 0) return 0; } return 1; } #endif static int ssl_scan_serverhello_tlsext(SSL *s, PACKET *pkt, int *al) { unsigned int length, type, size; int tlsext_servername = 0; int renegotiate_seen = 0; #ifndef OPENSSL_NO_NEXTPROTONEG s->s3->next_proto_neg_seen = 0; #endif s->tlsext_ticket_expected = 0; OPENSSL_free(s->s3->alpn_selected); s->s3->alpn_selected = NULL; #ifndef OPENSSL_NO_HEARTBEATS s->tlsext_heartbeat &= ~(SSL_DTLSEXT_HB_ENABLED | SSL_DTLSEXT_HB_DONT_SEND_REQUESTS); #endif s->tlsext_use_etm = 0; s->s3->flags &= ~TLS1_FLAGS_RECEIVED_EXTMS; if (!PACKET_get_net_2(pkt, &length)) goto ri_check; if (PACKET_remaining(pkt) != length) { *al = SSL_AD_DECODE_ERROR; return 0; } if (!tls1_check_duplicate_extensions(pkt)) { *al = SSL_AD_DECODE_ERROR; return 0; } while (PACKET_get_net_2(pkt, &type) && PACKET_get_net_2(pkt, &size)) { const unsigned char *data; PACKET spkt; if (!PACKET_get_sub_packet(pkt, &spkt, size) || !PACKET_peek_bytes(&spkt, &data, size)) goto ri_check; if (s->tlsext_debug_cb) s->tlsext_debug_cb(s, 1, type, data, size, s->tlsext_debug_arg); if (type == TLSEXT_TYPE_renegotiate) { if (!ssl_parse_serverhello_renegotiate_ext(s, &spkt, al)) return 0; renegotiate_seen = 1; } else if (s->version == SSL3_VERSION) { } else if (type == TLSEXT_TYPE_server_name) { if (s->tlsext_hostname == NULL || size > 0) { *al = TLS1_AD_UNRECOGNIZED_NAME; return 0; } tlsext_servername = 1; } #ifndef OPENSSL_NO_EC else if (type == TLSEXT_TYPE_ec_point_formats) { unsigned int ecpointformatlist_length; if (!PACKET_get_1(&spkt, &ecpointformatlist_length) || ecpointformatlist_length != size - 1) { *al = TLS1_AD_DECODE_ERROR; return 0; } if (!s->hit) { s->session->tlsext_ecpointformatlist_length = 0; OPENSSL_free(s->session->tlsext_ecpointformatlist); if ((s->session->tlsext_ecpointformatlist = OPENSSL_malloc(ecpointformatlist_length)) == NULL) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } s->session->tlsext_ecpointformatlist_length = ecpointformatlist_length; if (!PACKET_copy_bytes(&spkt, s->session->tlsext_ecpointformatlist, ecpointformatlist_length)) { *al = TLS1_AD_DECODE_ERROR; return 0; } } } #endif /* OPENSSL_NO_EC */ else if (type == TLSEXT_TYPE_session_ticket) { if (s->tls_session_ticket_ext_cb && !s->tls_session_ticket_ext_cb(s, data, size, s->tls_session_ticket_ext_cb_arg)) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } if (!tls_use_ticket(s) || (size > 0)) { *al = TLS1_AD_UNSUPPORTED_EXTENSION; return 0; } s->tlsext_ticket_expected = 1; } else if (type == TLSEXT_TYPE_status_request) { /* * MUST be empty and only sent if we've requested a status * request message. */ if ((s->tlsext_status_type == -1) || (size > 0)) { *al = TLS1_AD_UNSUPPORTED_EXTENSION; return 0; } /* Set flag to expect CertificateStatus message */ s->tlsext_status_expected = 1; } #ifndef OPENSSL_NO_CT /* * Only take it if we asked for it - i.e if there is no CT validation * callback set, then a custom extension MAY be processing it, so we * need to let control continue to flow to that. */ else if (type == TLSEXT_TYPE_signed_certificate_timestamp && s->ct_validation_callback != NULL) { /* Simply copy it off for later processing */ if (s->tlsext_scts != NULL) { OPENSSL_free(s->tlsext_scts); s->tlsext_scts = NULL; } s->tlsext_scts_len = size; if (size > 0) { s->tlsext_scts = OPENSSL_malloc(size); if (s->tlsext_scts == NULL) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } memcpy(s->tlsext_scts, data, size); } } #endif #ifndef OPENSSL_NO_NEXTPROTONEG else if (type == TLSEXT_TYPE_next_proto_neg && s->s3->tmp.finish_md_len == 0) { unsigned char *selected; unsigned char selected_len; /* We must have requested it. */ if (s->ctx->next_proto_select_cb == NULL) { *al = TLS1_AD_UNSUPPORTED_EXTENSION; return 0; } /* The data must be valid */ if (!ssl_next_proto_validate(&spkt)) { *al = TLS1_AD_DECODE_ERROR; return 0; } if (s->ctx->next_proto_select_cb(s, &selected, &selected_len, data, size, s-> ctx->next_proto_select_cb_arg) != SSL_TLSEXT_ERR_OK) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } /* * Could be non-NULL if server has sent multiple NPN extensions in * a single Serverhello */ OPENSSL_free(s->next_proto_negotiated); s->next_proto_negotiated = OPENSSL_malloc(selected_len); if (s->next_proto_negotiated == NULL) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } memcpy(s->next_proto_negotiated, selected, selected_len); s->next_proto_negotiated_len = selected_len; s->s3->next_proto_neg_seen = 1; } #endif else if (type == TLSEXT_TYPE_application_layer_protocol_negotiation) { unsigned len; /* We must have requested it. */ if (!s->s3->alpn_sent) { *al = TLS1_AD_UNSUPPORTED_EXTENSION; return 0; } /*- * The extension data consists of: * uint16 list_length * uint8 proto_length; * uint8 proto[proto_length]; */ if (!PACKET_get_net_2(&spkt, &len) || PACKET_remaining(&spkt) != len || !PACKET_get_1(&spkt, &len) || PACKET_remaining(&spkt) != len) { *al = TLS1_AD_DECODE_ERROR; return 0; } OPENSSL_free(s->s3->alpn_selected); s->s3->alpn_selected = OPENSSL_malloc(len); if (s->s3->alpn_selected == NULL) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } if (!PACKET_copy_bytes(&spkt, s->s3->alpn_selected, len)) { *al = TLS1_AD_DECODE_ERROR; return 0; } s->s3->alpn_selected_len = len; } #ifndef OPENSSL_NO_HEARTBEATS else if (SSL_IS_DTLS(s) && type == TLSEXT_TYPE_heartbeat) { unsigned int hbtype; if (!PACKET_get_1(&spkt, &hbtype)) { *al = SSL_AD_DECODE_ERROR; return 0; } switch (hbtype) { case 0x01: /* Server allows us to send HB requests */ s->tlsext_heartbeat |= SSL_DTLSEXT_HB_ENABLED; break; case 0x02: /* Server doesn't accept HB requests */ s->tlsext_heartbeat |= SSL_DTLSEXT_HB_ENABLED; s->tlsext_heartbeat |= SSL_DTLSEXT_HB_DONT_SEND_REQUESTS; break; default: *al = SSL_AD_ILLEGAL_PARAMETER; return 0; } } #endif #ifndef OPENSSL_NO_SRTP else if (SSL_IS_DTLS(s) && type == TLSEXT_TYPE_use_srtp) { if (ssl_parse_serverhello_use_srtp_ext(s, &spkt, al)) return 0; } #endif else if (type == TLSEXT_TYPE_encrypt_then_mac) { /* Ignore if inappropriate ciphersuite */ if (s->s3->tmp.new_cipher->algorithm_mac != SSL_AEAD && s->s3->tmp.new_cipher->algorithm_enc != SSL_RC4) s->tlsext_use_etm = 1; } else if (type == TLSEXT_TYPE_extended_master_secret) { s->s3->flags |= TLS1_FLAGS_RECEIVED_EXTMS; if (!s->hit) s->session->flags |= SSL_SESS_FLAG_EXTMS; } /* * If this extension type was not otherwise handled, but matches a * custom_cli_ext_record, then send it to the c callback */ else if (custom_ext_parse(s, 0, type, data, size, al) <= 0) return 0; } if (PACKET_remaining(pkt) != 0) { *al = SSL_AD_DECODE_ERROR; return 0; } if (!s->hit && tlsext_servername == 1) { if (s->tlsext_hostname) { if (s->session->tlsext_hostname == NULL) { s->session->tlsext_hostname = OPENSSL_strdup(s->tlsext_hostname); if (!s->session->tlsext_hostname) { *al = SSL_AD_UNRECOGNIZED_NAME; return 0; } } else { *al = SSL_AD_DECODE_ERROR; return 0; } } } ri_check: /* * Determine if we need to see RI. Strictly speaking if we want to avoid * an attack we should *always* see RI even on initial server hello * because the client doesn't see any renegotiation during an attack. * However this would mean we could not connect to any server which * doesn't support RI so for the immediate future tolerate RI absence */ if (!renegotiate_seen && !(s->options & SSL_OP_LEGACY_SERVER_CONNECT) && !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) { *al = SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL_SCAN_SERVERHELLO_TLSEXT, SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED); return 0; } if (s->hit) { /* * Check extended master secret extension is consistent with * original session. */ if (!(s->s3->flags & TLS1_FLAGS_RECEIVED_EXTMS) != !(s->session->flags & SSL_SESS_FLAG_EXTMS)) { *al = SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL_SCAN_SERVERHELLO_TLSEXT, SSL_R_INCONSISTENT_EXTMS); return 0; } } return 1; } int ssl_prepare_clienthello_tlsext(SSL *s) { s->s3->alpn_sent = 0; return 1; } int ssl_prepare_serverhello_tlsext(SSL *s) { return 1; } static int ssl_check_clienthello_tlsext_early(SSL *s) { int ret = SSL_TLSEXT_ERR_NOACK; int al = SSL_AD_UNRECOGNIZED_NAME; #ifndef OPENSSL_NO_EC /* * The handling of the ECPointFormats extension is done elsewhere, namely * in ssl3_choose_cipher in s3_lib.c. */ /* * The handling of the EllipticCurves extension is done elsewhere, namely * in ssl3_choose_cipher in s3_lib.c. */ #endif if (s->ctx != NULL && s->ctx->tlsext_servername_callback != 0) ret = s->ctx->tlsext_servername_callback(s, &al, s->ctx->tlsext_servername_arg); else if (s->session_ctx != NULL && s->session_ctx->tlsext_servername_callback != 0) ret = s->session_ctx->tlsext_servername_callback(s, &al, s-> session_ctx->tlsext_servername_arg); switch (ret) { case SSL_TLSEXT_ERR_ALERT_FATAL: ssl3_send_alert(s, SSL3_AL_FATAL, al); return -1; case SSL_TLSEXT_ERR_ALERT_WARNING: ssl3_send_alert(s, SSL3_AL_WARNING, al); return 1; case SSL_TLSEXT_ERR_NOACK: s->servername_done = 0; default: return 1; } } /* Initialise digests to default values */ void ssl_set_default_md(SSL *s) { const EVP_MD **pmd = s->s3->tmp.md; #ifndef OPENSSL_NO_DSA pmd[SSL_PKEY_DSA_SIGN] = ssl_md(SSL_MD_SHA1_IDX); #endif #ifndef OPENSSL_NO_RSA if (SSL_USE_SIGALGS(s)) pmd[SSL_PKEY_RSA_SIGN] = ssl_md(SSL_MD_SHA1_IDX); else pmd[SSL_PKEY_RSA_SIGN] = ssl_md(SSL_MD_MD5_SHA1_IDX); pmd[SSL_PKEY_RSA_ENC] = pmd[SSL_PKEY_RSA_SIGN]; #endif #ifndef OPENSSL_NO_EC pmd[SSL_PKEY_ECC] = ssl_md(SSL_MD_SHA1_IDX); #endif #ifndef OPENSSL_NO_GOST pmd[SSL_PKEY_GOST01] = ssl_md(SSL_MD_GOST94_IDX); pmd[SSL_PKEY_GOST12_256] = ssl_md(SSL_MD_GOST12_256_IDX); pmd[SSL_PKEY_GOST12_512] = ssl_md(SSL_MD_GOST12_512_IDX); #endif } int tls1_set_server_sigalgs(SSL *s) { int al; size_t i; /* Clear any shared signature algorithms */ OPENSSL_free(s->cert->shared_sigalgs); s->cert->shared_sigalgs = NULL; s->cert->shared_sigalgslen = 0; /* Clear certificate digests and validity flags */ for (i = 0; i < SSL_PKEY_NUM; i++) { s->s3->tmp.md[i] = NULL; s->s3->tmp.valid_flags[i] = 0; } /* If sigalgs received process it. */ if (s->s3->tmp.peer_sigalgs) { if (!tls1_process_sigalgs(s)) { SSLerr(SSL_F_TLS1_SET_SERVER_SIGALGS, ERR_R_MALLOC_FAILURE); al = SSL_AD_INTERNAL_ERROR; goto err; } /* Fatal error is no shared signature algorithms */ if (!s->cert->shared_sigalgs) { SSLerr(SSL_F_TLS1_SET_SERVER_SIGALGS, SSL_R_NO_SHARED_SIGNATURE_ALGORITHMS); al = SSL_AD_ILLEGAL_PARAMETER; goto err; } } else { ssl_set_default_md(s); } return 1; err: ssl3_send_alert(s, SSL3_AL_FATAL, al); return 0; } /* * Upon success, returns 1. * Upon failure, returns 0 and sets |al| to the appropriate fatal alert. */ int ssl_check_clienthello_tlsext_late(SSL *s, int *al) { s->tlsext_status_expected = 0; /* * If status request then ask callback what to do. Note: this must be * called after servername callbacks in case the certificate has changed, * and must be called after the cipher has been chosen because this may * influence which certificate is sent */ if ((s->tlsext_status_type != -1) && s->ctx && s->ctx->tlsext_status_cb) { int ret; CERT_PKEY *certpkey; certpkey = ssl_get_server_send_pkey(s); /* If no certificate can't return certificate status */ if (certpkey != NULL) { /* * Set current certificate to one we will use so SSL_get_certificate * et al can pick it up. */ s->cert->key = certpkey; ret = s->ctx->tlsext_status_cb(s, s->ctx->tlsext_status_arg); switch (ret) { /* We don't want to send a status request response */ case SSL_TLSEXT_ERR_NOACK: s->tlsext_status_expected = 0; break; /* status request response should be sent */ case SSL_TLSEXT_ERR_OK: if (s->tlsext_ocsp_resp) s->tlsext_status_expected = 1; break; /* something bad happened */ case SSL_TLSEXT_ERR_ALERT_FATAL: default: *al = SSL_AD_INTERNAL_ERROR; return 0; } } } if (!tls1_alpn_handle_client_hello_late(s, al)) { return 0; } return 1; } int ssl_check_serverhello_tlsext(SSL *s) { int ret = SSL_TLSEXT_ERR_NOACK; int al = SSL_AD_UNRECOGNIZED_NAME; #ifndef OPENSSL_NO_EC /* * If we are client and using an elliptic curve cryptography cipher * suite, then if server returns an EC point formats lists extension it * must contain uncompressed. */ unsigned long alg_k = s->s3->tmp.new_cipher->algorithm_mkey; unsigned long alg_a = s->s3->tmp.new_cipher->algorithm_auth; if ((s->tlsext_ecpointformatlist != NULL) && (s->tlsext_ecpointformatlist_length > 0) && (s->session->tlsext_ecpointformatlist != NULL) && (s->session->tlsext_ecpointformatlist_length > 0) && ((alg_k & SSL_kECDHE) || (alg_a & SSL_aECDSA))) { /* we are using an ECC cipher */ size_t i; unsigned char *list; int found_uncompressed = 0; list = s->session->tlsext_ecpointformatlist; for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++) { if (*(list++) == TLSEXT_ECPOINTFORMAT_uncompressed) { found_uncompressed = 1; break; } } if (!found_uncompressed) { SSLerr(SSL_F_SSL_CHECK_SERVERHELLO_TLSEXT, SSL_R_TLS_INVALID_ECPOINTFORMAT_LIST); return -1; } } ret = SSL_TLSEXT_ERR_OK; #endif /* OPENSSL_NO_EC */ if (s->ctx != NULL && s->ctx->tlsext_servername_callback != 0) ret = s->ctx->tlsext_servername_callback(s, &al, s->ctx->tlsext_servername_arg); else if (s->session_ctx != NULL && s->session_ctx->tlsext_servername_callback != 0) ret = s->session_ctx->tlsext_servername_callback(s, &al, s-> session_ctx->tlsext_servername_arg); /* * Ensure we get sensible values passed to tlsext_status_cb in the event * that we don't receive a status message */ OPENSSL_free(s->tlsext_ocsp_resp); s->tlsext_ocsp_resp = NULL; s->tlsext_ocsp_resplen = -1; switch (ret) { case SSL_TLSEXT_ERR_ALERT_FATAL: ssl3_send_alert(s, SSL3_AL_FATAL, al); return -1; case SSL_TLSEXT_ERR_ALERT_WARNING: ssl3_send_alert(s, SSL3_AL_WARNING, al); return 1; case SSL_TLSEXT_ERR_NOACK: s->servername_done = 0; default: return 1; } } int ssl_parse_serverhello_tlsext(SSL *s, PACKET *pkt) { int al = -1; if (s->version < SSL3_VERSION) return 1; if (ssl_scan_serverhello_tlsext(s, pkt, &al) <= 0) { ssl3_send_alert(s, SSL3_AL_FATAL, al); return 0; } if (ssl_check_serverhello_tlsext(s) <= 0) { SSLerr(SSL_F_SSL_PARSE_SERVERHELLO_TLSEXT, SSL_R_SERVERHELLO_TLSEXT); return 0; } return 1; } /*- * Since the server cache lookup is done early on in the processing of the * ClientHello and other operations depend on the result some extensions * need to be handled at the same time. * * Two extensions are currently handled, session ticket and extended master * secret. * * session_id: ClientHello session ID. * ext: ClientHello extensions (including length prefix) * ret: (output) on return, if a ticket was decrypted, then this is set to * point to the resulting session. * * If s->tls_session_secret_cb is set then we are expecting a pre-shared key * ciphersuite, in which case we have no use for session tickets and one will * never be decrypted, nor will s->tlsext_ticket_expected be set to 1. * * Returns: * -1: fatal error, either from parsing or decrypting the ticket. * 0: no ticket was found (or was ignored, based on settings). * 1: a zero length extension was found, indicating that the client supports * session tickets but doesn't currently have one to offer. * 2: either s->tls_session_secret_cb was set, or a ticket was offered but * couldn't be decrypted because of a non-fatal error. * 3: a ticket was successfully decrypted and *ret was set. * * Side effects: * Sets s->tlsext_ticket_expected to 1 if the server will have to issue * a new session ticket to the client because the client indicated support * (and s->tls_session_secret_cb is NULL) but the client either doesn't have * a session ticket or we couldn't use the one it gave us, or if * s->ctx->tlsext_ticket_key_cb asked to renew the client's ticket. * Otherwise, s->tlsext_ticket_expected is set to 0. * * For extended master secret flag is set if the extension is present. * */ int tls_check_serverhello_tlsext_early(SSL *s, const PACKET *ext, const PACKET *session_id, SSL_SESSION **ret) { unsigned int i; PACKET local_ext = *ext; int retv = -1; int have_ticket = 0; int use_ticket = tls_use_ticket(s); *ret = NULL; s->tlsext_ticket_expected = 0; s->s3->flags &= ~TLS1_FLAGS_RECEIVED_EXTMS; /* * If tickets disabled behave as if no ticket present to permit stateful * resumption. */ if ((s->version <= SSL3_VERSION)) return 0; if (!PACKET_get_net_2(&local_ext, &i)) { retv = 0; goto end; } while (PACKET_remaining(&local_ext) >= 4) { unsigned int type, size; if (!PACKET_get_net_2(&local_ext, &type) || !PACKET_get_net_2(&local_ext, &size)) { /* Shouldn't ever happen */ retv = -1; goto end; } if (PACKET_remaining(&local_ext) < size) { retv = 0; goto end; } if (type == TLSEXT_TYPE_session_ticket && use_ticket) { int r; const unsigned char *etick; /* Duplicate extension */ if (have_ticket != 0) { retv = -1; goto end; } have_ticket = 1; if (size == 0) { /* * The client will accept a ticket but doesn't currently have * one. */ s->tlsext_ticket_expected = 1; retv = 1; continue; } if (s->tls_session_secret_cb) { /* * Indicate that the ticket couldn't be decrypted rather than * generating the session from ticket now, trigger * abbreviated handshake based on external mechanism to * calculate the master secret later. */ retv = 2; continue; } if (!PACKET_get_bytes(&local_ext, &etick, size)) { /* Shouldn't ever happen */ retv = -1; goto end; } r = tls_decrypt_ticket(s, etick, size, PACKET_data(session_id), PACKET_remaining(session_id), ret); switch (r) { case 2: /* ticket couldn't be decrypted */ s->tlsext_ticket_expected = 1; retv = 2; break; case 3: /* ticket was decrypted */ retv = r; break; case 4: /* ticket decrypted but need to renew */ s->tlsext_ticket_expected = 1; retv = 3; break; default: /* fatal error */ retv = -1; break; } continue; } else { if (type == TLSEXT_TYPE_extended_master_secret) s->s3->flags |= TLS1_FLAGS_RECEIVED_EXTMS; if (!PACKET_forward(&local_ext, size)) { retv = -1; goto end; } } } if (have_ticket == 0) retv = 0; end: return retv; } /*- * tls_decrypt_ticket attempts to decrypt a session ticket. * * etick: points to the body of the session ticket extension. * eticklen: the length of the session tickets extension. * sess_id: points at the session ID. * sesslen: the length of the session ID. * psess: (output) on return, if a ticket was decrypted, then this is set to * point to the resulting session. * * Returns: * -2: fatal error, malloc failure. * -1: fatal error, either from parsing or decrypting the ticket. * 2: the ticket couldn't be decrypted. * 3: a ticket was successfully decrypted and *psess was set. * 4: same as 3, but the ticket needs to be renewed. */ static int tls_decrypt_ticket(SSL *s, const unsigned char *etick, int eticklen, const unsigned char *sess_id, int sesslen, SSL_SESSION **psess) { SSL_SESSION *sess; unsigned char *sdec; const unsigned char *p; int slen, mlen, renew_ticket = 0, ret = -1; unsigned char tick_hmac[EVP_MAX_MD_SIZE]; HMAC_CTX *hctx = NULL; EVP_CIPHER_CTX *ctx; SSL_CTX *tctx = s->session_ctx; /* Initialize session ticket encryption and HMAC contexts */ hctx = HMAC_CTX_new(); if (hctx == NULL) return -2; ctx = EVP_CIPHER_CTX_new(); if (ctx == NULL) { ret = -2; goto err; } if (tctx->tlsext_ticket_key_cb) { unsigned char *nctick = (unsigned char *)etick; int rv = tctx->tlsext_ticket_key_cb(s, nctick, nctick + 16, ctx, hctx, 0); if (rv < 0) goto err; if (rv == 0) { ret = 2; goto err; } if (rv == 2) renew_ticket = 1; } else { /* Check key name matches */ if (memcmp(etick, tctx->tlsext_tick_key_name, sizeof(tctx->tlsext_tick_key_name)) != 0) { ret = 2; goto err; } if (HMAC_Init_ex(hctx, tctx->tlsext_tick_hmac_key, sizeof(tctx->tlsext_tick_hmac_key), EVP_sha256(), NULL) <= 0 || EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, tctx->tlsext_tick_aes_key, etick + sizeof(tctx->tlsext_tick_key_name)) <= 0) { goto err; } } /* * Attempt to process session ticket, first conduct sanity and integrity * checks on ticket. */ mlen = HMAC_size(hctx); if (mlen < 0) { goto err; } /* Sanity check ticket length: must exceed keyname + IV + HMAC */ if (eticklen <= TLSEXT_KEYNAME_LENGTH + EVP_CIPHER_CTX_iv_length(ctx) + mlen) { ret = 2; goto err; } eticklen -= mlen; /* Check HMAC of encrypted ticket */ if (HMAC_Update(hctx, etick, eticklen) <= 0 || HMAC_Final(hctx, tick_hmac, NULL) <= 0) { goto err; } HMAC_CTX_free(hctx); if (CRYPTO_memcmp(tick_hmac, etick + eticklen, mlen)) { EVP_CIPHER_CTX_free(ctx); return 2; } /* Attempt to decrypt session data */ /* Move p after IV to start of encrypted ticket, update length */ p = etick + TLSEXT_KEYNAME_LENGTH + EVP_CIPHER_CTX_iv_length(ctx); eticklen -= TLSEXT_KEYNAME_LENGTH + EVP_CIPHER_CTX_iv_length(ctx); sdec = OPENSSL_malloc(eticklen); if (sdec == NULL || EVP_DecryptUpdate(ctx, sdec, &slen, p, eticklen) <= 0) { EVP_CIPHER_CTX_free(ctx); OPENSSL_free(sdec); return -1; } if (EVP_DecryptFinal(ctx, sdec + slen, &mlen) <= 0) { EVP_CIPHER_CTX_free(ctx); OPENSSL_free(sdec); return 2; } slen += mlen; EVP_CIPHER_CTX_free(ctx); ctx = NULL; p = sdec; sess = d2i_SSL_SESSION(NULL, &p, slen); OPENSSL_free(sdec); if (sess) { /* * The session ID, if non-empty, is used by some clients to detect * that the ticket has been accepted. So we copy it to the session * structure. If it is empty set length to zero as required by * standard. */ if (sesslen) memcpy(sess->session_id, sess_id, sesslen); sess->session_id_length = sesslen; *psess = sess; if (renew_ticket) return 4; else return 3; } ERR_clear_error(); /* * For session parse failure, indicate that we need to send a new ticket. */ return 2; err: EVP_CIPHER_CTX_free(ctx); HMAC_CTX_free(hctx); return ret; } /* Tables to translate from NIDs to TLS v1.2 ids */ typedef struct { int nid; int id; } tls12_lookup; static const tls12_lookup tls12_md[] = { {NID_md5, TLSEXT_hash_md5}, {NID_sha1, TLSEXT_hash_sha1}, {NID_sha224, TLSEXT_hash_sha224}, {NID_sha256, TLSEXT_hash_sha256}, {NID_sha384, TLSEXT_hash_sha384}, {NID_sha512, TLSEXT_hash_sha512}, {NID_id_GostR3411_94, TLSEXT_hash_gostr3411}, {NID_id_GostR3411_2012_256, TLSEXT_hash_gostr34112012_256}, {NID_id_GostR3411_2012_512, TLSEXT_hash_gostr34112012_512}, }; static const tls12_lookup tls12_sig[] = { {EVP_PKEY_RSA, TLSEXT_signature_rsa}, {EVP_PKEY_DSA, TLSEXT_signature_dsa}, {EVP_PKEY_EC, TLSEXT_signature_ecdsa}, {NID_id_GostR3410_2001, TLSEXT_signature_gostr34102001}, {NID_id_GostR3410_2012_256, TLSEXT_signature_gostr34102012_256}, {NID_id_GostR3410_2012_512, TLSEXT_signature_gostr34102012_512} }; static int tls12_find_id(int nid, const tls12_lookup *table, size_t tlen) { size_t i; for (i = 0; i < tlen; i++) { if (table[i].nid == nid) return table[i].id; } return -1; } static int tls12_find_nid(int id, const tls12_lookup *table, size_t tlen) { size_t i; for (i = 0; i < tlen; i++) { if ((table[i].id) == id) return table[i].nid; } return NID_undef; } int tls12_get_sigandhash(unsigned char *p, const EVP_PKEY *pk, const EVP_MD *md) { int sig_id, md_id; if (!md) return 0; md_id = tls12_find_id(EVP_MD_type(md), tls12_md, OSSL_NELEM(tls12_md)); if (md_id == -1) return 0; sig_id = tls12_get_sigid(pk); if (sig_id == -1) return 0; p[0] = (unsigned char)md_id; p[1] = (unsigned char)sig_id; return 1; } int tls12_get_sigid(const EVP_PKEY *pk) { return tls12_find_id(EVP_PKEY_id(pk), tls12_sig, OSSL_NELEM(tls12_sig)); } typedef struct { int nid; int secbits; int md_idx; unsigned char tlsext_hash; } tls12_hash_info; static const tls12_hash_info tls12_md_info[] = { {NID_md5, 64, SSL_MD_MD5_IDX, TLSEXT_hash_md5}, {NID_sha1, 80, SSL_MD_SHA1_IDX, TLSEXT_hash_sha1}, {NID_sha224, 112, SSL_MD_SHA224_IDX, TLSEXT_hash_sha224}, {NID_sha256, 128, SSL_MD_SHA256_IDX, TLSEXT_hash_sha256}, {NID_sha384, 192, SSL_MD_SHA384_IDX, TLSEXT_hash_sha384}, {NID_sha512, 256, SSL_MD_SHA512_IDX, TLSEXT_hash_sha512}, {NID_id_GostR3411_94, 128, SSL_MD_GOST94_IDX, TLSEXT_hash_gostr3411}, {NID_id_GostR3411_2012_256, 128, SSL_MD_GOST12_256_IDX, TLSEXT_hash_gostr34112012_256}, {NID_id_GostR3411_2012_512, 256, SSL_MD_GOST12_512_IDX, TLSEXT_hash_gostr34112012_512}, }; static const tls12_hash_info *tls12_get_hash_info(unsigned char hash_alg) { unsigned int i; if (hash_alg == 0) return NULL; for (i = 0; i < OSSL_NELEM(tls12_md_info); i++) { if (tls12_md_info[i].tlsext_hash == hash_alg) return tls12_md_info + i; } return NULL; } const EVP_MD *tls12_get_hash(unsigned char hash_alg) { const tls12_hash_info *inf; if (hash_alg == TLSEXT_hash_md5 && FIPS_mode()) return NULL; inf = tls12_get_hash_info(hash_alg); if (!inf) return NULL; return ssl_md(inf->md_idx); } static int tls12_get_pkey_idx(unsigned char sig_alg) { switch (sig_alg) { #ifndef OPENSSL_NO_RSA case TLSEXT_signature_rsa: return SSL_PKEY_RSA_SIGN; #endif #ifndef OPENSSL_NO_DSA case TLSEXT_signature_dsa: return SSL_PKEY_DSA_SIGN; #endif #ifndef OPENSSL_NO_EC case TLSEXT_signature_ecdsa: return SSL_PKEY_ECC; #endif #ifndef OPENSSL_NO_GOST case TLSEXT_signature_gostr34102001: return SSL_PKEY_GOST01; case TLSEXT_signature_gostr34102012_256: return SSL_PKEY_GOST12_256; case TLSEXT_signature_gostr34102012_512: return SSL_PKEY_GOST12_512; #endif } return -1; } /* Convert TLS 1.2 signature algorithm extension values into NIDs */ static void tls1_lookup_sigalg(int *phash_nid, int *psign_nid, int *psignhash_nid, const unsigned char *data) { int sign_nid = NID_undef, hash_nid = NID_undef; if (!phash_nid && !psign_nid && !psignhash_nid) return; if (phash_nid || psignhash_nid) { hash_nid = tls12_find_nid(data[0], tls12_md, OSSL_NELEM(tls12_md)); if (phash_nid) *phash_nid = hash_nid; } if (psign_nid || psignhash_nid) { sign_nid = tls12_find_nid(data[1], tls12_sig, OSSL_NELEM(tls12_sig)); if (psign_nid) *psign_nid = sign_nid; } if (psignhash_nid) { if (sign_nid == NID_undef || hash_nid == NID_undef || OBJ_find_sigid_by_algs(psignhash_nid, hash_nid, sign_nid) <= 0) *psignhash_nid = NID_undef; } } /* Check to see if a signature algorithm is allowed */ static int tls12_sigalg_allowed(SSL *s, int op, const unsigned char *ptmp) { /* See if we have an entry in the hash table and it is enabled */ const tls12_hash_info *hinf = tls12_get_hash_info(ptmp[0]); if (hinf == NULL || ssl_md(hinf->md_idx) == NULL) return 0; /* See if public key algorithm allowed */ if (tls12_get_pkey_idx(ptmp[1]) == -1) return 0; /* Finally see if security callback allows it */ return ssl_security(s, op, hinf->secbits, hinf->nid, (void *)ptmp); } /* * Get a mask of disabled public key algorithms based on supported signature * algorithms. For example if no signature algorithm supports RSA then RSA is * disabled. */ void ssl_set_sig_mask(uint32_t *pmask_a, SSL *s, int op) { const unsigned char *sigalgs; size_t i, sigalgslen; int have_rsa = 0, have_dsa = 0, have_ecdsa = 0; /* * Now go through all signature algorithms seeing if we support any for * RSA, DSA, ECDSA. Do this for all versions not just TLS 1.2. To keep * down calls to security callback only check if we have to. */ sigalgslen = tls12_get_psigalgs(s, 1, &sigalgs); for (i = 0; i < sigalgslen; i += 2, sigalgs += 2) { switch (sigalgs[1]) { #ifndef OPENSSL_NO_RSA case TLSEXT_signature_rsa: if (!have_rsa && tls12_sigalg_allowed(s, op, sigalgs)) have_rsa = 1; break; #endif #ifndef OPENSSL_NO_DSA case TLSEXT_signature_dsa: if (!have_dsa && tls12_sigalg_allowed(s, op, sigalgs)) have_dsa = 1; break; #endif #ifndef OPENSSL_NO_EC case TLSEXT_signature_ecdsa: if (!have_ecdsa && tls12_sigalg_allowed(s, op, sigalgs)) have_ecdsa = 1; break; #endif } } if (!have_rsa) *pmask_a |= SSL_aRSA; if (!have_dsa) *pmask_a |= SSL_aDSS; if (!have_ecdsa) *pmask_a |= SSL_aECDSA; } size_t tls12_copy_sigalgs(SSL *s, unsigned char *out, const unsigned char *psig, size_t psiglen) { unsigned char *tmpout = out; size_t i; for (i = 0; i < psiglen; i += 2, psig += 2) { if (tls12_sigalg_allowed(s, SSL_SECOP_SIGALG_SUPPORTED, psig)) { *tmpout++ = psig[0]; *tmpout++ = psig[1]; } } return tmpout - out; } /* Given preference and allowed sigalgs set shared sigalgs */ static int tls12_shared_sigalgs(SSL *s, TLS_SIGALGS *shsig, const unsigned char *pref, size_t preflen, const unsigned char *allow, size_t allowlen) { const unsigned char *ptmp, *atmp; size_t i, j, nmatch = 0; for (i = 0, ptmp = pref; i < preflen; i += 2, ptmp += 2) { /* Skip disabled hashes or signature algorithms */ if (!tls12_sigalg_allowed(s, SSL_SECOP_SIGALG_SHARED, ptmp)) continue; for (j = 0, atmp = allow; j < allowlen; j += 2, atmp += 2) { if (ptmp[0] == atmp[0] && ptmp[1] == atmp[1]) { nmatch++; if (shsig) { shsig->rhash = ptmp[0]; shsig->rsign = ptmp[1]; tls1_lookup_sigalg(&shsig->hash_nid, &shsig->sign_nid, &shsig->signandhash_nid, ptmp); shsig++; } break; } } } return nmatch; } /* Set shared signature algorithms for SSL structures */ static int tls1_set_shared_sigalgs(SSL *s) { const unsigned char *pref, *allow, *conf; size_t preflen, allowlen, conflen; size_t nmatch; TLS_SIGALGS *salgs = NULL; CERT *c = s->cert; unsigned int is_suiteb = tls1_suiteb(s); OPENSSL_free(c->shared_sigalgs); c->shared_sigalgs = NULL; c->shared_sigalgslen = 0; /* If client use client signature algorithms if not NULL */ if (!s->server && c->client_sigalgs && !is_suiteb) { conf = c->client_sigalgs; conflen = c->client_sigalgslen; } else if (c->conf_sigalgs && !is_suiteb) { conf = c->conf_sigalgs; conflen = c->conf_sigalgslen; } else conflen = tls12_get_psigalgs(s, 0, &conf); if (s->options & SSL_OP_CIPHER_SERVER_PREFERENCE || is_suiteb) { pref = conf; preflen = conflen; allow = s->s3->tmp.peer_sigalgs; allowlen = s->s3->tmp.peer_sigalgslen; } else { allow = conf; allowlen = conflen; pref = s->s3->tmp.peer_sigalgs; preflen = s->s3->tmp.peer_sigalgslen; } nmatch = tls12_shared_sigalgs(s, NULL, pref, preflen, allow, allowlen); if (nmatch) { salgs = OPENSSL_malloc(nmatch * sizeof(TLS_SIGALGS)); if (salgs == NULL) return 0; nmatch = tls12_shared_sigalgs(s, salgs, pref, preflen, allow, allowlen); } else { salgs = NULL; } c->shared_sigalgs = salgs; c->shared_sigalgslen = nmatch; return 1; } /* Set preferred digest for each key type */ int tls1_save_sigalgs(SSL *s, const unsigned char *data, int dsize) { CERT *c = s->cert; /* Extension ignored for inappropriate versions */ if (!SSL_USE_SIGALGS(s)) return 1; /* Should never happen */ if (!c) return 0; OPENSSL_free(s->s3->tmp.peer_sigalgs); s->s3->tmp.peer_sigalgs = OPENSSL_malloc(dsize); if (s->s3->tmp.peer_sigalgs == NULL) return 0; s->s3->tmp.peer_sigalgslen = dsize; memcpy(s->s3->tmp.peer_sigalgs, data, dsize); return 1; } int tls1_process_sigalgs(SSL *s) { int idx; size_t i; const EVP_MD *md; const EVP_MD **pmd = s->s3->tmp.md; uint32_t *pvalid = s->s3->tmp.valid_flags; CERT *c = s->cert; TLS_SIGALGS *sigptr; if (!tls1_set_shared_sigalgs(s)) return 0; for (i = 0, sigptr = c->shared_sigalgs; i < c->shared_sigalgslen; i++, sigptr++) { idx = tls12_get_pkey_idx(sigptr->rsign); if (idx > 0 && pmd[idx] == NULL) { md = tls12_get_hash(sigptr->rhash); pmd[idx] = md; pvalid[idx] = CERT_PKEY_EXPLICIT_SIGN; if (idx == SSL_PKEY_RSA_SIGN) { pvalid[SSL_PKEY_RSA_ENC] = CERT_PKEY_EXPLICIT_SIGN; pmd[SSL_PKEY_RSA_ENC] = md; } } } /* * In strict mode leave unset digests as NULL to indicate we can't use * the certificate for signing. */ if (!(s->cert->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT)) { /* * Set any remaining keys to default values. NOTE: if alg is not * supported it stays as NULL. */ #ifndef OPENSSL_NO_DSA if (pmd[SSL_PKEY_DSA_SIGN] == NULL) pmd[SSL_PKEY_DSA_SIGN] = EVP_sha1(); #endif #ifndef OPENSSL_NO_RSA if (pmd[SSL_PKEY_RSA_SIGN] == NULL) { pmd[SSL_PKEY_RSA_SIGN] = EVP_sha1(); pmd[SSL_PKEY_RSA_ENC] = EVP_sha1(); } #endif #ifndef OPENSSL_NO_EC if (pmd[SSL_PKEY_ECC] == NULL) pmd[SSL_PKEY_ECC] = EVP_sha1(); #endif #ifndef OPENSSL_NO_GOST if (pmd[SSL_PKEY_GOST01] == NULL) pmd[SSL_PKEY_GOST01] = EVP_get_digestbynid(NID_id_GostR3411_94); if (pmd[SSL_PKEY_GOST12_256] == NULL) pmd[SSL_PKEY_GOST12_256] = EVP_get_digestbynid(NID_id_GostR3411_2012_256); if (pmd[SSL_PKEY_GOST12_512] == NULL) pmd[SSL_PKEY_GOST12_512] = EVP_get_digestbynid(NID_id_GostR3411_2012_512); #endif } return 1; } int SSL_get_sigalgs(SSL *s, int idx, int *psign, int *phash, int *psignhash, unsigned char *rsig, unsigned char *rhash) { const unsigned char *psig = s->s3->tmp.peer_sigalgs; if (psig == NULL) return 0; if (idx >= 0) { idx <<= 1; if (idx >= (int)s->s3->tmp.peer_sigalgslen) return 0; psig += idx; if (rhash) *rhash = psig[0]; if (rsig) *rsig = psig[1]; tls1_lookup_sigalg(phash, psign, psignhash, psig); } return s->s3->tmp.peer_sigalgslen / 2; } int SSL_get_shared_sigalgs(SSL *s, int idx, int *psign, int *phash, int *psignhash, unsigned char *rsig, unsigned char *rhash) { TLS_SIGALGS *shsigalgs = s->cert->shared_sigalgs; if (!shsigalgs || idx >= (int)s->cert->shared_sigalgslen) return 0; shsigalgs += idx; if (phash) *phash = shsigalgs->hash_nid; if (psign) *psign = shsigalgs->sign_nid; if (psignhash) *psignhash = shsigalgs->signandhash_nid; if (rsig) *rsig = shsigalgs->rsign; if (rhash) *rhash = shsigalgs->rhash; return s->cert->shared_sigalgslen; } #define MAX_SIGALGLEN (TLSEXT_hash_num * TLSEXT_signature_num * 2) typedef struct { size_t sigalgcnt; int sigalgs[MAX_SIGALGLEN]; } sig_cb_st; static void get_sigorhash(int *psig, int *phash, const char *str) { if (strcmp(str, "RSA") == 0) { *psig = EVP_PKEY_RSA; } else if (strcmp(str, "DSA") == 0) { *psig = EVP_PKEY_DSA; } else if (strcmp(str, "ECDSA") == 0) { *psig = EVP_PKEY_EC; } else { *phash = OBJ_sn2nid(str); if (*phash == NID_undef) *phash = OBJ_ln2nid(str); } } static int sig_cb(const char *elem, int len, void *arg) { sig_cb_st *sarg = arg; size_t i; char etmp[20], *p; int sig_alg = NID_undef, hash_alg = NID_undef; if (elem == NULL) return 0; if (sarg->sigalgcnt == MAX_SIGALGLEN) return 0; if (len > (int)(sizeof(etmp) - 1)) return 0; memcpy(etmp, elem, len); etmp[len] = 0; p = strchr(etmp, '+'); if (!p) return 0; *p = 0; p++; if (!*p) return 0; get_sigorhash(&sig_alg, &hash_alg, etmp); get_sigorhash(&sig_alg, &hash_alg, p); if (sig_alg == NID_undef || hash_alg == NID_undef) return 0; for (i = 0; i < sarg->sigalgcnt; i += 2) { if (sarg->sigalgs[i] == sig_alg && sarg->sigalgs[i + 1] == hash_alg) return 0; } sarg->sigalgs[sarg->sigalgcnt++] = hash_alg; sarg->sigalgs[sarg->sigalgcnt++] = sig_alg; return 1; } /* * Set supported signature algorithms based on a colon separated list of the * form sig+hash e.g. RSA+SHA512:DSA+SHA512 */ int tls1_set_sigalgs_list(CERT *c, const char *str, int client) { sig_cb_st sig; sig.sigalgcnt = 0; if (!CONF_parse_list(str, ':', 1, sig_cb, &sig)) return 0; if (c == NULL) return 1; return tls1_set_sigalgs(c, sig.sigalgs, sig.sigalgcnt, client); } int tls1_set_sigalgs(CERT *c, const int *psig_nids, size_t salglen, int client) { unsigned char *sigalgs, *sptr; int rhash, rsign; size_t i; if (salglen & 1) return 0; sigalgs = OPENSSL_malloc(salglen); if (sigalgs == NULL) return 0; for (i = 0, sptr = sigalgs; i < salglen; i += 2) { rhash = tls12_find_id(*psig_nids++, tls12_md, OSSL_NELEM(tls12_md)); rsign = tls12_find_id(*psig_nids++, tls12_sig, OSSL_NELEM(tls12_sig)); if (rhash == -1 || rsign == -1) goto err; *sptr++ = rhash; *sptr++ = rsign; } if (client) { OPENSSL_free(c->client_sigalgs); c->client_sigalgs = sigalgs; c->client_sigalgslen = salglen; } else { OPENSSL_free(c->conf_sigalgs); c->conf_sigalgs = sigalgs; c->conf_sigalgslen = salglen; } return 1; err: OPENSSL_free(sigalgs); return 0; } static int tls1_check_sig_alg(CERT *c, X509 *x, int default_nid) { int sig_nid; size_t i; if (default_nid == -1) return 1; sig_nid = X509_get_signature_nid(x); if (default_nid) return sig_nid == default_nid ? 1 : 0; for (i = 0; i < c->shared_sigalgslen; i++) if (sig_nid == c->shared_sigalgs[i].signandhash_nid) return 1; return 0; } /* Check to see if a certificate issuer name matches list of CA names */ static int ssl_check_ca_name(STACK_OF(X509_NAME) *names, X509 *x) { X509_NAME *nm; int i; nm = X509_get_issuer_name(x); for (i = 0; i < sk_X509_NAME_num(names); i++) { if (!X509_NAME_cmp(nm, sk_X509_NAME_value(names, i))) return 1; } return 0; } /* * Check certificate chain is consistent with TLS extensions and is usable by * server. This servers two purposes: it allows users to check chains before * passing them to the server and it allows the server to check chains before * attempting to use them. */ /* Flags which need to be set for a certificate when stict mode not set */ #define CERT_PKEY_VALID_FLAGS \ (CERT_PKEY_EE_SIGNATURE|CERT_PKEY_EE_PARAM) /* Strict mode flags */ #define CERT_PKEY_STRICT_FLAGS \ (CERT_PKEY_VALID_FLAGS|CERT_PKEY_CA_SIGNATURE|CERT_PKEY_CA_PARAM \ | CERT_PKEY_ISSUER_NAME|CERT_PKEY_CERT_TYPE) int tls1_check_chain(SSL *s, X509 *x, EVP_PKEY *pk, STACK_OF(X509) *chain, int idx) { int i; int rv = 0; int check_flags = 0, strict_mode; CERT_PKEY *cpk = NULL; CERT *c = s->cert; uint32_t *pvalid; unsigned int suiteb_flags = tls1_suiteb(s); /* idx == -1 means checking server chains */ if (idx != -1) { /* idx == -2 means checking client certificate chains */ if (idx == -2) { cpk = c->key; idx = cpk - c->pkeys; } else cpk = c->pkeys + idx; pvalid = s->s3->tmp.valid_flags + idx; x = cpk->x509; pk = cpk->privatekey; chain = cpk->chain; strict_mode = c->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT; /* If no cert or key, forget it */ if (!x || !pk) goto end; } else { if (!x || !pk) return 0; idx = ssl_cert_type(x, pk); if (idx == -1) return 0; pvalid = s->s3->tmp.valid_flags + idx; if (c->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT) check_flags = CERT_PKEY_STRICT_FLAGS; else check_flags = CERT_PKEY_VALID_FLAGS; strict_mode = 1; } if (suiteb_flags) { int ok; if (check_flags) check_flags |= CERT_PKEY_SUITEB; ok = X509_chain_check_suiteb(NULL, x, chain, suiteb_flags); if (ok == X509_V_OK) rv |= CERT_PKEY_SUITEB; else if (!check_flags) goto end; } /* * Check all signature algorithms are consistent with signature * algorithms extension if TLS 1.2 or later and strict mode. */ if (TLS1_get_version(s) >= TLS1_2_VERSION && strict_mode) { int default_nid; unsigned char rsign = 0; if (s->s3->tmp.peer_sigalgs) default_nid = 0; /* If no sigalgs extension use defaults from RFC5246 */ else { switch (idx) { case SSL_PKEY_RSA_ENC: case SSL_PKEY_RSA_SIGN: rsign = TLSEXT_signature_rsa; default_nid = NID_sha1WithRSAEncryption; break; case SSL_PKEY_DSA_SIGN: rsign = TLSEXT_signature_dsa; default_nid = NID_dsaWithSHA1; break; case SSL_PKEY_ECC: rsign = TLSEXT_signature_ecdsa; default_nid = NID_ecdsa_with_SHA1; break; case SSL_PKEY_GOST01: rsign = TLSEXT_signature_gostr34102001; default_nid = NID_id_GostR3411_94_with_GostR3410_2001; break; case SSL_PKEY_GOST12_256: rsign = TLSEXT_signature_gostr34102012_256; default_nid = NID_id_tc26_signwithdigest_gost3410_2012_256; break; case SSL_PKEY_GOST12_512: rsign = TLSEXT_signature_gostr34102012_512; default_nid = NID_id_tc26_signwithdigest_gost3410_2012_512; break; default: default_nid = -1; break; } } /* * If peer sent no signature algorithms extension and we have set * preferred signature algorithms check we support sha1. */ if (default_nid > 0 && c->conf_sigalgs) { size_t j; const unsigned char *p = c->conf_sigalgs; for (j = 0; j < c->conf_sigalgslen; j += 2, p += 2) { if (p[0] == TLSEXT_hash_sha1 && p[1] == rsign) break; } if (j == c->conf_sigalgslen) { if (check_flags) goto skip_sigs; else goto end; } } /* Check signature algorithm of each cert in chain */ if (!tls1_check_sig_alg(c, x, default_nid)) { if (!check_flags) goto end; } else rv |= CERT_PKEY_EE_SIGNATURE; rv |= CERT_PKEY_CA_SIGNATURE; for (i = 0; i < sk_X509_num(chain); i++) { if (!tls1_check_sig_alg(c, sk_X509_value(chain, i), default_nid)) { if (check_flags) { rv &= ~CERT_PKEY_CA_SIGNATURE; break; } else goto end; } } } /* Else not TLS 1.2, so mark EE and CA signing algorithms OK */ else if (check_flags) rv |= CERT_PKEY_EE_SIGNATURE | CERT_PKEY_CA_SIGNATURE; skip_sigs: /* Check cert parameters are consistent */ if (tls1_check_cert_param(s, x, check_flags ? 1 : 2)) rv |= CERT_PKEY_EE_PARAM; else if (!check_flags) goto end; if (!s->server) rv |= CERT_PKEY_CA_PARAM; /* In strict mode check rest of chain too */ else if (strict_mode) { rv |= CERT_PKEY_CA_PARAM; for (i = 0; i < sk_X509_num(chain); i++) { X509 *ca = sk_X509_value(chain, i); if (!tls1_check_cert_param(s, ca, 0)) { if (check_flags) { rv &= ~CERT_PKEY_CA_PARAM; break; } else goto end; } } } if (!s->server && strict_mode) { STACK_OF(X509_NAME) *ca_dn; int check_type = 0; switch (EVP_PKEY_id(pk)) { case EVP_PKEY_RSA: check_type = TLS_CT_RSA_SIGN; break; case EVP_PKEY_DSA: check_type = TLS_CT_DSS_SIGN; break; case EVP_PKEY_EC: check_type = TLS_CT_ECDSA_SIGN; break; } if (check_type) { const unsigned char *ctypes; int ctypelen; if (c->ctypes) { ctypes = c->ctypes; ctypelen = (int)c->ctype_num; } else { ctypes = (unsigned char *)s->s3->tmp.ctype; ctypelen = s->s3->tmp.ctype_num; } for (i = 0; i < ctypelen; i++) { if (ctypes[i] == check_type) { rv |= CERT_PKEY_CERT_TYPE; break; } } if (!(rv & CERT_PKEY_CERT_TYPE) && !check_flags) goto end; } else rv |= CERT_PKEY_CERT_TYPE; ca_dn = s->s3->tmp.ca_names; if (!sk_X509_NAME_num(ca_dn)) rv |= CERT_PKEY_ISSUER_NAME; if (!(rv & CERT_PKEY_ISSUER_NAME)) { if (ssl_check_ca_name(ca_dn, x)) rv |= CERT_PKEY_ISSUER_NAME; } if (!(rv & CERT_PKEY_ISSUER_NAME)) { for (i = 0; i < sk_X509_num(chain); i++) { X509 *xtmp = sk_X509_value(chain, i); if (ssl_check_ca_name(ca_dn, xtmp)) { rv |= CERT_PKEY_ISSUER_NAME; break; } } } if (!check_flags && !(rv & CERT_PKEY_ISSUER_NAME)) goto end; } else rv |= CERT_PKEY_ISSUER_NAME | CERT_PKEY_CERT_TYPE; if (!check_flags || (rv & check_flags) == check_flags) rv |= CERT_PKEY_VALID; end: if (TLS1_get_version(s) >= TLS1_2_VERSION) { if (*pvalid & CERT_PKEY_EXPLICIT_SIGN) rv |= CERT_PKEY_EXPLICIT_SIGN | CERT_PKEY_SIGN; else if (s->s3->tmp.md[idx] != NULL) rv |= CERT_PKEY_SIGN; } else rv |= CERT_PKEY_SIGN | CERT_PKEY_EXPLICIT_SIGN; /* * When checking a CERT_PKEY structure all flags are irrelevant if the * chain is invalid. */ if (!check_flags) { if (rv & CERT_PKEY_VALID) *pvalid = rv; else { /* Preserve explicit sign flag, clear rest */ *pvalid &= CERT_PKEY_EXPLICIT_SIGN; return 0; } } return rv; } /* Set validity of certificates in an SSL structure */ void tls1_set_cert_validity(SSL *s) { tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_RSA_ENC); tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_RSA_SIGN); tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_DSA_SIGN); tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_ECC); tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_GOST01); tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_GOST12_256); tls1_check_chain(s, NULL, NULL, NULL, SSL_PKEY_GOST12_512); } /* User level utiity function to check a chain is suitable */ int SSL_check_chain(SSL *s, X509 *x, EVP_PKEY *pk, STACK_OF(X509) *chain) { return tls1_check_chain(s, x, pk, chain, -1); } #ifndef OPENSSL_NO_DH DH *ssl_get_auto_dh(SSL *s) { int dh_secbits = 80; if (s->cert->dh_tmp_auto == 2) return DH_get_1024_160(); if (s->s3->tmp.new_cipher->algorithm_auth & (SSL_aNULL | SSL_aPSK)) { if (s->s3->tmp.new_cipher->strength_bits == 256) dh_secbits = 128; else dh_secbits = 80; } else { CERT_PKEY *cpk = ssl_get_server_send_pkey(s); dh_secbits = EVP_PKEY_security_bits(cpk->privatekey); } if (dh_secbits >= 128) { DH *dhp = DH_new(); BIGNUM *p, *g; if (dhp == NULL) return NULL; g = BN_new(); if (g != NULL) BN_set_word(g, 2); if (dh_secbits >= 192) p = BN_get_rfc3526_prime_8192(NULL); else p = BN_get_rfc3526_prime_3072(NULL); if (p == NULL || g == NULL || !DH_set0_pqg(dhp, p, NULL, g)) { DH_free(dhp); BN_free(p); BN_free(g); return NULL; } return dhp; } if (dh_secbits >= 112) return DH_get_2048_224(); return DH_get_1024_160(); } #endif static int ssl_security_cert_key(SSL *s, SSL_CTX *ctx, X509 *x, int op) { int secbits = -1; EVP_PKEY *pkey = X509_get0_pubkey(x); if (pkey) { /* * If no parameters this will return -1 and fail using the default * security callback for any non-zero security level. This will * reject keys which omit parameters but this only affects DSA and * omission of parameters is never (?) done in practice. */ secbits = EVP_PKEY_security_bits(pkey); } if (s) return ssl_security(s, op, secbits, 0, x); else return ssl_ctx_security(ctx, op, secbits, 0, x); } static int ssl_security_cert_sig(SSL *s, SSL_CTX *ctx, X509 *x, int op) { /* Lookup signature algorithm digest */ int secbits = -1, md_nid = NID_undef, sig_nid; /* Don't check signature if self signed */ if ((X509_get_extension_flags(x) & EXFLAG_SS) != 0) return 1; sig_nid = X509_get_signature_nid(x); if (sig_nid && OBJ_find_sigid_algs(sig_nid, &md_nid, NULL)) { const EVP_MD *md; if (md_nid && (md = EVP_get_digestbynid(md_nid))) secbits = EVP_MD_size(md) * 4; } if (s) return ssl_security(s, op, secbits, md_nid, x); else return ssl_ctx_security(ctx, op, secbits, md_nid, x); } int ssl_security_cert(SSL *s, SSL_CTX *ctx, X509 *x, int vfy, int is_ee) { if (vfy) vfy = SSL_SECOP_PEER; if (is_ee) { if (!ssl_security_cert_key(s, ctx, x, SSL_SECOP_EE_KEY | vfy)) return SSL_R_EE_KEY_TOO_SMALL; } else { if (!ssl_security_cert_key(s, ctx, x, SSL_SECOP_CA_KEY | vfy)) return SSL_R_CA_KEY_TOO_SMALL; } if (!ssl_security_cert_sig(s, ctx, x, SSL_SECOP_CA_MD | vfy)) return SSL_R_CA_MD_TOO_WEAK; return 1; } /* * Check security of a chain, if sk includes the end entity certificate then * x is NULL. If vfy is 1 then we are verifying a peer chain and not sending * one to the peer. Return values: 1 if ok otherwise error code to use */ int ssl_security_cert_chain(SSL *s, STACK_OF(X509) *sk, X509 *x, int vfy) { int rv, start_idx, i; if (x == NULL) { x = sk_X509_value(sk, 0); start_idx = 1; } else start_idx = 0; rv = ssl_security_cert(s, NULL, x, vfy, 1); if (rv != 1) return rv; for (i = start_idx; i < sk_X509_num(sk); i++) { x = sk_X509_value(sk, i); rv = ssl_security_cert(s, NULL, x, vfy, 0); if (rv != 1) return rv; } return 1; }
./CrossVul/dataset_final_sorted/CWE-20/c/good_3070_5
crossvul-cpp_data_good_191_0
/* * MPEG-4 decoder * Copyright (c) 2000,2001 Fabrice Bellard * Copyright (c) 2002-2010 Michael Niedermayer <michaelni@gmx.at> * * 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 */ #define UNCHECKED_BITSTREAM_READER 1 #include "libavutil/internal.h" #include "libavutil/opt.h" #include "error_resilience.h" #include "hwaccel.h" #include "idctdsp.h" #include "internal.h" #include "mpegutils.h" #include "mpegvideo.h" #include "mpegvideodata.h" #include "mpeg4video.h" #include "h263.h" #include "profiles.h" #include "thread.h" #include "xvididct.h" /* The defines below define the number of bits that are read at once for * reading vlc values. Changing these may improve speed and data cache needs * be aware though that decreasing them may need the number of stages that is * passed to get_vlc* to be increased. */ #define SPRITE_TRAJ_VLC_BITS 6 #define DC_VLC_BITS 9 #define MB_TYPE_B_VLC_BITS 4 #define STUDIO_INTRA_BITS 9 static int decode_studio_vol_header(Mpeg4DecContext *ctx, GetBitContext *gb); static VLC dc_lum, dc_chrom; static VLC sprite_trajectory; static VLC mb_type_b_vlc; static const int mb_type_b_map[4] = { MB_TYPE_DIRECT2 | MB_TYPE_L0L1, MB_TYPE_L0L1 | MB_TYPE_16x16, MB_TYPE_L1 | MB_TYPE_16x16, MB_TYPE_L0 | MB_TYPE_16x16, }; /** * Predict the ac. * @param n block index (0-3 are luma, 4-5 are chroma) * @param dir the ac prediction direction */ void ff_mpeg4_pred_ac(MpegEncContext *s, int16_t *block, int n, int dir) { int i; int16_t *ac_val, *ac_val1; int8_t *const qscale_table = s->current_picture.qscale_table; /* find prediction */ ac_val = &s->ac_val[0][0][0] + s->block_index[n] * 16; ac_val1 = ac_val; if (s->ac_pred) { if (dir == 0) { const int xy = s->mb_x - 1 + s->mb_y * s->mb_stride; /* left prediction */ ac_val -= 16; if (s->mb_x == 0 || s->qscale == qscale_table[xy] || n == 1 || n == 3) { /* same qscale */ for (i = 1; i < 8; i++) block[s->idsp.idct_permutation[i << 3]] += ac_val[i]; } else { /* different qscale, we must rescale */ for (i = 1; i < 8; i++) block[s->idsp.idct_permutation[i << 3]] += ROUNDED_DIV(ac_val[i] * qscale_table[xy], s->qscale); } } else { const int xy = s->mb_x + s->mb_y * s->mb_stride - s->mb_stride; /* top prediction */ ac_val -= 16 * s->block_wrap[n]; if (s->mb_y == 0 || s->qscale == qscale_table[xy] || n == 2 || n == 3) { /* same qscale */ for (i = 1; i < 8; i++) block[s->idsp.idct_permutation[i]] += ac_val[i + 8]; } else { /* different qscale, we must rescale */ for (i = 1; i < 8; i++) block[s->idsp.idct_permutation[i]] += ROUNDED_DIV(ac_val[i + 8] * qscale_table[xy], s->qscale); } } } /* left copy */ for (i = 1; i < 8; i++) ac_val1[i] = block[s->idsp.idct_permutation[i << 3]]; /* top copy */ for (i = 1; i < 8; i++) ac_val1[8 + i] = block[s->idsp.idct_permutation[i]]; } /** * check if the next stuff is a resync marker or the end. * @return 0 if not */ static inline int mpeg4_is_resync(Mpeg4DecContext *ctx) { MpegEncContext *s = &ctx->m; int bits_count = get_bits_count(&s->gb); int v = show_bits(&s->gb, 16); if (s->workaround_bugs & FF_BUG_NO_PADDING && !ctx->resync_marker) return 0; while (v <= 0xFF) { if (s->pict_type == AV_PICTURE_TYPE_B || (v >> (8 - s->pict_type) != 1) || s->partitioned_frame) break; skip_bits(&s->gb, 8 + s->pict_type); bits_count += 8 + s->pict_type; v = show_bits(&s->gb, 16); } if (bits_count + 8 >= s->gb.size_in_bits) { v >>= 8; v |= 0x7F >> (7 - (bits_count & 7)); if (v == 0x7F) return s->mb_num; } else { if (v == ff_mpeg4_resync_prefix[bits_count & 7]) { int len, mb_num; int mb_num_bits = av_log2(s->mb_num - 1) + 1; GetBitContext gb = s->gb; skip_bits(&s->gb, 1); align_get_bits(&s->gb); for (len = 0; len < 32; len++) if (get_bits1(&s->gb)) break; mb_num = get_bits(&s->gb, mb_num_bits); if (!mb_num || mb_num > s->mb_num || get_bits_count(&s->gb)+6 > s->gb.size_in_bits) mb_num= -1; s->gb = gb; if (len >= ff_mpeg4_get_video_packet_prefix_length(s)) return mb_num; } } return 0; } static int mpeg4_decode_sprite_trajectory(Mpeg4DecContext *ctx, GetBitContext *gb) { MpegEncContext *s = &ctx->m; int a = 2 << s->sprite_warping_accuracy; int rho = 3 - s->sprite_warping_accuracy; int r = 16 / a; int alpha = 1; int beta = 0; int w = s->width; int h = s->height; int min_ab, i, w2, h2, w3, h3; int sprite_ref[4][2]; int virtual_ref[2][2]; int64_t sprite_offset[2][2]; int64_t sprite_delta[2][2]; // only true for rectangle shapes const int vop_ref[4][2] = { { 0, 0 }, { s->width, 0 }, { 0, s->height }, { s->width, s->height } }; int d[4][2] = { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 } }; if (w <= 0 || h <= 0) return AVERROR_INVALIDDATA; /* the decoder was not properly initialized and we cannot continue */ if (sprite_trajectory.table == NULL) return AVERROR_INVALIDDATA; for (i = 0; i < ctx->num_sprite_warping_points; i++) { int length; int x = 0, y = 0; length = get_vlc2(gb, sprite_trajectory.table, SPRITE_TRAJ_VLC_BITS, 3); if (length > 0) x = get_xbits(gb, length); if (!(ctx->divx_version == 500 && ctx->divx_build == 413)) check_marker(s->avctx, gb, "before sprite_trajectory"); length = get_vlc2(gb, sprite_trajectory.table, SPRITE_TRAJ_VLC_BITS, 3); if (length > 0) y = get_xbits(gb, length); check_marker(s->avctx, gb, "after sprite_trajectory"); ctx->sprite_traj[i][0] = d[i][0] = x; ctx->sprite_traj[i][1] = d[i][1] = y; } for (; i < 4; i++) ctx->sprite_traj[i][0] = ctx->sprite_traj[i][1] = 0; while ((1 << alpha) < w) alpha++; while ((1 << beta) < h) beta++; /* typo in the MPEG-4 std for the definition of w' and h' */ w2 = 1 << alpha; h2 = 1 << beta; // Note, the 4th point isn't used for GMC if (ctx->divx_version == 500 && ctx->divx_build == 413) { sprite_ref[0][0] = a * vop_ref[0][0] + d[0][0]; sprite_ref[0][1] = a * vop_ref[0][1] + d[0][1]; sprite_ref[1][0] = a * vop_ref[1][0] + d[0][0] + d[1][0]; sprite_ref[1][1] = a * vop_ref[1][1] + d[0][1] + d[1][1]; sprite_ref[2][0] = a * vop_ref[2][0] + d[0][0] + d[2][0]; sprite_ref[2][1] = a * vop_ref[2][1] + d[0][1] + d[2][1]; } else { sprite_ref[0][0] = (a >> 1) * (2 * vop_ref[0][0] + d[0][0]); sprite_ref[0][1] = (a >> 1) * (2 * vop_ref[0][1] + d[0][1]); sprite_ref[1][0] = (a >> 1) * (2 * vop_ref[1][0] + d[0][0] + d[1][0]); sprite_ref[1][1] = (a >> 1) * (2 * vop_ref[1][1] + d[0][1] + d[1][1]); sprite_ref[2][0] = (a >> 1) * (2 * vop_ref[2][0] + d[0][0] + d[2][0]); sprite_ref[2][1] = (a >> 1) * (2 * vop_ref[2][1] + d[0][1] + d[2][1]); } /* sprite_ref[3][0] = (a >> 1) * (2 * vop_ref[3][0] + d[0][0] + d[1][0] + d[2][0] + d[3][0]); * sprite_ref[3][1] = (a >> 1) * (2 * vop_ref[3][1] + d[0][1] + d[1][1] + d[2][1] + d[3][1]); */ /* This is mostly identical to the MPEG-4 std (and is totally unreadable * because of that...). Perhaps it should be reordered to be more readable. * The idea behind this virtual_ref mess is to be able to use shifts later * per pixel instead of divides so the distance between points is converted * from w&h based to w2&h2 based which are of the 2^x form. */ virtual_ref[0][0] = 16 * (vop_ref[0][0] + w2) + ROUNDED_DIV(((w - w2) * (r * sprite_ref[0][0] - 16LL * vop_ref[0][0]) + w2 * (r * sprite_ref[1][0] - 16LL * vop_ref[1][0])), w); virtual_ref[0][1] = 16 * vop_ref[0][1] + ROUNDED_DIV(((w - w2) * (r * sprite_ref[0][1] - 16LL * vop_ref[0][1]) + w2 * (r * sprite_ref[1][1] - 16LL * vop_ref[1][1])), w); virtual_ref[1][0] = 16 * vop_ref[0][0] + ROUNDED_DIV(((h - h2) * (r * sprite_ref[0][0] - 16LL * vop_ref[0][0]) + h2 * (r * sprite_ref[2][0] - 16LL * vop_ref[2][0])), h); virtual_ref[1][1] = 16 * (vop_ref[0][1] + h2) + ROUNDED_DIV(((h - h2) * (r * sprite_ref[0][1] - 16LL * vop_ref[0][1]) + h2 * (r * sprite_ref[2][1] - 16LL * vop_ref[2][1])), h); switch (ctx->num_sprite_warping_points) { case 0: sprite_offset[0][0] = sprite_offset[0][1] = sprite_offset[1][0] = sprite_offset[1][1] = 0; sprite_delta[0][0] = a; sprite_delta[0][1] = sprite_delta[1][0] = 0; sprite_delta[1][1] = a; ctx->sprite_shift[0] = ctx->sprite_shift[1] = 0; break; case 1: // GMC only sprite_offset[0][0] = sprite_ref[0][0] - a * vop_ref[0][0]; sprite_offset[0][1] = sprite_ref[0][1] - a * vop_ref[0][1]; sprite_offset[1][0] = ((sprite_ref[0][0] >> 1) | (sprite_ref[0][0] & 1)) - a * (vop_ref[0][0] / 2); sprite_offset[1][1] = ((sprite_ref[0][1] >> 1) | (sprite_ref[0][1] & 1)) - a * (vop_ref[0][1] / 2); sprite_delta[0][0] = a; sprite_delta[0][1] = sprite_delta[1][0] = 0; sprite_delta[1][1] = a; ctx->sprite_shift[0] = ctx->sprite_shift[1] = 0; break; case 2: sprite_offset[0][0] = ((int64_t) sprite_ref[0][0] * (1 << alpha + rho)) + ((int64_t) -r * sprite_ref[0][0] + virtual_ref[0][0]) * ((int64_t) -vop_ref[0][0]) + ((int64_t) r * sprite_ref[0][1] - virtual_ref[0][1]) * ((int64_t) -vop_ref[0][1]) + (1 << (alpha + rho - 1)); sprite_offset[0][1] = ((int64_t) sprite_ref[0][1] * (1 << alpha + rho)) + ((int64_t) -r * sprite_ref[0][1] + virtual_ref[0][1]) * ((int64_t) -vop_ref[0][0]) + ((int64_t) -r * sprite_ref[0][0] + virtual_ref[0][0]) * ((int64_t) -vop_ref[0][1]) + (1 << (alpha + rho - 1)); sprite_offset[1][0] = (((int64_t)-r * sprite_ref[0][0] + virtual_ref[0][0]) * ((int64_t)-2 * vop_ref[0][0] + 1) + ((int64_t) r * sprite_ref[0][1] - virtual_ref[0][1]) * ((int64_t)-2 * vop_ref[0][1] + 1) + 2 * w2 * r * (int64_t) sprite_ref[0][0] - 16 * w2 + (1 << (alpha + rho + 1))); sprite_offset[1][1] = (((int64_t)-r * sprite_ref[0][1] + virtual_ref[0][1]) * ((int64_t)-2 * vop_ref[0][0] + 1) + ((int64_t)-r * sprite_ref[0][0] + virtual_ref[0][0]) * ((int64_t)-2 * vop_ref[0][1] + 1) + 2 * w2 * r * (int64_t) sprite_ref[0][1] - 16 * w2 + (1 << (alpha + rho + 1))); sprite_delta[0][0] = (-r * sprite_ref[0][0] + virtual_ref[0][0]); sprite_delta[0][1] = (+r * sprite_ref[0][1] - virtual_ref[0][1]); sprite_delta[1][0] = (-r * sprite_ref[0][1] + virtual_ref[0][1]); sprite_delta[1][1] = (-r * sprite_ref[0][0] + virtual_ref[0][0]); ctx->sprite_shift[0] = alpha + rho; ctx->sprite_shift[1] = alpha + rho + 2; break; case 3: min_ab = FFMIN(alpha, beta); w3 = w2 >> min_ab; h3 = h2 >> min_ab; sprite_offset[0][0] = ((int64_t)sprite_ref[0][0] * (1 << (alpha + beta + rho - min_ab))) + ((int64_t)-r * sprite_ref[0][0] + virtual_ref[0][0]) * h3 * (-vop_ref[0][0]) + ((int64_t)-r * sprite_ref[0][0] + virtual_ref[1][0]) * w3 * (-vop_ref[0][1]) + ((int64_t)1 << (alpha + beta + rho - min_ab - 1)); sprite_offset[0][1] = ((int64_t)sprite_ref[0][1] * (1 << (alpha + beta + rho - min_ab))) + ((int64_t)-r * sprite_ref[0][1] + virtual_ref[0][1]) * h3 * (-vop_ref[0][0]) + ((int64_t)-r * sprite_ref[0][1] + virtual_ref[1][1]) * w3 * (-vop_ref[0][1]) + ((int64_t)1 << (alpha + beta + rho - min_ab - 1)); sprite_offset[1][0] = ((int64_t)-r * sprite_ref[0][0] + virtual_ref[0][0]) * h3 * (-2 * vop_ref[0][0] + 1) + ((int64_t)-r * sprite_ref[0][0] + virtual_ref[1][0]) * w3 * (-2 * vop_ref[0][1] + 1) + (int64_t)2 * w2 * h3 * r * sprite_ref[0][0] - 16 * w2 * h3 + ((int64_t)1 << (alpha + beta + rho - min_ab + 1)); sprite_offset[1][1] = ((int64_t)-r * sprite_ref[0][1] + virtual_ref[0][1]) * h3 * (-2 * vop_ref[0][0] + 1) + ((int64_t)-r * sprite_ref[0][1] + virtual_ref[1][1]) * w3 * (-2 * vop_ref[0][1] + 1) + (int64_t)2 * w2 * h3 * r * sprite_ref[0][1] - 16 * w2 * h3 + ((int64_t)1 << (alpha + beta + rho - min_ab + 1)); sprite_delta[0][0] = (-r * (int64_t)sprite_ref[0][0] + virtual_ref[0][0]) * h3; sprite_delta[0][1] = (-r * (int64_t)sprite_ref[0][0] + virtual_ref[1][0]) * w3; sprite_delta[1][0] = (-r * (int64_t)sprite_ref[0][1] + virtual_ref[0][1]) * h3; sprite_delta[1][1] = (-r * (int64_t)sprite_ref[0][1] + virtual_ref[1][1]) * w3; ctx->sprite_shift[0] = alpha + beta + rho - min_ab; ctx->sprite_shift[1] = alpha + beta + rho - min_ab + 2; break; } /* try to simplify the situation */ if (sprite_delta[0][0] == a << ctx->sprite_shift[0] && sprite_delta[0][1] == 0 && sprite_delta[1][0] == 0 && sprite_delta[1][1] == a << ctx->sprite_shift[0]) { sprite_offset[0][0] >>= ctx->sprite_shift[0]; sprite_offset[0][1] >>= ctx->sprite_shift[0]; sprite_offset[1][0] >>= ctx->sprite_shift[1]; sprite_offset[1][1] >>= ctx->sprite_shift[1]; sprite_delta[0][0] = a; sprite_delta[0][1] = 0; sprite_delta[1][0] = 0; sprite_delta[1][1] = a; ctx->sprite_shift[0] = 0; ctx->sprite_shift[1] = 0; s->real_sprite_warping_points = 1; } else { int shift_y = 16 - ctx->sprite_shift[0]; int shift_c = 16 - ctx->sprite_shift[1]; for (i = 0; i < 2; i++) { if (shift_c < 0 || shift_y < 0 || FFABS( sprite_offset[0][i]) >= INT_MAX >> shift_y || FFABS( sprite_offset[1][i]) >= INT_MAX >> shift_c || FFABS( sprite_delta[0][i]) >= INT_MAX >> shift_y || FFABS( sprite_delta[1][i]) >= INT_MAX >> shift_y ) { avpriv_request_sample(s->avctx, "Too large sprite shift, delta or offset"); goto overflow; } } for (i = 0; i < 2; i++) { sprite_offset[0][i] *= 1 << shift_y; sprite_offset[1][i] *= 1 << shift_c; sprite_delta[0][i] *= 1 << shift_y; sprite_delta[1][i] *= 1 << shift_y; ctx->sprite_shift[i] = 16; } for (i = 0; i < 2; i++) { int64_t sd[2] = { sprite_delta[i][0] - a * (1LL<<16), sprite_delta[i][1] - a * (1LL<<16) }; if (llabs(sprite_offset[0][i] + sprite_delta[i][0] * (w+16LL)) >= INT_MAX || llabs(sprite_offset[0][i] + sprite_delta[i][1] * (h+16LL)) >= INT_MAX || llabs(sprite_offset[0][i] + sprite_delta[i][0] * (w+16LL) + sprite_delta[i][1] * (h+16LL)) >= INT_MAX || llabs(sprite_delta[i][0] * (w+16LL)) >= INT_MAX || llabs(sprite_delta[i][1] * (w+16LL)) >= INT_MAX || llabs(sd[0]) >= INT_MAX || llabs(sd[1]) >= INT_MAX || llabs(sprite_offset[0][i] + sd[0] * (w+16LL)) >= INT_MAX || llabs(sprite_offset[0][i] + sd[1] * (h+16LL)) >= INT_MAX || llabs(sprite_offset[0][i] + sd[0] * (w+16LL) + sd[1] * (h+16LL)) >= INT_MAX ) { avpriv_request_sample(s->avctx, "Overflow on sprite points"); goto overflow; } } s->real_sprite_warping_points = ctx->num_sprite_warping_points; } for (i = 0; i < 4; i++) { s->sprite_offset[i&1][i>>1] = sprite_offset[i&1][i>>1]; s->sprite_delta [i&1][i>>1] = sprite_delta [i&1][i>>1]; } return 0; overflow: memset(s->sprite_offset, 0, sizeof(s->sprite_offset)); memset(s->sprite_delta, 0, sizeof(s->sprite_delta)); return AVERROR_PATCHWELCOME; } static int decode_new_pred(Mpeg4DecContext *ctx, GetBitContext *gb) { MpegEncContext *s = &ctx->m; int len = FFMIN(ctx->time_increment_bits + 3, 15); get_bits(gb, len); if (get_bits1(gb)) get_bits(gb, len); check_marker(s->avctx, gb, "after new_pred"); return 0; } /** * Decode the next video packet. * @return <0 if something went wrong */ int ff_mpeg4_decode_video_packet_header(Mpeg4DecContext *ctx) { MpegEncContext *s = &ctx->m; int mb_num_bits = av_log2(s->mb_num - 1) + 1; int header_extension = 0, mb_num, len; /* is there enough space left for a video packet + header */ if (get_bits_count(&s->gb) > s->gb.size_in_bits - 20) return AVERROR_INVALIDDATA; for (len = 0; len < 32; len++) if (get_bits1(&s->gb)) break; if (len != ff_mpeg4_get_video_packet_prefix_length(s)) { av_log(s->avctx, AV_LOG_ERROR, "marker does not match f_code\n"); return AVERROR_INVALIDDATA; } if (ctx->shape != RECT_SHAPE) { header_extension = get_bits1(&s->gb); // FIXME more stuff here } mb_num = get_bits(&s->gb, mb_num_bits); if (mb_num >= s->mb_num || !mb_num) { av_log(s->avctx, AV_LOG_ERROR, "illegal mb_num in video packet (%d %d) \n", mb_num, s->mb_num); return AVERROR_INVALIDDATA; } s->mb_x = mb_num % s->mb_width; s->mb_y = mb_num / s->mb_width; if (ctx->shape != BIN_ONLY_SHAPE) { int qscale = get_bits(&s->gb, s->quant_precision); if (qscale) s->chroma_qscale = s->qscale = qscale; } if (ctx->shape == RECT_SHAPE) header_extension = get_bits1(&s->gb); if (header_extension) { int time_incr = 0; while (get_bits1(&s->gb) != 0) time_incr++; check_marker(s->avctx, &s->gb, "before time_increment in video packed header"); skip_bits(&s->gb, ctx->time_increment_bits); /* time_increment */ check_marker(s->avctx, &s->gb, "before vop_coding_type in video packed header"); skip_bits(&s->gb, 2); /* vop coding type */ // FIXME not rect stuff here if (ctx->shape != BIN_ONLY_SHAPE) { skip_bits(&s->gb, 3); /* intra dc vlc threshold */ // FIXME don't just ignore everything if (s->pict_type == AV_PICTURE_TYPE_S && ctx->vol_sprite_usage == GMC_SPRITE) { if (mpeg4_decode_sprite_trajectory(ctx, &s->gb) < 0) return AVERROR_INVALIDDATA; av_log(s->avctx, AV_LOG_ERROR, "untested\n"); } // FIXME reduced res stuff here if (s->pict_type != AV_PICTURE_TYPE_I) { int f_code = get_bits(&s->gb, 3); /* fcode_for */ if (f_code == 0) av_log(s->avctx, AV_LOG_ERROR, "Error, video packet header damaged (f_code=0)\n"); } if (s->pict_type == AV_PICTURE_TYPE_B) { int b_code = get_bits(&s->gb, 3); if (b_code == 0) av_log(s->avctx, AV_LOG_ERROR, "Error, video packet header damaged (b_code=0)\n"); } } } if (ctx->new_pred) decode_new_pred(ctx, &s->gb); return 0; } static void reset_studio_dc_predictors(MpegEncContext *s) { /* Reset DC Predictors */ s->last_dc[0] = s->last_dc[1] = s->last_dc[2] = 1 << (s->avctx->bits_per_raw_sample + s->dct_precision + s->intra_dc_precision - 1); } /** * Decode the next video packet. * @return <0 if something went wrong */ int ff_mpeg4_decode_studio_slice_header(Mpeg4DecContext *ctx) { MpegEncContext *s = &ctx->m; GetBitContext *gb = &s->gb; unsigned vlc_len; uint16_t mb_num; if (get_bits_left(gb) >= 32 && get_bits_long(gb, 32) == SLICE_START_CODE) { vlc_len = av_log2(s->mb_width * s->mb_height) + 1; mb_num = get_bits(gb, vlc_len); if (mb_num >= s->mb_num) return AVERROR_INVALIDDATA; s->mb_x = mb_num % s->mb_width; s->mb_y = mb_num / s->mb_width; if (ctx->shape != BIN_ONLY_SHAPE) s->qscale = mpeg_get_qscale(s); if (get_bits1(gb)) { /* slice_extension_flag */ skip_bits1(gb); /* intra_slice */ skip_bits1(gb); /* slice_VOP_id_enable */ skip_bits(gb, 6); /* slice_VOP_id */ while (get_bits1(gb)) /* extra_bit_slice */ skip_bits(gb, 8); /* extra_information_slice */ } reset_studio_dc_predictors(s); } else { return AVERROR_INVALIDDATA; } return 0; } /** * Get the average motion vector for a GMC MB. * @param n either 0 for the x component or 1 for y * @return the average MV for a GMC MB */ static inline int get_amv(Mpeg4DecContext *ctx, int n) { MpegEncContext *s = &ctx->m; int x, y, mb_v, sum, dx, dy, shift; int len = 1 << (s->f_code + 4); const int a = s->sprite_warping_accuracy; if (s->workaround_bugs & FF_BUG_AMV) len >>= s->quarter_sample; if (s->real_sprite_warping_points == 1) { if (ctx->divx_version == 500 && ctx->divx_build == 413) sum = s->sprite_offset[0][n] / (1 << (a - s->quarter_sample)); else sum = RSHIFT(s->sprite_offset[0][n] * (1 << s->quarter_sample), a); } else { dx = s->sprite_delta[n][0]; dy = s->sprite_delta[n][1]; shift = ctx->sprite_shift[0]; if (n) dy -= 1 << (shift + a + 1); else dx -= 1 << (shift + a + 1); mb_v = s->sprite_offset[0][n] + dx * s->mb_x * 16 + dy * s->mb_y * 16; sum = 0; for (y = 0; y < 16; y++) { int v; v = mb_v + dy * y; // FIXME optimize for (x = 0; x < 16; x++) { sum += v >> shift; v += dx; } } sum = RSHIFT(sum, a + 8 - s->quarter_sample); } if (sum < -len) sum = -len; else if (sum >= len) sum = len - 1; return sum; } /** * Decode the dc value. * @param n block index (0-3 are luma, 4-5 are chroma) * @param dir_ptr the prediction direction will be stored here * @return the quantized dc */ static inline int mpeg4_decode_dc(MpegEncContext *s, int n, int *dir_ptr) { int level, code; if (n < 4) code = get_vlc2(&s->gb, dc_lum.table, DC_VLC_BITS, 1); else code = get_vlc2(&s->gb, dc_chrom.table, DC_VLC_BITS, 1); if (code < 0 || code > 9 /* && s->nbit < 9 */) { av_log(s->avctx, AV_LOG_ERROR, "illegal dc vlc\n"); return AVERROR_INVALIDDATA; } if (code == 0) { level = 0; } else { if (IS_3IV1) { if (code == 1) level = 2 * get_bits1(&s->gb) - 1; else { if (get_bits1(&s->gb)) level = get_bits(&s->gb, code - 1) + (1 << (code - 1)); else level = -get_bits(&s->gb, code - 1) - (1 << (code - 1)); } } else { level = get_xbits(&s->gb, code); } if (code > 8) { if (get_bits1(&s->gb) == 0) { /* marker */ if (s->avctx->err_recognition & (AV_EF_BITSTREAM|AV_EF_COMPLIANT)) { av_log(s->avctx, AV_LOG_ERROR, "dc marker bit missing\n"); return AVERROR_INVALIDDATA; } } } } return ff_mpeg4_pred_dc(s, n, level, dir_ptr, 0); } /** * Decode first partition. * @return number of MBs decoded or <0 if an error occurred */ static int mpeg4_decode_partition_a(Mpeg4DecContext *ctx) { MpegEncContext *s = &ctx->m; int mb_num = 0; static const int8_t quant_tab[4] = { -1, -2, 1, 2 }; /* decode first partition */ s->first_slice_line = 1; for (; s->mb_y < s->mb_height; s->mb_y++) { ff_init_block_index(s); for (; s->mb_x < s->mb_width; s->mb_x++) { const int xy = s->mb_x + s->mb_y * s->mb_stride; int cbpc; int dir = 0; mb_num++; ff_update_block_index(s); if (s->mb_x == s->resync_mb_x && s->mb_y == s->resync_mb_y + 1) s->first_slice_line = 0; if (s->pict_type == AV_PICTURE_TYPE_I) { int i; do { if (show_bits_long(&s->gb, 19) == DC_MARKER) return mb_num - 1; cbpc = get_vlc2(&s->gb, ff_h263_intra_MCBPC_vlc.table, INTRA_MCBPC_VLC_BITS, 2); if (cbpc < 0) { av_log(s->avctx, AV_LOG_ERROR, "mcbpc corrupted at %d %d\n", s->mb_x, s->mb_y); return AVERROR_INVALIDDATA; } } while (cbpc == 8); s->cbp_table[xy] = cbpc & 3; s->current_picture.mb_type[xy] = MB_TYPE_INTRA; s->mb_intra = 1; if (cbpc & 4) ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]); s->current_picture.qscale_table[xy] = s->qscale; s->mbintra_table[xy] = 1; for (i = 0; i < 6; i++) { int dc_pred_dir; int dc = mpeg4_decode_dc(s, i, &dc_pred_dir); if (dc < 0) { av_log(s->avctx, AV_LOG_ERROR, "DC corrupted at %d %d\n", s->mb_x, s->mb_y); return dc; } dir <<= 1; if (dc_pred_dir) dir |= 1; } s->pred_dir_table[xy] = dir; } else { /* P/S_TYPE */ int mx, my, pred_x, pred_y, bits; int16_t *const mot_val = s->current_picture.motion_val[0][s->block_index[0]]; const int stride = s->b8_stride * 2; try_again: bits = show_bits(&s->gb, 17); if (bits == MOTION_MARKER) return mb_num - 1; skip_bits1(&s->gb); if (bits & 0x10000) { /* skip mb */ if (s->pict_type == AV_PICTURE_TYPE_S && ctx->vol_sprite_usage == GMC_SPRITE) { s->current_picture.mb_type[xy] = MB_TYPE_SKIP | MB_TYPE_16x16 | MB_TYPE_GMC | MB_TYPE_L0; mx = get_amv(ctx, 0); my = get_amv(ctx, 1); } else { s->current_picture.mb_type[xy] = MB_TYPE_SKIP | MB_TYPE_16x16 | MB_TYPE_L0; mx = my = 0; } mot_val[0] = mot_val[2] = mot_val[0 + stride] = mot_val[2 + stride] = mx; mot_val[1] = mot_val[3] = mot_val[1 + stride] = mot_val[3 + stride] = my; if (s->mbintra_table[xy]) ff_clean_intra_table_entries(s); continue; } cbpc = get_vlc2(&s->gb, ff_h263_inter_MCBPC_vlc.table, INTER_MCBPC_VLC_BITS, 2); if (cbpc < 0) { av_log(s->avctx, AV_LOG_ERROR, "mcbpc corrupted at %d %d\n", s->mb_x, s->mb_y); return AVERROR_INVALIDDATA; } if (cbpc == 20) goto try_again; s->cbp_table[xy] = cbpc & (8 + 3); // 8 is dquant s->mb_intra = ((cbpc & 4) != 0); if (s->mb_intra) { s->current_picture.mb_type[xy] = MB_TYPE_INTRA; s->mbintra_table[xy] = 1; mot_val[0] = mot_val[2] = mot_val[0 + stride] = mot_val[2 + stride] = 0; mot_val[1] = mot_val[3] = mot_val[1 + stride] = mot_val[3 + stride] = 0; } else { if (s->mbintra_table[xy]) ff_clean_intra_table_entries(s); if (s->pict_type == AV_PICTURE_TYPE_S && ctx->vol_sprite_usage == GMC_SPRITE && (cbpc & 16) == 0) s->mcsel = get_bits1(&s->gb); else s->mcsel = 0; if ((cbpc & 16) == 0) { /* 16x16 motion prediction */ ff_h263_pred_motion(s, 0, 0, &pred_x, &pred_y); if (!s->mcsel) { mx = ff_h263_decode_motion(s, pred_x, s->f_code); if (mx >= 0xffff) return AVERROR_INVALIDDATA; my = ff_h263_decode_motion(s, pred_y, s->f_code); if (my >= 0xffff) return AVERROR_INVALIDDATA; s->current_picture.mb_type[xy] = MB_TYPE_16x16 | MB_TYPE_L0; } else { mx = get_amv(ctx, 0); my = get_amv(ctx, 1); s->current_picture.mb_type[xy] = MB_TYPE_16x16 | MB_TYPE_GMC | MB_TYPE_L0; } mot_val[0] = mot_val[2] = mot_val[0 + stride] = mot_val[2 + stride] = mx; mot_val[1] = mot_val[3] = mot_val[1 + stride] = mot_val[3 + stride] = my; } else { int i; s->current_picture.mb_type[xy] = MB_TYPE_8x8 | MB_TYPE_L0; for (i = 0; i < 4; i++) { int16_t *mot_val = ff_h263_pred_motion(s, i, 0, &pred_x, &pred_y); mx = ff_h263_decode_motion(s, pred_x, s->f_code); if (mx >= 0xffff) return AVERROR_INVALIDDATA; my = ff_h263_decode_motion(s, pred_y, s->f_code); if (my >= 0xffff) return AVERROR_INVALIDDATA; mot_val[0] = mx; mot_val[1] = my; } } } } } s->mb_x = 0; } return mb_num; } /** * decode second partition. * @return <0 if an error occurred */ static int mpeg4_decode_partition_b(MpegEncContext *s, int mb_count) { int mb_num = 0; static const int8_t quant_tab[4] = { -1, -2, 1, 2 }; s->mb_x = s->resync_mb_x; s->first_slice_line = 1; for (s->mb_y = s->resync_mb_y; mb_num < mb_count; s->mb_y++) { ff_init_block_index(s); for (; mb_num < mb_count && s->mb_x < s->mb_width; s->mb_x++) { const int xy = s->mb_x + s->mb_y * s->mb_stride; mb_num++; ff_update_block_index(s); if (s->mb_x == s->resync_mb_x && s->mb_y == s->resync_mb_y + 1) s->first_slice_line = 0; if (s->pict_type == AV_PICTURE_TYPE_I) { int ac_pred = get_bits1(&s->gb); int cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1); if (cbpy < 0) { av_log(s->avctx, AV_LOG_ERROR, "cbpy corrupted at %d %d\n", s->mb_x, s->mb_y); return AVERROR_INVALIDDATA; } s->cbp_table[xy] |= cbpy << 2; s->current_picture.mb_type[xy] |= ac_pred * MB_TYPE_ACPRED; } else { /* P || S_TYPE */ if (IS_INTRA(s->current_picture.mb_type[xy])) { int i; int dir = 0; int ac_pred = get_bits1(&s->gb); int cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1); if (cbpy < 0) { av_log(s->avctx, AV_LOG_ERROR, "I cbpy corrupted at %d %d\n", s->mb_x, s->mb_y); return AVERROR_INVALIDDATA; } if (s->cbp_table[xy] & 8) ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]); s->current_picture.qscale_table[xy] = s->qscale; for (i = 0; i < 6; i++) { int dc_pred_dir; int dc = mpeg4_decode_dc(s, i, &dc_pred_dir); if (dc < 0) { av_log(s->avctx, AV_LOG_ERROR, "DC corrupted at %d %d\n", s->mb_x, s->mb_y); return dc; } dir <<= 1; if (dc_pred_dir) dir |= 1; } s->cbp_table[xy] &= 3; // remove dquant s->cbp_table[xy] |= cbpy << 2; s->current_picture.mb_type[xy] |= ac_pred * MB_TYPE_ACPRED; s->pred_dir_table[xy] = dir; } else if (IS_SKIP(s->current_picture.mb_type[xy])) { s->current_picture.qscale_table[xy] = s->qscale; s->cbp_table[xy] = 0; } else { int cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1); if (cbpy < 0) { av_log(s->avctx, AV_LOG_ERROR, "P cbpy corrupted at %d %d\n", s->mb_x, s->mb_y); return AVERROR_INVALIDDATA; } if (s->cbp_table[xy] & 8) ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]); s->current_picture.qscale_table[xy] = s->qscale; s->cbp_table[xy] &= 3; // remove dquant s->cbp_table[xy] |= (cbpy ^ 0xf) << 2; } } } if (mb_num >= mb_count) return 0; s->mb_x = 0; } return 0; } /** * Decode the first and second partition. * @return <0 if error (and sets error type in the error_status_table) */ int ff_mpeg4_decode_partitions(Mpeg4DecContext *ctx) { MpegEncContext *s = &ctx->m; int mb_num; int ret; const int part_a_error = s->pict_type == AV_PICTURE_TYPE_I ? (ER_DC_ERROR | ER_MV_ERROR) : ER_MV_ERROR; const int part_a_end = s->pict_type == AV_PICTURE_TYPE_I ? (ER_DC_END | ER_MV_END) : ER_MV_END; mb_num = mpeg4_decode_partition_a(ctx); if (mb_num <= 0) { ff_er_add_slice(&s->er, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, part_a_error); return mb_num ? mb_num : AVERROR_INVALIDDATA; } if (s->resync_mb_x + s->resync_mb_y * s->mb_width + mb_num > s->mb_num) { av_log(s->avctx, AV_LOG_ERROR, "slice below monitor ...\n"); ff_er_add_slice(&s->er, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, part_a_error); return AVERROR_INVALIDDATA; } s->mb_num_left = mb_num; if (s->pict_type == AV_PICTURE_TYPE_I) { while (show_bits(&s->gb, 9) == 1) skip_bits(&s->gb, 9); if (get_bits_long(&s->gb, 19) != DC_MARKER) { av_log(s->avctx, AV_LOG_ERROR, "marker missing after first I partition at %d %d\n", s->mb_x, s->mb_y); return AVERROR_INVALIDDATA; } } else { while (show_bits(&s->gb, 10) == 1) skip_bits(&s->gb, 10); if (get_bits(&s->gb, 17) != MOTION_MARKER) { av_log(s->avctx, AV_LOG_ERROR, "marker missing after first P partition at %d %d\n", s->mb_x, s->mb_y); return AVERROR_INVALIDDATA; } } ff_er_add_slice(&s->er, s->resync_mb_x, s->resync_mb_y, s->mb_x - 1, s->mb_y, part_a_end); ret = mpeg4_decode_partition_b(s, mb_num); if (ret < 0) { if (s->pict_type == AV_PICTURE_TYPE_P) ff_er_add_slice(&s->er, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, ER_DC_ERROR); return ret; } else { if (s->pict_type == AV_PICTURE_TYPE_P) ff_er_add_slice(&s->er, s->resync_mb_x, s->resync_mb_y, s->mb_x - 1, s->mb_y, ER_DC_END); } return 0; } /** * Decode a block. * @return <0 if an error occurred */ static inline int mpeg4_decode_block(Mpeg4DecContext *ctx, int16_t *block, int n, int coded, int intra, int rvlc) { MpegEncContext *s = &ctx->m; int level, i, last, run, qmul, qadd; int av_uninit(dc_pred_dir); RLTable *rl; RL_VLC_ELEM *rl_vlc; const uint8_t *scan_table; // Note intra & rvlc should be optimized away if this is inlined if (intra) { if (ctx->use_intra_dc_vlc) { /* DC coef */ if (s->partitioned_frame) { level = s->dc_val[0][s->block_index[n]]; if (n < 4) level = FASTDIV((level + (s->y_dc_scale >> 1)), s->y_dc_scale); else level = FASTDIV((level + (s->c_dc_scale >> 1)), s->c_dc_scale); dc_pred_dir = (s->pred_dir_table[s->mb_x + s->mb_y * s->mb_stride] << n) & 32; } else { level = mpeg4_decode_dc(s, n, &dc_pred_dir); if (level < 0) return level; } block[0] = level; i = 0; } else { i = -1; ff_mpeg4_pred_dc(s, n, 0, &dc_pred_dir, 0); } if (!coded) goto not_coded; if (rvlc) { rl = &ff_rvlc_rl_intra; rl_vlc = ff_rvlc_rl_intra.rl_vlc[0]; } else { rl = &ff_mpeg4_rl_intra; rl_vlc = ff_mpeg4_rl_intra.rl_vlc[0]; } if (s->ac_pred) { if (dc_pred_dir == 0) scan_table = s->intra_v_scantable.permutated; /* left */ else scan_table = s->intra_h_scantable.permutated; /* top */ } else { scan_table = s->intra_scantable.permutated; } qmul = 1; qadd = 0; } else { i = -1; if (!coded) { s->block_last_index[n] = i; return 0; } if (rvlc) rl = &ff_rvlc_rl_inter; else rl = &ff_h263_rl_inter; scan_table = s->intra_scantable.permutated; if (s->mpeg_quant) { qmul = 1; qadd = 0; if (rvlc) rl_vlc = ff_rvlc_rl_inter.rl_vlc[0]; else rl_vlc = ff_h263_rl_inter.rl_vlc[0]; } else { qmul = s->qscale << 1; qadd = (s->qscale - 1) | 1; if (rvlc) rl_vlc = ff_rvlc_rl_inter.rl_vlc[s->qscale]; else rl_vlc = ff_h263_rl_inter.rl_vlc[s->qscale]; } } { OPEN_READER(re, &s->gb); for (;;) { UPDATE_CACHE(re, &s->gb); GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2, 0); if (level == 0) { /* escape */ if (rvlc) { if (SHOW_UBITS(re, &s->gb, 1) == 0) { av_log(s->avctx, AV_LOG_ERROR, "1. marker bit missing in rvlc esc\n"); return AVERROR_INVALIDDATA; } SKIP_CACHE(re, &s->gb, 1); last = SHOW_UBITS(re, &s->gb, 1); SKIP_CACHE(re, &s->gb, 1); run = SHOW_UBITS(re, &s->gb, 6); SKIP_COUNTER(re, &s->gb, 1 + 1 + 6); UPDATE_CACHE(re, &s->gb); if (SHOW_UBITS(re, &s->gb, 1) == 0) { av_log(s->avctx, AV_LOG_ERROR, "2. marker bit missing in rvlc esc\n"); return AVERROR_INVALIDDATA; } SKIP_CACHE(re, &s->gb, 1); level = SHOW_UBITS(re, &s->gb, 11); SKIP_CACHE(re, &s->gb, 11); if (SHOW_UBITS(re, &s->gb, 5) != 0x10) { av_log(s->avctx, AV_LOG_ERROR, "reverse esc missing\n"); return AVERROR_INVALIDDATA; } SKIP_CACHE(re, &s->gb, 5); level = level * qmul + qadd; level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1); SKIP_COUNTER(re, &s->gb, 1 + 11 + 5 + 1); i += run + 1; if (last) i += 192; } else { int cache; cache = GET_CACHE(re, &s->gb); if (IS_3IV1) cache ^= 0xC0000000; if (cache & 0x80000000) { if (cache & 0x40000000) { /* third escape */ SKIP_CACHE(re, &s->gb, 2); last = SHOW_UBITS(re, &s->gb, 1); SKIP_CACHE(re, &s->gb, 1); run = SHOW_UBITS(re, &s->gb, 6); SKIP_COUNTER(re, &s->gb, 2 + 1 + 6); UPDATE_CACHE(re, &s->gb); if (IS_3IV1) { level = SHOW_SBITS(re, &s->gb, 12); LAST_SKIP_BITS(re, &s->gb, 12); } else { if (SHOW_UBITS(re, &s->gb, 1) == 0) { av_log(s->avctx, AV_LOG_ERROR, "1. marker bit missing in 3. esc\n"); if (!(s->avctx->err_recognition & AV_EF_IGNORE_ERR)) return AVERROR_INVALIDDATA; } SKIP_CACHE(re, &s->gb, 1); level = SHOW_SBITS(re, &s->gb, 12); SKIP_CACHE(re, &s->gb, 12); if (SHOW_UBITS(re, &s->gb, 1) == 0) { av_log(s->avctx, AV_LOG_ERROR, "2. marker bit missing in 3. esc\n"); if (!(s->avctx->err_recognition & AV_EF_IGNORE_ERR)) return AVERROR_INVALIDDATA; } SKIP_COUNTER(re, &s->gb, 1 + 12 + 1); } #if 0 if (s->error_recognition >= FF_ER_COMPLIANT) { const int abs_level= FFABS(level); if (abs_level<=MAX_LEVEL && run<=MAX_RUN) { const int run1= run - rl->max_run[last][abs_level] - 1; if (abs_level <= rl->max_level[last][run]) { av_log(s->avctx, AV_LOG_ERROR, "illegal 3. esc, vlc encoding possible\n"); return AVERROR_INVALIDDATA; } if (s->error_recognition > FF_ER_COMPLIANT) { if (abs_level <= rl->max_level[last][run]*2) { av_log(s->avctx, AV_LOG_ERROR, "illegal 3. esc, esc 1 encoding possible\n"); return AVERROR_INVALIDDATA; } if (run1 >= 0 && abs_level <= rl->max_level[last][run1]) { av_log(s->avctx, AV_LOG_ERROR, "illegal 3. esc, esc 2 encoding possible\n"); return AVERROR_INVALIDDATA; } } } } #endif if (level > 0) level = level * qmul + qadd; else level = level * qmul - qadd; if ((unsigned)(level + 2048) > 4095) { if (s->avctx->err_recognition & (AV_EF_BITSTREAM|AV_EF_AGGRESSIVE)) { if (level > 2560 || level < -2560) { av_log(s->avctx, AV_LOG_ERROR, "|level| overflow in 3. esc, qp=%d\n", s->qscale); return AVERROR_INVALIDDATA; } } level = level < 0 ? -2048 : 2047; } i += run + 1; if (last) i += 192; } else { /* second escape */ SKIP_BITS(re, &s->gb, 2); GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2, 1); i += run + rl->max_run[run >> 7][level / qmul] + 1; // FIXME opt indexing level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1); LAST_SKIP_BITS(re, &s->gb, 1); } } else { /* first escape */ SKIP_BITS(re, &s->gb, 1); GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2, 1); i += run; level = level + rl->max_level[run >> 7][(run - 1) & 63] * qmul; // FIXME opt indexing level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1); LAST_SKIP_BITS(re, &s->gb, 1); } } } else { i += run; level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1); LAST_SKIP_BITS(re, &s->gb, 1); } ff_tlog(s->avctx, "dct[%d][%d] = %- 4d end?:%d\n", scan_table[i&63]&7, scan_table[i&63] >> 3, level, i>62); if (i > 62) { i -= 192; if (i & (~63)) { av_log(s->avctx, AV_LOG_ERROR, "ac-tex damaged at %d %d\n", s->mb_x, s->mb_y); return AVERROR_INVALIDDATA; } block[scan_table[i]] = level; break; } block[scan_table[i]] = level; } CLOSE_READER(re, &s->gb); } not_coded: if (intra) { if (!ctx->use_intra_dc_vlc) { block[0] = ff_mpeg4_pred_dc(s, n, block[0], &dc_pred_dir, 0); i -= i >> 31; // if (i == -1) i = 0; } ff_mpeg4_pred_ac(s, block, n, dc_pred_dir); if (s->ac_pred) i = 63; // FIXME not optimal } s->block_last_index[n] = i; return 0; } /** * decode partition C of one MB. * @return <0 if an error occurred */ static int mpeg4_decode_partitioned_mb(MpegEncContext *s, int16_t block[6][64]) { Mpeg4DecContext *ctx = s->avctx->priv_data; int cbp, mb_type; const int xy = s->mb_x + s->mb_y * s->mb_stride; av_assert2(s == (void*)ctx); mb_type = s->current_picture.mb_type[xy]; cbp = s->cbp_table[xy]; ctx->use_intra_dc_vlc = s->qscale < ctx->intra_dc_threshold; if (s->current_picture.qscale_table[xy] != s->qscale) ff_set_qscale(s, s->current_picture.qscale_table[xy]); if (s->pict_type == AV_PICTURE_TYPE_P || s->pict_type == AV_PICTURE_TYPE_S) { int i; for (i = 0; i < 4; i++) { s->mv[0][i][0] = s->current_picture.motion_val[0][s->block_index[i]][0]; s->mv[0][i][1] = s->current_picture.motion_val[0][s->block_index[i]][1]; } s->mb_intra = IS_INTRA(mb_type); if (IS_SKIP(mb_type)) { /* skip mb */ for (i = 0; i < 6; i++) s->block_last_index[i] = -1; s->mv_dir = MV_DIR_FORWARD; s->mv_type = MV_TYPE_16X16; if (s->pict_type == AV_PICTURE_TYPE_S && ctx->vol_sprite_usage == GMC_SPRITE) { s->mcsel = 1; s->mb_skipped = 0; } else { s->mcsel = 0; s->mb_skipped = 1; } } else if (s->mb_intra) { s->ac_pred = IS_ACPRED(s->current_picture.mb_type[xy]); } else if (!s->mb_intra) { // s->mcsel = 0; // FIXME do we need to init that? s->mv_dir = MV_DIR_FORWARD; if (IS_8X8(mb_type)) { s->mv_type = MV_TYPE_8X8; } else { s->mv_type = MV_TYPE_16X16; } } } else { /* I-Frame */ s->mb_intra = 1; s->ac_pred = IS_ACPRED(s->current_picture.mb_type[xy]); } if (!IS_SKIP(mb_type)) { int i; s->bdsp.clear_blocks(s->block[0]); /* decode each block */ for (i = 0; i < 6; i++) { if (mpeg4_decode_block(ctx, block[i], i, cbp & 32, s->mb_intra, ctx->rvlc) < 0) { av_log(s->avctx, AV_LOG_ERROR, "texture corrupted at %d %d %d\n", s->mb_x, s->mb_y, s->mb_intra); return AVERROR_INVALIDDATA; } cbp += cbp; } } /* per-MB end of slice check */ if (--s->mb_num_left <= 0) { if (mpeg4_is_resync(ctx)) return SLICE_END; else return SLICE_NOEND; } else { if (mpeg4_is_resync(ctx)) { const int delta = s->mb_x + 1 == s->mb_width ? 2 : 1; if (s->cbp_table[xy + delta]) return SLICE_END; } return SLICE_OK; } } static int mpeg4_decode_mb(MpegEncContext *s, int16_t block[6][64]) { Mpeg4DecContext *ctx = s->avctx->priv_data; int cbpc, cbpy, i, cbp, pred_x, pred_y, mx, my, dquant; int16_t *mot_val; static const int8_t quant_tab[4] = { -1, -2, 1, 2 }; const int xy = s->mb_x + s->mb_y * s->mb_stride; av_assert2(s == (void*)ctx); av_assert2(s->h263_pred); if (s->pict_type == AV_PICTURE_TYPE_P || s->pict_type == AV_PICTURE_TYPE_S) { do { if (get_bits1(&s->gb)) { /* skip mb */ s->mb_intra = 0; for (i = 0; i < 6; i++) s->block_last_index[i] = -1; s->mv_dir = MV_DIR_FORWARD; s->mv_type = MV_TYPE_16X16; if (s->pict_type == AV_PICTURE_TYPE_S && ctx->vol_sprite_usage == GMC_SPRITE) { s->current_picture.mb_type[xy] = MB_TYPE_SKIP | MB_TYPE_GMC | MB_TYPE_16x16 | MB_TYPE_L0; s->mcsel = 1; s->mv[0][0][0] = get_amv(ctx, 0); s->mv[0][0][1] = get_amv(ctx, 1); s->mb_skipped = 0; } else { s->current_picture.mb_type[xy] = MB_TYPE_SKIP | MB_TYPE_16x16 | MB_TYPE_L0; s->mcsel = 0; s->mv[0][0][0] = 0; s->mv[0][0][1] = 0; s->mb_skipped = 1; } goto end; } cbpc = get_vlc2(&s->gb, ff_h263_inter_MCBPC_vlc.table, INTER_MCBPC_VLC_BITS, 2); if (cbpc < 0) { av_log(s->avctx, AV_LOG_ERROR, "mcbpc damaged at %d %d\n", s->mb_x, s->mb_y); return AVERROR_INVALIDDATA; } } while (cbpc == 20); s->bdsp.clear_blocks(s->block[0]); dquant = cbpc & 8; s->mb_intra = ((cbpc & 4) != 0); if (s->mb_intra) goto intra; if (s->pict_type == AV_PICTURE_TYPE_S && ctx->vol_sprite_usage == GMC_SPRITE && (cbpc & 16) == 0) s->mcsel = get_bits1(&s->gb); else s->mcsel = 0; cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1) ^ 0x0F; if (cbpy < 0) { av_log(s->avctx, AV_LOG_ERROR, "P cbpy damaged at %d %d\n", s->mb_x, s->mb_y); return AVERROR_INVALIDDATA; } cbp = (cbpc & 3) | (cbpy << 2); if (dquant) ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]); if ((!s->progressive_sequence) && (cbp || (s->workaround_bugs & FF_BUG_XVID_ILACE))) s->interlaced_dct = get_bits1(&s->gb); s->mv_dir = MV_DIR_FORWARD; if ((cbpc & 16) == 0) { if (s->mcsel) { s->current_picture.mb_type[xy] = MB_TYPE_GMC | MB_TYPE_16x16 | MB_TYPE_L0; /* 16x16 global motion prediction */ s->mv_type = MV_TYPE_16X16; mx = get_amv(ctx, 0); my = get_amv(ctx, 1); s->mv[0][0][0] = mx; s->mv[0][0][1] = my; } else if ((!s->progressive_sequence) && get_bits1(&s->gb)) { s->current_picture.mb_type[xy] = MB_TYPE_16x8 | MB_TYPE_L0 | MB_TYPE_INTERLACED; /* 16x8 field motion prediction */ s->mv_type = MV_TYPE_FIELD; s->field_select[0][0] = get_bits1(&s->gb); s->field_select[0][1] = get_bits1(&s->gb); ff_h263_pred_motion(s, 0, 0, &pred_x, &pred_y); for (i = 0; i < 2; i++) { mx = ff_h263_decode_motion(s, pred_x, s->f_code); if (mx >= 0xffff) return AVERROR_INVALIDDATA; my = ff_h263_decode_motion(s, pred_y / 2, s->f_code); if (my >= 0xffff) return AVERROR_INVALIDDATA; s->mv[0][i][0] = mx; s->mv[0][i][1] = my; } } else { s->current_picture.mb_type[xy] = MB_TYPE_16x16 | MB_TYPE_L0; /* 16x16 motion prediction */ s->mv_type = MV_TYPE_16X16; ff_h263_pred_motion(s, 0, 0, &pred_x, &pred_y); mx = ff_h263_decode_motion(s, pred_x, s->f_code); if (mx >= 0xffff) return AVERROR_INVALIDDATA; my = ff_h263_decode_motion(s, pred_y, s->f_code); if (my >= 0xffff) return AVERROR_INVALIDDATA; s->mv[0][0][0] = mx; s->mv[0][0][1] = my; } } else { s->current_picture.mb_type[xy] = MB_TYPE_8x8 | MB_TYPE_L0; s->mv_type = MV_TYPE_8X8; for (i = 0; i < 4; i++) { mot_val = ff_h263_pred_motion(s, i, 0, &pred_x, &pred_y); mx = ff_h263_decode_motion(s, pred_x, s->f_code); if (mx >= 0xffff) return AVERROR_INVALIDDATA; my = ff_h263_decode_motion(s, pred_y, s->f_code); if (my >= 0xffff) return AVERROR_INVALIDDATA; s->mv[0][i][0] = mx; s->mv[0][i][1] = my; mot_val[0] = mx; mot_val[1] = my; } } } else if (s->pict_type == AV_PICTURE_TYPE_B) { int modb1; // first bit of modb int modb2; // second bit of modb int mb_type; s->mb_intra = 0; // B-frames never contain intra blocks s->mcsel = 0; // ... true gmc blocks if (s->mb_x == 0) { for (i = 0; i < 2; i++) { s->last_mv[i][0][0] = s->last_mv[i][0][1] = s->last_mv[i][1][0] = s->last_mv[i][1][1] = 0; } ff_thread_await_progress(&s->next_picture_ptr->tf, s->mb_y, 0); } /* if we skipped it in the future P-frame than skip it now too */ s->mb_skipped = s->next_picture.mbskip_table[s->mb_y * s->mb_stride + s->mb_x]; // Note, skiptab=0 if last was GMC if (s->mb_skipped) { /* skip mb */ for (i = 0; i < 6; i++) s->block_last_index[i] = -1; s->mv_dir = MV_DIR_FORWARD; s->mv_type = MV_TYPE_16X16; s->mv[0][0][0] = s->mv[0][0][1] = s->mv[1][0][0] = s->mv[1][0][1] = 0; s->current_picture.mb_type[xy] = MB_TYPE_SKIP | MB_TYPE_16x16 | MB_TYPE_L0; goto end; } modb1 = get_bits1(&s->gb); if (modb1) { // like MB_TYPE_B_DIRECT but no vectors coded mb_type = MB_TYPE_DIRECT2 | MB_TYPE_SKIP | MB_TYPE_L0L1; cbp = 0; } else { modb2 = get_bits1(&s->gb); mb_type = get_vlc2(&s->gb, mb_type_b_vlc.table, MB_TYPE_B_VLC_BITS, 1); if (mb_type < 0) { av_log(s->avctx, AV_LOG_ERROR, "illegal MB_type\n"); return AVERROR_INVALIDDATA; } mb_type = mb_type_b_map[mb_type]; if (modb2) { cbp = 0; } else { s->bdsp.clear_blocks(s->block[0]); cbp = get_bits(&s->gb, 6); } if ((!IS_DIRECT(mb_type)) && cbp) { if (get_bits1(&s->gb)) ff_set_qscale(s, s->qscale + get_bits1(&s->gb) * 4 - 2); } if (!s->progressive_sequence) { if (cbp) s->interlaced_dct = get_bits1(&s->gb); if (!IS_DIRECT(mb_type) && get_bits1(&s->gb)) { mb_type |= MB_TYPE_16x8 | MB_TYPE_INTERLACED; mb_type &= ~MB_TYPE_16x16; if (USES_LIST(mb_type, 0)) { s->field_select[0][0] = get_bits1(&s->gb); s->field_select[0][1] = get_bits1(&s->gb); } if (USES_LIST(mb_type, 1)) { s->field_select[1][0] = get_bits1(&s->gb); s->field_select[1][1] = get_bits1(&s->gb); } } } s->mv_dir = 0; if ((mb_type & (MB_TYPE_DIRECT2 | MB_TYPE_INTERLACED)) == 0) { s->mv_type = MV_TYPE_16X16; if (USES_LIST(mb_type, 0)) { s->mv_dir = MV_DIR_FORWARD; mx = ff_h263_decode_motion(s, s->last_mv[0][0][0], s->f_code); my = ff_h263_decode_motion(s, s->last_mv[0][0][1], s->f_code); s->last_mv[0][1][0] = s->last_mv[0][0][0] = s->mv[0][0][0] = mx; s->last_mv[0][1][1] = s->last_mv[0][0][1] = s->mv[0][0][1] = my; } if (USES_LIST(mb_type, 1)) { s->mv_dir |= MV_DIR_BACKWARD; mx = ff_h263_decode_motion(s, s->last_mv[1][0][0], s->b_code); my = ff_h263_decode_motion(s, s->last_mv[1][0][1], s->b_code); s->last_mv[1][1][0] = s->last_mv[1][0][0] = s->mv[1][0][0] = mx; s->last_mv[1][1][1] = s->last_mv[1][0][1] = s->mv[1][0][1] = my; } } else if (!IS_DIRECT(mb_type)) { s->mv_type = MV_TYPE_FIELD; if (USES_LIST(mb_type, 0)) { s->mv_dir = MV_DIR_FORWARD; for (i = 0; i < 2; i++) { mx = ff_h263_decode_motion(s, s->last_mv[0][i][0], s->f_code); my = ff_h263_decode_motion(s, s->last_mv[0][i][1] / 2, s->f_code); s->last_mv[0][i][0] = s->mv[0][i][0] = mx; s->last_mv[0][i][1] = (s->mv[0][i][1] = my) * 2; } } if (USES_LIST(mb_type, 1)) { s->mv_dir |= MV_DIR_BACKWARD; for (i = 0; i < 2; i++) { mx = ff_h263_decode_motion(s, s->last_mv[1][i][0], s->b_code); my = ff_h263_decode_motion(s, s->last_mv[1][i][1] / 2, s->b_code); s->last_mv[1][i][0] = s->mv[1][i][0] = mx; s->last_mv[1][i][1] = (s->mv[1][i][1] = my) * 2; } } } } if (IS_DIRECT(mb_type)) { if (IS_SKIP(mb_type)) { mx = my = 0; } else { mx = ff_h263_decode_motion(s, 0, 1); my = ff_h263_decode_motion(s, 0, 1); } s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD | MV_DIRECT; mb_type |= ff_mpeg4_set_direct_mv(s, mx, my); } s->current_picture.mb_type[xy] = mb_type; } else { /* I-Frame */ do { cbpc = get_vlc2(&s->gb, ff_h263_intra_MCBPC_vlc.table, INTRA_MCBPC_VLC_BITS, 2); if (cbpc < 0) { av_log(s->avctx, AV_LOG_ERROR, "I cbpc damaged at %d %d\n", s->mb_x, s->mb_y); return AVERROR_INVALIDDATA; } } while (cbpc == 8); dquant = cbpc & 4; s->mb_intra = 1; intra: s->ac_pred = get_bits1(&s->gb); if (s->ac_pred) s->current_picture.mb_type[xy] = MB_TYPE_INTRA | MB_TYPE_ACPRED; else s->current_picture.mb_type[xy] = MB_TYPE_INTRA; cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1); if (cbpy < 0) { av_log(s->avctx, AV_LOG_ERROR, "I cbpy damaged at %d %d\n", s->mb_x, s->mb_y); return AVERROR_INVALIDDATA; } cbp = (cbpc & 3) | (cbpy << 2); ctx->use_intra_dc_vlc = s->qscale < ctx->intra_dc_threshold; if (dquant) ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]); if (!s->progressive_sequence) s->interlaced_dct = get_bits1(&s->gb); s->bdsp.clear_blocks(s->block[0]); /* decode each block */ for (i = 0; i < 6; i++) { if (mpeg4_decode_block(ctx, block[i], i, cbp & 32, 1, 0) < 0) return AVERROR_INVALIDDATA; cbp += cbp; } goto end; } /* decode each block */ for (i = 0; i < 6; i++) { if (mpeg4_decode_block(ctx, block[i], i, cbp & 32, 0, 0) < 0) return AVERROR_INVALIDDATA; cbp += cbp; } end: /* per-MB end of slice check */ if (s->codec_id == AV_CODEC_ID_MPEG4) { int next = mpeg4_is_resync(ctx); if (next) { if (s->mb_x + s->mb_y*s->mb_width + 1 > next && (s->avctx->err_recognition & AV_EF_AGGRESSIVE)) { return AVERROR_INVALIDDATA; } else if (s->mb_x + s->mb_y*s->mb_width + 1 >= next) return SLICE_END; if (s->pict_type == AV_PICTURE_TYPE_B) { const int delta= s->mb_x + 1 == s->mb_width ? 2 : 1; ff_thread_await_progress(&s->next_picture_ptr->tf, (s->mb_x + delta >= s->mb_width) ? FFMIN(s->mb_y + 1, s->mb_height - 1) : s->mb_y, 0); if (s->next_picture.mbskip_table[xy + delta]) return SLICE_OK; } return SLICE_END; } } return SLICE_OK; } /* As per spec, studio start code search isn't the same as the old type of start code */ static void next_start_code_studio(GetBitContext *gb) { align_get_bits(gb); while (get_bits_left(gb) >= 24 && show_bits_long(gb, 24) != 0x1) { get_bits(gb, 8); } } /* additional_code, vlc index */ static const uint8_t ac_state_tab[22][2] = { {0, 0}, {0, 1}, {1, 1}, {2, 1}, {3, 1}, {4, 1}, {5, 1}, {1, 2}, {2, 2}, {3, 2}, {4, 2}, {5, 2}, {6, 2}, {1, 3}, {2, 4}, {3, 5}, {4, 6}, {5, 7}, {6, 8}, {7, 9}, {8, 10}, {0, 11} }; static int mpeg4_decode_studio_block(MpegEncContext *s, int32_t block[64], int n) { Mpeg4DecContext *ctx = s->avctx->priv_data; int cc, dct_dc_size, dct_diff, code, j, idx = 1, group = 0, run = 0, additional_code_len, sign, mismatch; VLC *cur_vlc = &ctx->studio_intra_tab[0]; uint8_t *const scantable = s->intra_scantable.permutated; const uint16_t *quant_matrix; uint32_t flc; const int min = -1 * (1 << (s->avctx->bits_per_raw_sample + 6)); const int max = ((1 << (s->avctx->bits_per_raw_sample + 6)) - 1); mismatch = 1; memset(block, 0, 64 * sizeof(int32_t)); if (n < 4) { cc = 0; dct_dc_size = get_vlc2(&s->gb, ctx->studio_luma_dc.table, STUDIO_INTRA_BITS, 2); quant_matrix = s->intra_matrix; } else { cc = (n & 1) + 1; if (ctx->rgb) dct_dc_size = get_vlc2(&s->gb, ctx->studio_luma_dc.table, STUDIO_INTRA_BITS, 2); else dct_dc_size = get_vlc2(&s->gb, ctx->studio_chroma_dc.table, STUDIO_INTRA_BITS, 2); quant_matrix = s->chroma_intra_matrix; } if (dct_dc_size < 0) { av_log(s->avctx, AV_LOG_ERROR, "illegal dct_dc_size vlc\n"); return AVERROR_INVALIDDATA; } else if (dct_dc_size == 0) { dct_diff = 0; } else { dct_diff = get_xbits(&s->gb, dct_dc_size); if (dct_dc_size > 8) { if(!check_marker(s->avctx, &s->gb, "dct_dc_size > 8")) return AVERROR_INVALIDDATA; } } s->last_dc[cc] += dct_diff; if (s->mpeg_quant) block[0] = s->last_dc[cc] * (8 >> s->intra_dc_precision); else block[0] = s->last_dc[cc] * (8 >> s->intra_dc_precision) * (8 >> s->dct_precision); /* TODO: support mpeg_quant for AC coefficients */ block[0] = av_clip(block[0], min, max); mismatch ^= block[0]; /* AC Coefficients */ while (1) { group = get_vlc2(&s->gb, cur_vlc->table, STUDIO_INTRA_BITS, 2); if (group < 0) { av_log(s->avctx, AV_LOG_ERROR, "illegal ac coefficient group vlc\n"); return AVERROR_INVALIDDATA; } additional_code_len = ac_state_tab[group][0]; cur_vlc = &ctx->studio_intra_tab[ac_state_tab[group][1]]; if (group == 0) { /* End of Block */ break; } else if (group >= 1 && group <= 6) { /* Zero run length (Table B.47) */ run = 1 << additional_code_len; if (additional_code_len) run += get_bits(&s->gb, additional_code_len); idx += run; continue; } else if (group >= 7 && group <= 12) { /* Zero run length and +/-1 level (Table B.48) */ code = get_bits(&s->gb, additional_code_len); sign = code & 1; code >>= 1; run = (1 << (additional_code_len - 1)) + code; idx += run; j = scantable[idx++]; block[j] = sign ? 1 : -1; } else if (group >= 13 && group <= 20) { /* Level value (Table B.49) */ j = scantable[idx++]; block[j] = get_xbits(&s->gb, additional_code_len); } else if (group == 21) { /* Escape */ j = scantable[idx++]; additional_code_len = s->avctx->bits_per_raw_sample + s->dct_precision + 4; flc = get_bits(&s->gb, additional_code_len); if (flc >> (additional_code_len-1)) block[j] = -1 * (( flc ^ ((1 << additional_code_len) -1)) + 1); else block[j] = flc; } block[j] = ((8 * 2 * block[j] * quant_matrix[j] * s->qscale) >> s->dct_precision) / 32; block[j] = av_clip(block[j], min, max); mismatch ^= block[j]; } block[63] ^= mismatch & 1; return 0; } static int mpeg4_decode_studio_mb(MpegEncContext *s, int16_t block_[12][64]) { int i; /* StudioMacroblock */ /* Assumes I-VOP */ s->mb_intra = 1; if (get_bits1(&s->gb)) { /* compression_mode */ /* DCT */ /* macroblock_type, 1 or 2-bit VLC */ if (!get_bits1(&s->gb)) { skip_bits1(&s->gb); s->qscale = mpeg_get_qscale(s); } for (i = 0; i < mpeg4_block_count[s->chroma_format]; i++) { if (mpeg4_decode_studio_block(s, (*s->block32)[i], i) < 0) return AVERROR_INVALIDDATA; } } else { /* DPCM */ check_marker(s->avctx, &s->gb, "DPCM block start"); avpriv_request_sample(s->avctx, "DPCM encoded block"); next_start_code_studio(&s->gb); return SLICE_ERROR; } if (get_bits_left(&s->gb) >= 24 && show_bits(&s->gb, 23) == 0) { next_start_code_studio(&s->gb); return SLICE_END; } return SLICE_OK; } static int mpeg4_decode_gop_header(MpegEncContext *s, GetBitContext *gb) { int hours, minutes, seconds; if (!show_bits(gb, 23)) { av_log(s->avctx, AV_LOG_WARNING, "GOP header invalid\n"); return AVERROR_INVALIDDATA; } hours = get_bits(gb, 5); minutes = get_bits(gb, 6); check_marker(s->avctx, gb, "in gop_header"); seconds = get_bits(gb, 6); s->time_base = seconds + 60*(minutes + 60*hours); skip_bits1(gb); skip_bits1(gb); return 0; } static int mpeg4_decode_profile_level(MpegEncContext *s, GetBitContext *gb) { s->avctx->profile = get_bits(gb, 4); s->avctx->level = get_bits(gb, 4); // for Simple profile, level 0 if (s->avctx->profile == 0 && s->avctx->level == 8) { s->avctx->level = 0; } return 0; } static int mpeg4_decode_visual_object(MpegEncContext *s, GetBitContext *gb) { int visual_object_type; int is_visual_object_identifier = get_bits1(gb); if (is_visual_object_identifier) { skip_bits(gb, 4+3); } visual_object_type = get_bits(gb, 4); if (visual_object_type == VOT_VIDEO_ID || visual_object_type == VOT_STILL_TEXTURE_ID) { int video_signal_type = get_bits1(gb); if (video_signal_type) { int video_range, color_description; skip_bits(gb, 3); // video_format video_range = get_bits1(gb); color_description = get_bits1(gb); s->avctx->color_range = video_range ? AVCOL_RANGE_JPEG : AVCOL_RANGE_MPEG; if (color_description) { s->avctx->color_primaries = get_bits(gb, 8); s->avctx->color_trc = get_bits(gb, 8); s->avctx->colorspace = get_bits(gb, 8); } } } return 0; } static void mpeg4_load_default_matrices(MpegEncContext *s) { int i, v; /* load default matrices */ for (i = 0; i < 64; i++) { int j = s->idsp.idct_permutation[i]; v = ff_mpeg4_default_intra_matrix[i]; s->intra_matrix[j] = v; s->chroma_intra_matrix[j] = v; v = ff_mpeg4_default_non_intra_matrix[i]; s->inter_matrix[j] = v; s->chroma_inter_matrix[j] = v; } } static int decode_vol_header(Mpeg4DecContext *ctx, GetBitContext *gb) { MpegEncContext *s = &ctx->m; int width, height, vo_ver_id; /* vol header */ skip_bits(gb, 1); /* random access */ s->vo_type = get_bits(gb, 8); /* If we are in studio profile (per vo_type), check if its all consistent * and if so continue pass control to decode_studio_vol_header(). * elIf something is inconsistent, error out * else continue with (non studio) vol header decpoding. */ if (s->vo_type == CORE_STUDIO_VO_TYPE || s->vo_type == SIMPLE_STUDIO_VO_TYPE) { if (s->avctx->profile != FF_PROFILE_UNKNOWN && s->avctx->profile != FF_PROFILE_MPEG4_SIMPLE_STUDIO) return AVERROR_INVALIDDATA; s->studio_profile = 1; s->avctx->profile = FF_PROFILE_MPEG4_SIMPLE_STUDIO; return decode_studio_vol_header(ctx, gb); } else if (s->studio_profile) { return AVERROR_PATCHWELCOME; } if (get_bits1(gb) != 0) { /* is_ol_id */ vo_ver_id = get_bits(gb, 4); /* vo_ver_id */ skip_bits(gb, 3); /* vo_priority */ } else { vo_ver_id = 1; } s->aspect_ratio_info = get_bits(gb, 4); if (s->aspect_ratio_info == FF_ASPECT_EXTENDED) { s->avctx->sample_aspect_ratio.num = get_bits(gb, 8); // par_width s->avctx->sample_aspect_ratio.den = get_bits(gb, 8); // par_height } else { s->avctx->sample_aspect_ratio = ff_h263_pixel_aspect[s->aspect_ratio_info]; } if ((ctx->vol_control_parameters = get_bits1(gb))) { /* vol control parameter */ int chroma_format = get_bits(gb, 2); if (chroma_format != CHROMA_420) av_log(s->avctx, AV_LOG_ERROR, "illegal chroma format\n"); s->low_delay = get_bits1(gb); if (get_bits1(gb)) { /* vbv parameters */ get_bits(gb, 15); /* first_half_bitrate */ check_marker(s->avctx, gb, "after first_half_bitrate"); get_bits(gb, 15); /* latter_half_bitrate */ check_marker(s->avctx, gb, "after latter_half_bitrate"); get_bits(gb, 15); /* first_half_vbv_buffer_size */ check_marker(s->avctx, gb, "after first_half_vbv_buffer_size"); get_bits(gb, 3); /* latter_half_vbv_buffer_size */ get_bits(gb, 11); /* first_half_vbv_occupancy */ check_marker(s->avctx, gb, "after first_half_vbv_occupancy"); get_bits(gb, 15); /* latter_half_vbv_occupancy */ check_marker(s->avctx, gb, "after latter_half_vbv_occupancy"); } } else { /* is setting low delay flag only once the smartest thing to do? * low delay detection will not be overridden. */ if (s->picture_number == 0) { switch(s->vo_type) { case SIMPLE_VO_TYPE: case ADV_SIMPLE_VO_TYPE: s->low_delay = 1; break; default: s->low_delay = 0; } } } ctx->shape = get_bits(gb, 2); /* vol shape */ if (ctx->shape != RECT_SHAPE) av_log(s->avctx, AV_LOG_ERROR, "only rectangular vol supported\n"); if (ctx->shape == GRAY_SHAPE && vo_ver_id != 1) { av_log(s->avctx, AV_LOG_ERROR, "Gray shape not supported\n"); skip_bits(gb, 4); /* video_object_layer_shape_extension */ } check_marker(s->avctx, gb, "before time_increment_resolution"); s->avctx->framerate.num = get_bits(gb, 16); if (!s->avctx->framerate.num) { av_log(s->avctx, AV_LOG_ERROR, "framerate==0\n"); return AVERROR_INVALIDDATA; } ctx->time_increment_bits = av_log2(s->avctx->framerate.num - 1) + 1; if (ctx->time_increment_bits < 1) ctx->time_increment_bits = 1; check_marker(s->avctx, gb, "before fixed_vop_rate"); if (get_bits1(gb) != 0) /* fixed_vop_rate */ s->avctx->framerate.den = get_bits(gb, ctx->time_increment_bits); else s->avctx->framerate.den = 1; s->avctx->time_base = av_inv_q(av_mul_q(s->avctx->framerate, (AVRational){s->avctx->ticks_per_frame, 1})); ctx->t_frame = 0; if (ctx->shape != BIN_ONLY_SHAPE) { if (ctx->shape == RECT_SHAPE) { check_marker(s->avctx, gb, "before width"); width = get_bits(gb, 13); check_marker(s->avctx, gb, "before height"); height = get_bits(gb, 13); check_marker(s->avctx, gb, "after height"); if (width && height && /* they should be non zero but who knows */ !(s->width && s->codec_tag == AV_RL32("MP4S"))) { if (s->width && s->height && (s->width != width || s->height != height)) s->context_reinit = 1; s->width = width; s->height = height; } } s->progressive_sequence = s->progressive_frame = get_bits1(gb) ^ 1; s->interlaced_dct = 0; if (!get_bits1(gb) && (s->avctx->debug & FF_DEBUG_PICT_INFO)) av_log(s->avctx, AV_LOG_INFO, /* OBMC Disable */ "MPEG-4 OBMC not supported (very likely buggy encoder)\n"); if (vo_ver_id == 1) ctx->vol_sprite_usage = get_bits1(gb); /* vol_sprite_usage */ else ctx->vol_sprite_usage = get_bits(gb, 2); /* vol_sprite_usage */ if (ctx->vol_sprite_usage == STATIC_SPRITE) av_log(s->avctx, AV_LOG_ERROR, "Static Sprites not supported\n"); if (ctx->vol_sprite_usage == STATIC_SPRITE || ctx->vol_sprite_usage == GMC_SPRITE) { if (ctx->vol_sprite_usage == STATIC_SPRITE) { skip_bits(gb, 13); // sprite_width check_marker(s->avctx, gb, "after sprite_width"); skip_bits(gb, 13); // sprite_height check_marker(s->avctx, gb, "after sprite_height"); skip_bits(gb, 13); // sprite_left check_marker(s->avctx, gb, "after sprite_left"); skip_bits(gb, 13); // sprite_top check_marker(s->avctx, gb, "after sprite_top"); } ctx->num_sprite_warping_points = get_bits(gb, 6); if (ctx->num_sprite_warping_points > 3) { av_log(s->avctx, AV_LOG_ERROR, "%d sprite_warping_points\n", ctx->num_sprite_warping_points); ctx->num_sprite_warping_points = 0; return AVERROR_INVALIDDATA; } s->sprite_warping_accuracy = get_bits(gb, 2); ctx->sprite_brightness_change = get_bits1(gb); if (ctx->vol_sprite_usage == STATIC_SPRITE) skip_bits1(gb); // low_latency_sprite } // FIXME sadct disable bit if verid!=1 && shape not rect if (get_bits1(gb) == 1) { /* not_8_bit */ s->quant_precision = get_bits(gb, 4); /* quant_precision */ if (get_bits(gb, 4) != 8) /* bits_per_pixel */ av_log(s->avctx, AV_LOG_ERROR, "N-bit not supported\n"); if (s->quant_precision != 5) av_log(s->avctx, AV_LOG_ERROR, "quant precision %d\n", s->quant_precision); if (s->quant_precision<3 || s->quant_precision>9) { s->quant_precision = 5; } } else { s->quant_precision = 5; } // FIXME a bunch of grayscale shape things if ((s->mpeg_quant = get_bits1(gb))) { /* vol_quant_type */ int i, v; mpeg4_load_default_matrices(s); /* load custom intra matrix */ if (get_bits1(gb)) { int last = 0; for (i = 0; i < 64; i++) { int j; if (get_bits_left(gb) < 8) { av_log(s->avctx, AV_LOG_ERROR, "insufficient data for custom matrix\n"); return AVERROR_INVALIDDATA; } v = get_bits(gb, 8); if (v == 0) break; last = v; j = s->idsp.idct_permutation[ff_zigzag_direct[i]]; s->intra_matrix[j] = last; s->chroma_intra_matrix[j] = last; } /* replicate last value */ for (; i < 64; i++) { int j = s->idsp.idct_permutation[ff_zigzag_direct[i]]; s->intra_matrix[j] = last; s->chroma_intra_matrix[j] = last; } } /* load custom non intra matrix */ if (get_bits1(gb)) { int last = 0; for (i = 0; i < 64; i++) { int j; if (get_bits_left(gb) < 8) { av_log(s->avctx, AV_LOG_ERROR, "insufficient data for custom matrix\n"); return AVERROR_INVALIDDATA; } v = get_bits(gb, 8); if (v == 0) break; last = v; j = s->idsp.idct_permutation[ff_zigzag_direct[i]]; s->inter_matrix[j] = v; s->chroma_inter_matrix[j] = v; } /* replicate last value */ for (; i < 64; i++) { int j = s->idsp.idct_permutation[ff_zigzag_direct[i]]; s->inter_matrix[j] = last; s->chroma_inter_matrix[j] = last; } } // FIXME a bunch of grayscale shape things } if (vo_ver_id != 1) s->quarter_sample = get_bits1(gb); else s->quarter_sample = 0; if (get_bits_left(gb) < 4) { av_log(s->avctx, AV_LOG_ERROR, "VOL Header truncated\n"); return AVERROR_INVALIDDATA; } if (!get_bits1(gb)) { int pos = get_bits_count(gb); int estimation_method = get_bits(gb, 2); if (estimation_method < 2) { if (!get_bits1(gb)) { ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* opaque */ ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* transparent */ ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* intra_cae */ ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* inter_cae */ ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* no_update */ ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* upsampling */ } if (!get_bits1(gb)) { ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* intra_blocks */ ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* inter_blocks */ ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* inter4v_blocks */ ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* not coded blocks */ } if (!check_marker(s->avctx, gb, "in complexity estimation part 1")) { skip_bits_long(gb, pos - get_bits_count(gb)); goto no_cplx_est; } if (!get_bits1(gb)) { ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* dct_coeffs */ ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* dct_lines */ ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* vlc_syms */ ctx->cplx_estimation_trash_i += 4 * get_bits1(gb); /* vlc_bits */ } if (!get_bits1(gb)) { ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* apm */ ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* npm */ ctx->cplx_estimation_trash_b += 8 * get_bits1(gb); /* interpolate_mc_q */ ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* forwback_mc_q */ ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* halfpel2 */ ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* halfpel4 */ } if (!check_marker(s->avctx, gb, "in complexity estimation part 2")) { skip_bits_long(gb, pos - get_bits_count(gb)); goto no_cplx_est; } if (estimation_method == 1) { ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* sadct */ ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* qpel */ } } else av_log(s->avctx, AV_LOG_ERROR, "Invalid Complexity estimation method %d\n", estimation_method); } else { no_cplx_est: ctx->cplx_estimation_trash_i = ctx->cplx_estimation_trash_p = ctx->cplx_estimation_trash_b = 0; } ctx->resync_marker = !get_bits1(gb); /* resync_marker_disabled */ s->data_partitioning = get_bits1(gb); if (s->data_partitioning) ctx->rvlc = get_bits1(gb); if (vo_ver_id != 1) { ctx->new_pred = get_bits1(gb); if (ctx->new_pred) { av_log(s->avctx, AV_LOG_ERROR, "new pred not supported\n"); skip_bits(gb, 2); /* requested upstream message type */ skip_bits1(gb); /* newpred segment type */ } if (get_bits1(gb)) // reduced_res_vop av_log(s->avctx, AV_LOG_ERROR, "reduced resolution VOP not supported\n"); } else { ctx->new_pred = 0; } ctx->scalability = get_bits1(gb); if (ctx->scalability) { GetBitContext bak = *gb; int h_sampling_factor_n; int h_sampling_factor_m; int v_sampling_factor_n; int v_sampling_factor_m; skip_bits1(gb); // hierarchy_type skip_bits(gb, 4); /* ref_layer_id */ skip_bits1(gb); /* ref_layer_sampling_dir */ h_sampling_factor_n = get_bits(gb, 5); h_sampling_factor_m = get_bits(gb, 5); v_sampling_factor_n = get_bits(gb, 5); v_sampling_factor_m = get_bits(gb, 5); ctx->enhancement_type = get_bits1(gb); if (h_sampling_factor_n == 0 || h_sampling_factor_m == 0 || v_sampling_factor_n == 0 || v_sampling_factor_m == 0) { /* illegal scalability header (VERY broken encoder), * trying to workaround */ ctx->scalability = 0; *gb = bak; } else av_log(s->avctx, AV_LOG_ERROR, "scalability not supported\n"); // bin shape stuff FIXME } } if (s->avctx->debug&FF_DEBUG_PICT_INFO) { av_log(s->avctx, AV_LOG_DEBUG, "tb %d/%d, tincrbits:%d, qp_prec:%d, ps:%d, low_delay:%d %s%s%s%s\n", s->avctx->framerate.den, s->avctx->framerate.num, ctx->time_increment_bits, s->quant_precision, s->progressive_sequence, s->low_delay, ctx->scalability ? "scalability " :"" , s->quarter_sample ? "qpel " : "", s->data_partitioning ? "partition " : "", ctx->rvlc ? "rvlc " : "" ); } return 0; } /** * Decode the user data stuff in the header. * Also initializes divx/xvid/lavc_version/build. */ static int decode_user_data(Mpeg4DecContext *ctx, GetBitContext *gb) { MpegEncContext *s = &ctx->m; char buf[256]; int i; int e; int ver = 0, build = 0, ver2 = 0, ver3 = 0; char last; for (i = 0; i < 255 && get_bits_count(gb) < gb->size_in_bits; i++) { if (show_bits(gb, 23) == 0) break; buf[i] = get_bits(gb, 8); } buf[i] = 0; /* divx detection */ e = sscanf(buf, "DivX%dBuild%d%c", &ver, &build, &last); if (e < 2) e = sscanf(buf, "DivX%db%d%c", &ver, &build, &last); if (e >= 2) { ctx->divx_version = ver; ctx->divx_build = build; s->divx_packed = e == 3 && last == 'p'; } /* libavcodec detection */ e = sscanf(buf, "FFmpe%*[^b]b%d", &build) + 3; if (e != 4) e = sscanf(buf, "FFmpeg v%d.%d.%d / libavcodec build: %d", &ver, &ver2, &ver3, &build); if (e != 4) { e = sscanf(buf, "Lavc%d.%d.%d", &ver, &ver2, &ver3) + 1; if (e > 1) { if (ver > 0xFFU || ver2 > 0xFFU || ver3 > 0xFFU) { av_log(s->avctx, AV_LOG_WARNING, "Unknown Lavc version string encountered, %d.%d.%d; " "clamping sub-version values to 8-bits.\n", ver, ver2, ver3); } build = ((ver & 0xFF) << 16) + ((ver2 & 0xFF) << 8) + (ver3 & 0xFF); } } if (e != 4) { if (strcmp(buf, "ffmpeg") == 0) ctx->lavc_build = 4600; } if (e == 4) ctx->lavc_build = build; /* Xvid detection */ e = sscanf(buf, "XviD%d", &build); if (e == 1) ctx->xvid_build = build; return 0; } int ff_mpeg4_workaround_bugs(AVCodecContext *avctx) { Mpeg4DecContext *ctx = avctx->priv_data; MpegEncContext *s = &ctx->m; if (ctx->xvid_build == -1 && ctx->divx_version == -1 && ctx->lavc_build == -1) { if (s->codec_tag == AV_RL32("XVID") || s->codec_tag == AV_RL32("XVIX") || s->codec_tag == AV_RL32("RMP4") || s->codec_tag == AV_RL32("ZMP4") || s->codec_tag == AV_RL32("SIPP")) ctx->xvid_build = 0; } if (ctx->xvid_build == -1 && ctx->divx_version == -1 && ctx->lavc_build == -1) if (s->codec_tag == AV_RL32("DIVX") && s->vo_type == 0 && ctx->vol_control_parameters == 0) ctx->divx_version = 400; // divx 4 if (ctx->xvid_build >= 0 && ctx->divx_version >= 0) { ctx->divx_version = ctx->divx_build = -1; } if (s->workaround_bugs & FF_BUG_AUTODETECT) { if (s->codec_tag == AV_RL32("XVIX")) s->workaround_bugs |= FF_BUG_XVID_ILACE; if (s->codec_tag == AV_RL32("UMP4")) s->workaround_bugs |= FF_BUG_UMP4; if (ctx->divx_version >= 500 && ctx->divx_build < 1814) s->workaround_bugs |= FF_BUG_QPEL_CHROMA; if (ctx->divx_version > 502 && ctx->divx_build < 1814) s->workaround_bugs |= FF_BUG_QPEL_CHROMA2; if (ctx->xvid_build <= 3U) s->padding_bug_score = 256 * 256 * 256 * 64; if (ctx->xvid_build <= 1U) s->workaround_bugs |= FF_BUG_QPEL_CHROMA; if (ctx->xvid_build <= 12U) s->workaround_bugs |= FF_BUG_EDGE; if (ctx->xvid_build <= 32U) s->workaround_bugs |= FF_BUG_DC_CLIP; #define SET_QPEL_FUNC(postfix1, postfix2) \ s->qdsp.put_ ## postfix1 = ff_put_ ## postfix2; \ s->qdsp.put_no_rnd_ ## postfix1 = ff_put_no_rnd_ ## postfix2; \ s->qdsp.avg_ ## postfix1 = ff_avg_ ## postfix2; if (ctx->lavc_build < 4653U) s->workaround_bugs |= FF_BUG_STD_QPEL; if (ctx->lavc_build < 4655U) s->workaround_bugs |= FF_BUG_DIRECT_BLOCKSIZE; if (ctx->lavc_build < 4670U) s->workaround_bugs |= FF_BUG_EDGE; if (ctx->lavc_build <= 4712U) s->workaround_bugs |= FF_BUG_DC_CLIP; if ((ctx->lavc_build&0xFF) >= 100) { if (ctx->lavc_build > 3621476 && ctx->lavc_build < 3752552 && (ctx->lavc_build < 3752037 || ctx->lavc_build > 3752191) // 3.2.1+ ) s->workaround_bugs |= FF_BUG_IEDGE; } if (ctx->divx_version >= 0) s->workaround_bugs |= FF_BUG_DIRECT_BLOCKSIZE; if (ctx->divx_version == 501 && ctx->divx_build == 20020416) s->padding_bug_score = 256 * 256 * 256 * 64; if (ctx->divx_version < 500U) s->workaround_bugs |= FF_BUG_EDGE; if (ctx->divx_version >= 0) s->workaround_bugs |= FF_BUG_HPEL_CHROMA; } if (s->workaround_bugs & FF_BUG_STD_QPEL) { SET_QPEL_FUNC(qpel_pixels_tab[0][5], qpel16_mc11_old_c) SET_QPEL_FUNC(qpel_pixels_tab[0][7], qpel16_mc31_old_c) SET_QPEL_FUNC(qpel_pixels_tab[0][9], qpel16_mc12_old_c) SET_QPEL_FUNC(qpel_pixels_tab[0][11], qpel16_mc32_old_c) SET_QPEL_FUNC(qpel_pixels_tab[0][13], qpel16_mc13_old_c) SET_QPEL_FUNC(qpel_pixels_tab[0][15], qpel16_mc33_old_c) SET_QPEL_FUNC(qpel_pixels_tab[1][5], qpel8_mc11_old_c) SET_QPEL_FUNC(qpel_pixels_tab[1][7], qpel8_mc31_old_c) SET_QPEL_FUNC(qpel_pixels_tab[1][9], qpel8_mc12_old_c) SET_QPEL_FUNC(qpel_pixels_tab[1][11], qpel8_mc32_old_c) SET_QPEL_FUNC(qpel_pixels_tab[1][13], qpel8_mc13_old_c) SET_QPEL_FUNC(qpel_pixels_tab[1][15], qpel8_mc33_old_c) } if (avctx->debug & FF_DEBUG_BUGS) av_log(s->avctx, AV_LOG_DEBUG, "bugs: %X lavc_build:%d xvid_build:%d divx_version:%d divx_build:%d %s\n", s->workaround_bugs, ctx->lavc_build, ctx->xvid_build, ctx->divx_version, ctx->divx_build, s->divx_packed ? "p" : ""); if (CONFIG_MPEG4_DECODER && ctx->xvid_build >= 0 && s->codec_id == AV_CODEC_ID_MPEG4 && avctx->idct_algo == FF_IDCT_AUTO) { avctx->idct_algo = FF_IDCT_XVID; ff_mpv_idct_init(s); return 1; } return 0; } static int decode_vop_header(Mpeg4DecContext *ctx, GetBitContext *gb) { MpegEncContext *s = &ctx->m; int time_incr, time_increment; int64_t pts; s->mcsel = 0; s->pict_type = get_bits(gb, 2) + AV_PICTURE_TYPE_I; /* pict type: I = 0 , P = 1 */ if (s->pict_type == AV_PICTURE_TYPE_B && s->low_delay && ctx->vol_control_parameters == 0 && !(s->avctx->flags & AV_CODEC_FLAG_LOW_DELAY)) { av_log(s->avctx, AV_LOG_ERROR, "low_delay flag set incorrectly, clearing it\n"); s->low_delay = 0; } s->partitioned_frame = s->data_partitioning && s->pict_type != AV_PICTURE_TYPE_B; if (s->partitioned_frame) s->decode_mb = mpeg4_decode_partitioned_mb; else s->decode_mb = mpeg4_decode_mb; time_incr = 0; while (get_bits1(gb) != 0) time_incr++; check_marker(s->avctx, gb, "before time_increment"); if (ctx->time_increment_bits == 0 || !(show_bits(gb, ctx->time_increment_bits + 1) & 1)) { av_log(s->avctx, AV_LOG_WARNING, "time_increment_bits %d is invalid in relation to the current bitstream, this is likely caused by a missing VOL header\n", ctx->time_increment_bits); for (ctx->time_increment_bits = 1; ctx->time_increment_bits < 16; ctx->time_increment_bits++) { if (s->pict_type == AV_PICTURE_TYPE_P || (s->pict_type == AV_PICTURE_TYPE_S && ctx->vol_sprite_usage == GMC_SPRITE)) { if ((show_bits(gb, ctx->time_increment_bits + 6) & 0x37) == 0x30) break; } else if ((show_bits(gb, ctx->time_increment_bits + 5) & 0x1F) == 0x18) break; } av_log(s->avctx, AV_LOG_WARNING, "time_increment_bits set to %d bits, based on bitstream analysis\n", ctx->time_increment_bits); if (s->avctx->framerate.num && 4*s->avctx->framerate.num < 1<<ctx->time_increment_bits) { s->avctx->framerate.num = 1<<ctx->time_increment_bits; s->avctx->time_base = av_inv_q(av_mul_q(s->avctx->framerate, (AVRational){s->avctx->ticks_per_frame, 1})); } } if (IS_3IV1) time_increment = get_bits1(gb); // FIXME investigate further else time_increment = get_bits(gb, ctx->time_increment_bits); if (s->pict_type != AV_PICTURE_TYPE_B) { s->last_time_base = s->time_base; s->time_base += time_incr; s->time = s->time_base * (int64_t)s->avctx->framerate.num + time_increment; if (s->workaround_bugs & FF_BUG_UMP4) { if (s->time < s->last_non_b_time) { /* header is not mpeg-4-compatible, broken encoder, * trying to workaround */ s->time_base++; s->time += s->avctx->framerate.num; } } s->pp_time = s->time - s->last_non_b_time; s->last_non_b_time = s->time; } else { s->time = (s->last_time_base + time_incr) * (int64_t)s->avctx->framerate.num + time_increment; s->pb_time = s->pp_time - (s->last_non_b_time - s->time); if (s->pp_time <= s->pb_time || s->pp_time <= s->pp_time - s->pb_time || s->pp_time <= 0) { /* messed up order, maybe after seeking? skipping current B-frame */ return FRAME_SKIPPED; } ff_mpeg4_init_direct_mv(s); if (ctx->t_frame == 0) ctx->t_frame = s->pb_time; if (ctx->t_frame == 0) ctx->t_frame = 1; // 1/0 protection s->pp_field_time = (ROUNDED_DIV(s->last_non_b_time, ctx->t_frame) - ROUNDED_DIV(s->last_non_b_time - s->pp_time, ctx->t_frame)) * 2; s->pb_field_time = (ROUNDED_DIV(s->time, ctx->t_frame) - ROUNDED_DIV(s->last_non_b_time - s->pp_time, ctx->t_frame)) * 2; if (s->pp_field_time <= s->pb_field_time || s->pb_field_time <= 1) { s->pb_field_time = 2; s->pp_field_time = 4; if (!s->progressive_sequence) return FRAME_SKIPPED; } } if (s->avctx->framerate.den) pts = ROUNDED_DIV(s->time, s->avctx->framerate.den); else pts = AV_NOPTS_VALUE; ff_dlog(s->avctx, "MPEG4 PTS: %"PRId64"\n", pts); check_marker(s->avctx, gb, "before vop_coded"); /* vop coded */ if (get_bits1(gb) != 1) { if (s->avctx->debug & FF_DEBUG_PICT_INFO) av_log(s->avctx, AV_LOG_ERROR, "vop not coded\n"); return FRAME_SKIPPED; } if (ctx->new_pred) decode_new_pred(ctx, gb); if (ctx->shape != BIN_ONLY_SHAPE && (s->pict_type == AV_PICTURE_TYPE_P || (s->pict_type == AV_PICTURE_TYPE_S && ctx->vol_sprite_usage == GMC_SPRITE))) { /* rounding type for motion estimation */ s->no_rounding = get_bits1(gb); } else { s->no_rounding = 0; } // FIXME reduced res stuff if (ctx->shape != RECT_SHAPE) { if (ctx->vol_sprite_usage != 1 || s->pict_type != AV_PICTURE_TYPE_I) { skip_bits(gb, 13); /* width */ check_marker(s->avctx, gb, "after width"); skip_bits(gb, 13); /* height */ check_marker(s->avctx, gb, "after height"); skip_bits(gb, 13); /* hor_spat_ref */ check_marker(s->avctx, gb, "after hor_spat_ref"); skip_bits(gb, 13); /* ver_spat_ref */ } skip_bits1(gb); /* change_CR_disable */ if (get_bits1(gb) != 0) skip_bits(gb, 8); /* constant_alpha_value */ } // FIXME complexity estimation stuff if (ctx->shape != BIN_ONLY_SHAPE) { skip_bits_long(gb, ctx->cplx_estimation_trash_i); if (s->pict_type != AV_PICTURE_TYPE_I) skip_bits_long(gb, ctx->cplx_estimation_trash_p); if (s->pict_type == AV_PICTURE_TYPE_B) skip_bits_long(gb, ctx->cplx_estimation_trash_b); if (get_bits_left(gb) < 3) { av_log(s->avctx, AV_LOG_ERROR, "Header truncated\n"); return AVERROR_INVALIDDATA; } ctx->intra_dc_threshold = ff_mpeg4_dc_threshold[get_bits(gb, 3)]; if (!s->progressive_sequence) { s->top_field_first = get_bits1(gb); s->alternate_scan = get_bits1(gb); } else s->alternate_scan = 0; } if (s->alternate_scan) { ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_alternate_vertical_scan); ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_alternate_vertical_scan); ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_vertical_scan); ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan); } else { ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_zigzag_direct); ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_zigzag_direct); ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_horizontal_scan); ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan); } if (s->pict_type == AV_PICTURE_TYPE_S) { if((ctx->vol_sprite_usage == STATIC_SPRITE || ctx->vol_sprite_usage == GMC_SPRITE)) { if (mpeg4_decode_sprite_trajectory(ctx, gb) < 0) return AVERROR_INVALIDDATA; if (ctx->sprite_brightness_change) av_log(s->avctx, AV_LOG_ERROR, "sprite_brightness_change not supported\n"); if (ctx->vol_sprite_usage == STATIC_SPRITE) av_log(s->avctx, AV_LOG_ERROR, "static sprite not supported\n"); } else { memset(s->sprite_offset, 0, sizeof(s->sprite_offset)); memset(s->sprite_delta, 0, sizeof(s->sprite_delta)); } } if (ctx->shape != BIN_ONLY_SHAPE) { s->chroma_qscale = s->qscale = get_bits(gb, s->quant_precision); if (s->qscale == 0) { av_log(s->avctx, AV_LOG_ERROR, "Error, header damaged or not MPEG-4 header (qscale=0)\n"); return AVERROR_INVALIDDATA; // makes no sense to continue, as there is nothing left from the image then } if (s->pict_type != AV_PICTURE_TYPE_I) { s->f_code = get_bits(gb, 3); /* fcode_for */ if (s->f_code == 0) { av_log(s->avctx, AV_LOG_ERROR, "Error, header damaged or not MPEG-4 header (f_code=0)\n"); s->f_code = 1; return AVERROR_INVALIDDATA; // makes no sense to continue, as there is nothing left from the image then } } else s->f_code = 1; if (s->pict_type == AV_PICTURE_TYPE_B) { s->b_code = get_bits(gb, 3); if (s->b_code == 0) { av_log(s->avctx, AV_LOG_ERROR, "Error, header damaged or not MPEG4 header (b_code=0)\n"); s->b_code=1; return AVERROR_INVALIDDATA; // makes no sense to continue, as the MV decoding will break very quickly } } else s->b_code = 1; if (s->avctx->debug & FF_DEBUG_PICT_INFO) { av_log(s->avctx, AV_LOG_DEBUG, "qp:%d fc:%d,%d %s size:%d pro:%d alt:%d top:%d %spel part:%d resync:%d w:%d a:%d rnd:%d vot:%d%s dc:%d ce:%d/%d/%d time:%"PRId64" tincr:%d\n", s->qscale, s->f_code, s->b_code, s->pict_type == AV_PICTURE_TYPE_I ? "I" : (s->pict_type == AV_PICTURE_TYPE_P ? "P" : (s->pict_type == AV_PICTURE_TYPE_B ? "B" : "S")), gb->size_in_bits,s->progressive_sequence, s->alternate_scan, s->top_field_first, s->quarter_sample ? "q" : "h", s->data_partitioning, ctx->resync_marker, ctx->num_sprite_warping_points, s->sprite_warping_accuracy, 1 - s->no_rounding, s->vo_type, ctx->vol_control_parameters ? " VOLC" : " ", ctx->intra_dc_threshold, ctx->cplx_estimation_trash_i, ctx->cplx_estimation_trash_p, ctx->cplx_estimation_trash_b, s->time, time_increment ); } if (!ctx->scalability) { if (ctx->shape != RECT_SHAPE && s->pict_type != AV_PICTURE_TYPE_I) skip_bits1(gb); // vop shape coding type } else { if (ctx->enhancement_type) { int load_backward_shape = get_bits1(gb); if (load_backward_shape) av_log(s->avctx, AV_LOG_ERROR, "load backward shape isn't supported\n"); } skip_bits(gb, 2); // ref_select_code } } /* detect buggy encoders which don't set the low_delay flag * (divx4/xvid/opendivx). Note we cannot detect divx5 without B-frames * easily (although it's buggy too) */ if (s->vo_type == 0 && ctx->vol_control_parameters == 0 && ctx->divx_version == -1 && s->picture_number == 0) { av_log(s->avctx, AV_LOG_WARNING, "looks like this file was encoded with (divx4/(old)xvid/opendivx) -> forcing low_delay flag\n"); s->low_delay = 1; } s->picture_number++; // better than pic number==0 always ;) // FIXME add short header support s->y_dc_scale_table = ff_mpeg4_y_dc_scale_table; s->c_dc_scale_table = ff_mpeg4_c_dc_scale_table; if (s->workaround_bugs & FF_BUG_EDGE) { s->h_edge_pos = s->width; s->v_edge_pos = s->height; } return 0; } static void read_quant_matrix_ext(MpegEncContext *s, GetBitContext *gb) { int i, j, v; if (get_bits1(gb)) { /* intra_quantiser_matrix */ for (i = 0; i < 64; i++) { v = get_bits(gb, 8); j = s->idsp.idct_permutation[ff_zigzag_direct[i]]; s->intra_matrix[j] = v; s->chroma_intra_matrix[j] = v; } } if (get_bits1(gb)) { /* non_intra_quantiser_matrix */ for (i = 0; i < 64; i++) { get_bits(gb, 8); } } if (get_bits1(gb)) { /* chroma_intra_quantiser_matrix */ for (i = 0; i < 64; i++) { v = get_bits(gb, 8); j = s->idsp.idct_permutation[ff_zigzag_direct[i]]; s->chroma_intra_matrix[j] = v; } } if (get_bits1(gb)) { /* chroma_non_intra_quantiser_matrix */ for (i = 0; i < 64; i++) { get_bits(gb, 8); } } next_start_code_studio(gb); } static void extension_and_user_data(MpegEncContext *s, GetBitContext *gb, int id) { uint32_t startcode; uint8_t extension_type; startcode = show_bits_long(gb, 32); if (startcode == USER_DATA_STARTCODE || startcode == EXT_STARTCODE) { if ((id == 2 || id == 4) && startcode == EXT_STARTCODE) { skip_bits_long(gb, 32); extension_type = get_bits(gb, 4); if (extension_type == QUANT_MATRIX_EXT_ID) read_quant_matrix_ext(s, gb); } } } static void decode_smpte_tc(Mpeg4DecContext *ctx, GetBitContext *gb) { MpegEncContext *s = &ctx->m; skip_bits(gb, 16); /* Time_code[63..48] */ check_marker(s->avctx, gb, "after Time_code[63..48]"); skip_bits(gb, 16); /* Time_code[47..32] */ check_marker(s->avctx, gb, "after Time_code[47..32]"); skip_bits(gb, 16); /* Time_code[31..16] */ check_marker(s->avctx, gb, "after Time_code[31..16]"); skip_bits(gb, 16); /* Time_code[15..0] */ check_marker(s->avctx, gb, "after Time_code[15..0]"); skip_bits(gb, 4); /* reserved_bits */ } /** * Decode the next studio vop header. * @return <0 if something went wrong */ static int decode_studio_vop_header(Mpeg4DecContext *ctx, GetBitContext *gb) { MpegEncContext *s = &ctx->m; if (get_bits_left(gb) <= 32) return 0; s->decode_mb = mpeg4_decode_studio_mb; decode_smpte_tc(ctx, gb); skip_bits(gb, 10); /* temporal_reference */ skip_bits(gb, 2); /* vop_structure */ s->pict_type = get_bits(gb, 2) + AV_PICTURE_TYPE_I; /* vop_coding_type */ if (get_bits1(gb)) { /* vop_coded */ skip_bits1(gb); /* top_field_first */ skip_bits1(gb); /* repeat_first_field */ s->progressive_frame = get_bits1(gb) ^ 1; /* progressive_frame */ } if (s->pict_type == AV_PICTURE_TYPE_I) { if (get_bits1(gb)) reset_studio_dc_predictors(s); } if (ctx->shape != BIN_ONLY_SHAPE) { s->alternate_scan = get_bits1(gb); s->frame_pred_frame_dct = get_bits1(gb); s->dct_precision = get_bits(gb, 2); s->intra_dc_precision = get_bits(gb, 2); s->q_scale_type = get_bits1(gb); } if (s->alternate_scan) { ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_alternate_vertical_scan); ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_alternate_vertical_scan); ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_vertical_scan); ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan); } else { ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_zigzag_direct); ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_zigzag_direct); ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_horizontal_scan); ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan); } mpeg4_load_default_matrices(s); next_start_code_studio(gb); extension_and_user_data(s, gb, 4); return 0; } static int decode_studiovisualobject(Mpeg4DecContext *ctx, GetBitContext *gb) { MpegEncContext *s = &ctx->m; int visual_object_type; skip_bits(gb, 4); /* visual_object_verid */ visual_object_type = get_bits(gb, 4); if (visual_object_type != VOT_VIDEO_ID) { avpriv_request_sample(s->avctx, "VO type %u", visual_object_type); return AVERROR_PATCHWELCOME; } next_start_code_studio(gb); extension_and_user_data(s, gb, 1); return 0; } static int decode_studio_vol_header(Mpeg4DecContext *ctx, GetBitContext *gb) { MpegEncContext *s = &ctx->m; int width, height; int bits_per_raw_sample; // random_accessible_vol and video_object_type_indication have already // been read by the caller decode_vol_header() skip_bits(gb, 4); /* video_object_layer_verid */ ctx->shape = get_bits(gb, 2); /* video_object_layer_shape */ skip_bits(gb, 4); /* video_object_layer_shape_extension */ skip_bits1(gb); /* progressive_sequence */ if (ctx->shape != BIN_ONLY_SHAPE) { ctx->rgb = get_bits1(gb); /* rgb_components */ s->chroma_format = get_bits(gb, 2); /* chroma_format */ if (!s->chroma_format) { av_log(s->avctx, AV_LOG_ERROR, "illegal chroma format\n"); return AVERROR_INVALIDDATA; } bits_per_raw_sample = get_bits(gb, 4); /* bit_depth */ if (bits_per_raw_sample == 10) { if (ctx->rgb) { s->avctx->pix_fmt = AV_PIX_FMT_GBRP10; } else { s->avctx->pix_fmt = s->chroma_format == CHROMA_422 ? AV_PIX_FMT_YUV422P10 : AV_PIX_FMT_YUV444P10; } } else { avpriv_request_sample(s->avctx, "MPEG-4 Studio profile bit-depth %u", bits_per_raw_sample); return AVERROR_PATCHWELCOME; } s->avctx->bits_per_raw_sample = bits_per_raw_sample; } if (ctx->shape == RECT_SHAPE) { check_marker(s->avctx, gb, "before video_object_layer_width"); width = get_bits(gb, 14); /* video_object_layer_width */ check_marker(s->avctx, gb, "before video_object_layer_height"); height = get_bits(gb, 14); /* video_object_layer_height */ check_marker(s->avctx, gb, "after video_object_layer_height"); /* Do the same check as non-studio profile */ if (width && height) { if (s->width && s->height && (s->width != width || s->height != height)) s->context_reinit = 1; s->width = width; s->height = height; } } s->aspect_ratio_info = get_bits(gb, 4); if (s->aspect_ratio_info == FF_ASPECT_EXTENDED) { s->avctx->sample_aspect_ratio.num = get_bits(gb, 8); // par_width s->avctx->sample_aspect_ratio.den = get_bits(gb, 8); // par_height } else { s->avctx->sample_aspect_ratio = ff_h263_pixel_aspect[s->aspect_ratio_info]; } skip_bits(gb, 4); /* frame_rate_code */ skip_bits(gb, 15); /* first_half_bit_rate */ check_marker(s->avctx, gb, "after first_half_bit_rate"); skip_bits(gb, 15); /* latter_half_bit_rate */ check_marker(s->avctx, gb, "after latter_half_bit_rate"); skip_bits(gb, 15); /* first_half_vbv_buffer_size */ check_marker(s->avctx, gb, "after first_half_vbv_buffer_size"); skip_bits(gb, 3); /* latter_half_vbv_buffer_size */ skip_bits(gb, 11); /* first_half_vbv_buffer_size */ check_marker(s->avctx, gb, "after first_half_vbv_buffer_size"); skip_bits(gb, 15); /* latter_half_vbv_occupancy */ check_marker(s->avctx, gb, "after latter_half_vbv_occupancy"); s->low_delay = get_bits1(gb); s->mpeg_quant = get_bits1(gb); /* mpeg2_stream */ next_start_code_studio(gb); extension_and_user_data(s, gb, 2); return 0; } /** * Decode MPEG-4 headers. * @return <0 if no VOP found (or a damaged one) * FRAME_SKIPPED if a not coded VOP is found * 0 if a VOP is found */ int ff_mpeg4_decode_picture_header(Mpeg4DecContext *ctx, GetBitContext *gb) { MpegEncContext *s = &ctx->m; unsigned startcode, v; int ret; int vol = 0; /* search next start code */ align_get_bits(gb); // If we have not switched to studio profile than we also did not switch bps // that means something else (like a previous instance) outside set bps which // would be inconsistant with the currect state, thus reset it if (!s->studio_profile && s->avctx->bits_per_raw_sample != 8) s->avctx->bits_per_raw_sample = 0; if (s->codec_tag == AV_RL32("WV1F") && show_bits(gb, 24) == 0x575630) { skip_bits(gb, 24); if (get_bits(gb, 8) == 0xF0) goto end; } startcode = 0xff; for (;;) { if (get_bits_count(gb) >= gb->size_in_bits) { if (gb->size_in_bits == 8 && (ctx->divx_version >= 0 || ctx->xvid_build >= 0) || s->codec_tag == AV_RL32("QMP4")) { av_log(s->avctx, AV_LOG_VERBOSE, "frame skip %d\n", gb->size_in_bits); return FRAME_SKIPPED; // divx bug } else return AVERROR_INVALIDDATA; // end of stream } /* use the bits after the test */ v = get_bits(gb, 8); startcode = ((startcode << 8) | v) & 0xffffffff; if ((startcode & 0xFFFFFF00) != 0x100) continue; // no startcode if (s->avctx->debug & FF_DEBUG_STARTCODE) { av_log(s->avctx, AV_LOG_DEBUG, "startcode: %3X ", startcode); if (startcode <= 0x11F) av_log(s->avctx, AV_LOG_DEBUG, "Video Object Start"); else if (startcode <= 0x12F) av_log(s->avctx, AV_LOG_DEBUG, "Video Object Layer Start"); else if (startcode <= 0x13F) av_log(s->avctx, AV_LOG_DEBUG, "Reserved"); else if (startcode <= 0x15F) av_log(s->avctx, AV_LOG_DEBUG, "FGS bp start"); else if (startcode <= 0x1AF) av_log(s->avctx, AV_LOG_DEBUG, "Reserved"); else if (startcode == 0x1B0) av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Seq Start"); else if (startcode == 0x1B1) av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Seq End"); else if (startcode == 0x1B2) av_log(s->avctx, AV_LOG_DEBUG, "User Data"); else if (startcode == 0x1B3) av_log(s->avctx, AV_LOG_DEBUG, "Group of VOP start"); else if (startcode == 0x1B4) av_log(s->avctx, AV_LOG_DEBUG, "Video Session Error"); else if (startcode == 0x1B5) av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Start"); else if (startcode == 0x1B6) av_log(s->avctx, AV_LOG_DEBUG, "Video Object Plane start"); else if (startcode == 0x1B7) av_log(s->avctx, AV_LOG_DEBUG, "slice start"); else if (startcode == 0x1B8) av_log(s->avctx, AV_LOG_DEBUG, "extension start"); else if (startcode == 0x1B9) av_log(s->avctx, AV_LOG_DEBUG, "fgs start"); else if (startcode == 0x1BA) av_log(s->avctx, AV_LOG_DEBUG, "FBA Object start"); else if (startcode == 0x1BB) av_log(s->avctx, AV_LOG_DEBUG, "FBA Object Plane start"); else if (startcode == 0x1BC) av_log(s->avctx, AV_LOG_DEBUG, "Mesh Object start"); else if (startcode == 0x1BD) av_log(s->avctx, AV_LOG_DEBUG, "Mesh Object Plane start"); else if (startcode == 0x1BE) av_log(s->avctx, AV_LOG_DEBUG, "Still Texture Object start"); else if (startcode == 0x1BF) av_log(s->avctx, AV_LOG_DEBUG, "Texture Spatial Layer start"); else if (startcode == 0x1C0) av_log(s->avctx, AV_LOG_DEBUG, "Texture SNR Layer start"); else if (startcode == 0x1C1) av_log(s->avctx, AV_LOG_DEBUG, "Texture Tile start"); else if (startcode == 0x1C2) av_log(s->avctx, AV_LOG_DEBUG, "Texture Shape Layer start"); else if (startcode == 0x1C3) av_log(s->avctx, AV_LOG_DEBUG, "stuffing start"); else if (startcode <= 0x1C5) av_log(s->avctx, AV_LOG_DEBUG, "reserved"); else if (startcode <= 0x1FF) av_log(s->avctx, AV_LOG_DEBUG, "System start"); av_log(s->avctx, AV_LOG_DEBUG, " at %d\n", get_bits_count(gb)); } if (startcode >= 0x120 && startcode <= 0x12F) { if (vol) { av_log(s->avctx, AV_LOG_WARNING, "Ignoring multiple VOL headers\n"); continue; } vol++; if ((ret = decode_vol_header(ctx, gb)) < 0) return ret; } else if (startcode == USER_DATA_STARTCODE) { decode_user_data(ctx, gb); } else if (startcode == GOP_STARTCODE) { mpeg4_decode_gop_header(s, gb); } else if (startcode == VOS_STARTCODE) { mpeg4_decode_profile_level(s, gb); if (s->avctx->profile == FF_PROFILE_MPEG4_SIMPLE_STUDIO && (s->avctx->level > 0 && s->avctx->level < 9)) { s->studio_profile = 1; next_start_code_studio(gb); extension_and_user_data(s, gb, 0); } } else if (startcode == VISUAL_OBJ_STARTCODE) { if (s->studio_profile) { if ((ret = decode_studiovisualobject(ctx, gb)) < 0) return ret; } else mpeg4_decode_visual_object(s, gb); } else if (startcode == VOP_STARTCODE) { break; } align_get_bits(gb); startcode = 0xff; } end: if (s->avctx->flags & AV_CODEC_FLAG_LOW_DELAY) s->low_delay = 1; s->avctx->has_b_frames = !s->low_delay; if (s->studio_profile) { if (!s->avctx->bits_per_raw_sample) { av_log(s->avctx, AV_LOG_ERROR, "Missing VOL header\n"); return AVERROR_INVALIDDATA; } return decode_studio_vop_header(ctx, gb); } else return decode_vop_header(ctx, gb); } av_cold void ff_mpeg4videodec_static_init(void) { static int done = 0; if (!done) { ff_rl_init(&ff_mpeg4_rl_intra, ff_mpeg4_static_rl_table_store[0]); ff_rl_init(&ff_rvlc_rl_inter, ff_mpeg4_static_rl_table_store[1]); ff_rl_init(&ff_rvlc_rl_intra, ff_mpeg4_static_rl_table_store[2]); INIT_VLC_RL(ff_mpeg4_rl_intra, 554); INIT_VLC_RL(ff_rvlc_rl_inter, 1072); INIT_VLC_RL(ff_rvlc_rl_intra, 1072); INIT_VLC_STATIC(&dc_lum, DC_VLC_BITS, 10 /* 13 */, &ff_mpeg4_DCtab_lum[0][1], 2, 1, &ff_mpeg4_DCtab_lum[0][0], 2, 1, 512); INIT_VLC_STATIC(&dc_chrom, DC_VLC_BITS, 10 /* 13 */, &ff_mpeg4_DCtab_chrom[0][1], 2, 1, &ff_mpeg4_DCtab_chrom[0][0], 2, 1, 512); INIT_VLC_STATIC(&sprite_trajectory, SPRITE_TRAJ_VLC_BITS, 15, &ff_sprite_trajectory_tab[0][1], 4, 2, &ff_sprite_trajectory_tab[0][0], 4, 2, 128); INIT_VLC_STATIC(&mb_type_b_vlc, MB_TYPE_B_VLC_BITS, 4, &ff_mb_type_b_tab[0][1], 2, 1, &ff_mb_type_b_tab[0][0], 2, 1, 16); done = 1; } } int ff_mpeg4_frame_end(AVCodecContext *avctx, const uint8_t *buf, int buf_size) { Mpeg4DecContext *ctx = avctx->priv_data; MpegEncContext *s = &ctx->m; /* divx 5.01+ bitstream reorder stuff */ /* Since this clobbers the input buffer and hwaccel codecs still need the * data during hwaccel->end_frame we should not do this any earlier */ if (s->divx_packed) { int current_pos = s->gb.buffer == s->bitstream_buffer ? 0 : (get_bits_count(&s->gb) >> 3); int startcode_found = 0; if (buf_size - current_pos > 7) { int i; for (i = current_pos; i < buf_size - 4; i++) if (buf[i] == 0 && buf[i + 1] == 0 && buf[i + 2] == 1 && buf[i + 3] == 0xB6) { startcode_found = !(buf[i + 4] & 0x40); break; } } if (startcode_found) { if (!ctx->showed_packed_warning) { av_log(s->avctx, AV_LOG_INFO, "Video uses a non-standard and " "wasteful way to store B-frames ('packed B-frames'). " "Consider using the mpeg4_unpack_bframes bitstream filter without encoding but stream copy to fix it.\n"); ctx->showed_packed_warning = 1; } av_fast_padded_malloc(&s->bitstream_buffer, &s->allocated_bitstream_buffer_size, buf_size - current_pos); if (!s->bitstream_buffer) { s->bitstream_buffer_size = 0; return AVERROR(ENOMEM); } memcpy(s->bitstream_buffer, buf + current_pos, buf_size - current_pos); s->bitstream_buffer_size = buf_size - current_pos; } } return 0; } #if HAVE_THREADS static int mpeg4_update_thread_context(AVCodecContext *dst, const AVCodecContext *src) { Mpeg4DecContext *s = dst->priv_data; const Mpeg4DecContext *s1 = src->priv_data; int init = s->m.context_initialized; int ret = ff_mpeg_update_thread_context(dst, src); if (ret < 0) return ret; memcpy(((uint8_t*)s) + sizeof(MpegEncContext), ((uint8_t*)s1) + sizeof(MpegEncContext), sizeof(Mpeg4DecContext) - sizeof(MpegEncContext)); if (CONFIG_MPEG4_DECODER && !init && s1->xvid_build >= 0) ff_xvid_idct_init(&s->m.idsp, dst); return 0; } #endif static av_cold int init_studio_vlcs(Mpeg4DecContext *ctx) { int i, ret; for (i = 0; i < 12; i++) { ret = init_vlc(&ctx->studio_intra_tab[i], STUDIO_INTRA_BITS, 22, &ff_mpeg4_studio_intra[i][0][1], 4, 2, &ff_mpeg4_studio_intra[i][0][0], 4, 2, 0); if (ret < 0) return ret; } ret = init_vlc(&ctx->studio_luma_dc, STUDIO_INTRA_BITS, 19, &ff_mpeg4_studio_dc_luma[0][1], 4, 2, &ff_mpeg4_studio_dc_luma[0][0], 4, 2, 0); if (ret < 0) return ret; ret = init_vlc(&ctx->studio_chroma_dc, STUDIO_INTRA_BITS, 19, &ff_mpeg4_studio_dc_chroma[0][1], 4, 2, &ff_mpeg4_studio_dc_chroma[0][0], 4, 2, 0); if (ret < 0) return ret; return 0; } static av_cold int decode_init(AVCodecContext *avctx) { Mpeg4DecContext *ctx = avctx->priv_data; MpegEncContext *s = &ctx->m; int ret; ctx->divx_version = ctx->divx_build = ctx->xvid_build = ctx->lavc_build = -1; if ((ret = ff_h263_decode_init(avctx)) < 0) return ret; ff_mpeg4videodec_static_init(); if ((ret = init_studio_vlcs(ctx)) < 0) return ret; s->h263_pred = 1; s->low_delay = 0; /* default, might be overridden in the vol header during header parsing */ s->decode_mb = mpeg4_decode_mb; ctx->time_increment_bits = 4; /* default value for broken headers */ avctx->chroma_sample_location = AVCHROMA_LOC_LEFT; avctx->internal->allocate_progress = 1; return 0; } static av_cold int decode_end(AVCodecContext *avctx) { Mpeg4DecContext *ctx = avctx->priv_data; int i; if (!avctx->internal->is_copy) { for (i = 0; i < 12; i++) ff_free_vlc(&ctx->studio_intra_tab[i]); ff_free_vlc(&ctx->studio_luma_dc); ff_free_vlc(&ctx->studio_chroma_dc); } return ff_h263_decode_end(avctx); } static const AVOption mpeg4_options[] = { {"quarter_sample", "1/4 subpel MC", offsetof(MpegEncContext, quarter_sample), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, 0}, {"divx_packed", "divx style packed b frames", offsetof(MpegEncContext, divx_packed), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, 0}, {NULL} }; static const AVClass mpeg4_class = { .class_name = "MPEG4 Video Decoder", .item_name = av_default_item_name, .option = mpeg4_options, .version = LIBAVUTIL_VERSION_INT, }; AVCodec ff_mpeg4_decoder = { .name = "mpeg4", .long_name = NULL_IF_CONFIG_SMALL("MPEG-4 part 2"), .type = AVMEDIA_TYPE_VIDEO, .id = AV_CODEC_ID_MPEG4, .priv_data_size = sizeof(Mpeg4DecContext), .init = decode_init, .close = decode_end, .decode = ff_h263_decode_frame, .capabilities = AV_CODEC_CAP_DRAW_HORIZ_BAND | AV_CODEC_CAP_DR1 | AV_CODEC_CAP_TRUNCATED | AV_CODEC_CAP_DELAY | AV_CODEC_CAP_FRAME_THREADS, .caps_internal = FF_CODEC_CAP_SKIP_FRAME_FILL_PARAM, .flush = ff_mpeg_flush, .max_lowres = 3, .pix_fmts = ff_h263_hwaccel_pixfmt_list_420, .profiles = NULL_IF_CONFIG_SMALL(ff_mpeg4_video_profiles), .update_thread_context = ONLY_IF_THREADS_ENABLED(mpeg4_update_thread_context), .priv_class = &mpeg4_class, .hw_configs = (const AVCodecHWConfigInternal*[]) { #if CONFIG_MPEG4_NVDEC_HWACCEL HWACCEL_NVDEC(mpeg4), #endif #if CONFIG_MPEG4_VAAPI_HWACCEL HWACCEL_VAAPI(mpeg4), #endif #if CONFIG_MPEG4_VDPAU_HWACCEL HWACCEL_VDPAU(mpeg4), #endif #if CONFIG_MPEG4_VIDEOTOOLBOX_HWACCEL HWACCEL_VIDEOTOOLBOX(mpeg4), #endif NULL }, };
./CrossVul/dataset_final_sorted/CWE-20/c/good_191_0
crossvul-cpp_data_good_5213_0
/* $OpenBSD: auth-passwd.c,v 1.45 2016/07/21 01:39:35 dtucker Exp $ */ /* * Author: Tatu Ylonen <ylo@cs.hut.fi> * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland * All rights reserved * Password authentication. This file contains the functions to check whether * the password is valid for the user. * * As far as I am concerned, the code I have written for this software * can be used freely for any purpose. Any derived versions of this * software must be clearly marked as such, and if the derived work is * incompatible with the protocol description in the RFC file, it must be * called by a name other than "ssh" or "Secure Shell". * * Copyright (c) 1999 Dug Song. All rights reserved. * Copyright (c) 2000 Markus Friedl. 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 ``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 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 "includes.h" #include <sys/types.h> #include <pwd.h> #include <stdio.h> #include <string.h> #include <stdarg.h> #include "packet.h" #include "buffer.h" #include "log.h" #include "misc.h" #include "servconf.h" #include "key.h" #include "hostfile.h" #include "auth.h" #include "auth-options.h" extern Buffer loginmsg; extern ServerOptions options; #ifdef HAVE_LOGIN_CAP extern login_cap_t *lc; #endif #define DAY (24L * 60 * 60) /* 1 day in seconds */ #define TWO_WEEKS (2L * 7 * DAY) /* 2 weeks in seconds */ #define MAX_PASSWORD_LEN 1024 void disable_forwarding(void) { no_port_forwarding_flag = 1; no_agent_forwarding_flag = 1; no_x11_forwarding_flag = 1; } /* * Tries to authenticate the user using password. Returns true if * authentication succeeds. */ int auth_password(Authctxt *authctxt, const char *password) { struct passwd * pw = authctxt->pw; int result, ok = authctxt->valid; #if defined(USE_SHADOW) && defined(HAS_SHADOW_EXPIRE) static int expire_checked = 0; #endif if (strlen(password) > MAX_PASSWORD_LEN) return 0; #ifndef HAVE_CYGWIN if (pw->pw_uid == 0 && options.permit_root_login != PERMIT_YES) ok = 0; #endif if (*password == '\0' && options.permit_empty_passwd == 0) return 0; #ifdef KRB5 if (options.kerberos_authentication == 1) { int ret = auth_krb5_password(authctxt, password); if (ret == 1 || ret == 0) return ret && ok; /* Fall back to ordinary passwd authentication. */ } #endif #ifdef HAVE_CYGWIN { HANDLE hToken = cygwin_logon_user(pw, password); if (hToken == INVALID_HANDLE_VALUE) return 0; cygwin_set_impersonation_token(hToken); return ok; } #endif #ifdef USE_PAM if (options.use_pam) return (sshpam_auth_passwd(authctxt, password) && ok); #endif #if defined(USE_SHADOW) && defined(HAS_SHADOW_EXPIRE) if (!expire_checked) { expire_checked = 1; if (auth_shadow_pwexpired(authctxt)) authctxt->force_pwchange = 1; } #endif result = sys_auth_passwd(authctxt, password); if (authctxt->force_pwchange) disable_forwarding(); return (result && ok); } #ifdef BSD_AUTH static void warn_expiry(Authctxt *authctxt, auth_session_t *as) { char buf[256]; quad_t pwtimeleft, actimeleft, daysleft, pwwarntime, acwarntime; pwwarntime = acwarntime = TWO_WEEKS; pwtimeleft = auth_check_change(as); actimeleft = auth_check_expire(as); #ifdef HAVE_LOGIN_CAP if (authctxt->valid) { pwwarntime = login_getcaptime(lc, "password-warn", TWO_WEEKS, TWO_WEEKS); acwarntime = login_getcaptime(lc, "expire-warn", TWO_WEEKS, TWO_WEEKS); } #endif if (pwtimeleft != 0 && pwtimeleft < pwwarntime) { daysleft = pwtimeleft / DAY + 1; snprintf(buf, sizeof(buf), "Your password will expire in %lld day%s.\n", daysleft, daysleft == 1 ? "" : "s"); buffer_append(&loginmsg, buf, strlen(buf)); } if (actimeleft != 0 && actimeleft < acwarntime) { daysleft = actimeleft / DAY + 1; snprintf(buf, sizeof(buf), "Your account will expire in %lld day%s.\n", daysleft, daysleft == 1 ? "" : "s"); buffer_append(&loginmsg, buf, strlen(buf)); } } int sys_auth_passwd(Authctxt *authctxt, const char *password) { struct passwd *pw = authctxt->pw; auth_session_t *as; static int expire_checked = 0; as = auth_usercheck(pw->pw_name, authctxt->style, "auth-ssh", (char *)password); if (as == NULL) return (0); if (auth_getstate(as) & AUTH_PWEXPIRED) { auth_close(as); disable_forwarding(); authctxt->force_pwchange = 1; return (1); } else { if (!expire_checked) { expire_checked = 1; warn_expiry(authctxt, as); } return (auth_close(as)); } } #elif !defined(CUSTOM_SYS_AUTH_PASSWD) int sys_auth_passwd(Authctxt *authctxt, const char *password) { struct passwd *pw = authctxt->pw; char *encrypted_password, *salt = NULL; /* Just use the supplied fake password if authctxt is invalid */ char *pw_password = authctxt->valid ? shadow_pw(pw) : pw->pw_passwd; /* Check for users with no password. */ if (strcmp(pw_password, "") == 0 && strcmp(password, "") == 0) return (1); /* * Encrypt the candidate password using the proper salt, or pass a * NULL and let xcrypt pick one. */ if (authctxt->valid && pw_password[0] && pw_password[1]) salt = pw_password; encrypted_password = xcrypt(password, salt); /* * Authentication is accepted if the encrypted passwords * are identical. */ return encrypted_password != NULL && strcmp(encrypted_password, pw_password) == 0; } #endif
./CrossVul/dataset_final_sorted/CWE-20/c/good_5213_0
crossvul-cpp_data_bad_539_0
/* * 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_includes.h" /** @defgroup PI PI - Implementation of a packet iterator */ /*@{*/ /** @name Local static functions */ /*@{*/ /** Get next packet in layer-resolution-component-precinct order. @param pi packet iterator to modify @return returns false if pi pointed to the last packet or else returns true */ static opj_bool pi_next_lrcp(opj_pi_iterator_t * pi); /** Get next packet in resolution-layer-component-precinct order. @param pi packet iterator to modify @return returns false if pi pointed to the last packet or else returns true */ static opj_bool pi_next_rlcp(opj_pi_iterator_t * pi); /** Get next packet in resolution-precinct-component-layer order. @param pi packet iterator to modify @return returns false if pi pointed to the last packet or else returns true */ static opj_bool pi_next_rpcl(opj_pi_iterator_t * pi); /** Get next packet in precinct-component-resolution-layer order. @param pi packet iterator to modify @return returns false if pi pointed to the last packet or else returns true */ static opj_bool pi_next_pcrl(opj_pi_iterator_t * pi); /** Get next packet in component-precinct-resolution-layer order. @param pi packet iterator to modify @return returns false if pi pointed to the last packet or else returns true */ static opj_bool pi_next_cprl(opj_pi_iterator_t * pi); /*@}*/ /*@}*/ /* ========================================================== local functions ========================================================== */ static opj_bool pi_next_lrcp(opj_pi_iterator_t * pi) { opj_pi_comp_t *comp = NULL; opj_pi_resolution_t *res = NULL; long index = 0; if (!pi->first) { comp = &pi->comps[pi->compno]; res = &comp->resolutions[pi->resno]; goto LABEL_SKIP; } else { pi->first = 0; } for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) { for (pi->resno = pi->poc.resno0; pi->resno < pi->poc.resno1; pi->resno++) { for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) { comp = &pi->comps[pi->compno]; if (pi->resno >= comp->numresolutions) { continue; } res = &comp->resolutions[pi->resno]; if (!pi->tp_on) { pi->poc.precno1 = res->pw * res->ph; } for (pi->precno = pi->poc.precno0; pi->precno < pi->poc.precno1; pi->precno++) { index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p; if (!pi->include[index]) { pi->include[index] = 1; return OPJ_TRUE; } LABEL_SKIP: ; } } } } return OPJ_FALSE; } static opj_bool pi_next_rlcp(opj_pi_iterator_t * pi) { opj_pi_comp_t *comp = NULL; opj_pi_resolution_t *res = NULL; long index = 0; if (!pi->first) { comp = &pi->comps[pi->compno]; res = &comp->resolutions[pi->resno]; goto LABEL_SKIP; } else { pi->first = 0; } for (pi->resno = pi->poc.resno0; pi->resno < pi->poc.resno1; pi->resno++) { for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) { for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) { comp = &pi->comps[pi->compno]; if (pi->resno >= comp->numresolutions) { continue; } res = &comp->resolutions[pi->resno]; if (!pi->tp_on) { pi->poc.precno1 = res->pw * res->ph; } for (pi->precno = pi->poc.precno0; pi->precno < pi->poc.precno1; pi->precno++) { index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p; if (!pi->include[index]) { pi->include[index] = 1; return OPJ_TRUE; } LABEL_SKIP: ; } } } } return OPJ_FALSE; } static opj_bool pi_next_rpcl(opj_pi_iterator_t * pi) { opj_pi_comp_t *comp = NULL; opj_pi_resolution_t *res = NULL; long index = 0; if (!pi->first) { goto LABEL_SKIP; } else { int compno, resno; pi->first = 0; pi->dx = 0; pi->dy = 0; for (compno = 0; compno < pi->numcomps; compno++) { comp = &pi->comps[compno]; for (resno = 0; resno < comp->numresolutions; resno++) { int dx, dy; res = &comp->resolutions[resno]; dx = comp->dx * (1 << (res->pdx + comp->numresolutions - 1 - resno)); dy = comp->dy * (1 << (res->pdy + comp->numresolutions - 1 - resno)); pi->dx = !pi->dx ? dx : int_min(pi->dx, dx); pi->dy = !pi->dy ? dy : int_min(pi->dy, dy); } } } if (!pi->tp_on) { pi->poc.ty0 = pi->ty0; pi->poc.tx0 = pi->tx0; pi->poc.ty1 = pi->ty1; pi->poc.tx1 = pi->tx1; } for (pi->resno = pi->poc.resno0; pi->resno < pi->poc.resno1; pi->resno++) { for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1; pi->y += pi->dy - (pi->y % pi->dy)) { for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1; pi->x += pi->dx - (pi->x % pi->dx)) { for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) { int levelno; int trx0, try0; int trx1, try1; int rpx, rpy; int prci, prcj; comp = &pi->comps[pi->compno]; if (pi->resno >= comp->numresolutions) { continue; } res = &comp->resolutions[pi->resno]; levelno = comp->numresolutions - 1 - pi->resno; trx0 = int_ceildiv(pi->tx0, comp->dx << levelno); try0 = int_ceildiv(pi->ty0, comp->dy << levelno); trx1 = int_ceildiv(pi->tx1, comp->dx << levelno); try1 = int_ceildiv(pi->ty1, comp->dy << levelno); rpx = res->pdx + levelno; rpy = res->pdy + levelno; /* To avoid divisions by zero / undefined behaviour on shift */ if (rpx >= 31 || ((comp->dx << rpx) >> rpx) != comp->dx || rpy >= 31 || ((comp->dy << rpy) >> rpy) != comp->dy) { continue; } if (!((pi->y % (comp->dy << rpy) == 0) || ((pi->y == pi->ty0) && ((try0 << levelno) % (1 << rpy))))) { continue; } if (!((pi->x % (comp->dx << rpx) == 0) || ((pi->x == pi->tx0) && ((trx0 << levelno) % (1 << rpx))))) { continue; } if ((res->pw == 0) || (res->ph == 0)) { continue; } if ((trx0 == trx1) || (try0 == try1)) { continue; } prci = int_floordivpow2(int_ceildiv(pi->x, comp->dx << levelno), res->pdx) - int_floordivpow2(trx0, res->pdx); prcj = int_floordivpow2(int_ceildiv(pi->y, comp->dy << levelno), res->pdy) - int_floordivpow2(try0, res->pdy); pi->precno = prci + prcj * res->pw; for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) { index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p; if (!pi->include[index]) { pi->include[index] = 1; return OPJ_TRUE; } LABEL_SKIP: ; } } } } } return OPJ_FALSE; } static opj_bool pi_next_pcrl(opj_pi_iterator_t * pi) { opj_pi_comp_t *comp = NULL; opj_pi_resolution_t *res = NULL; long index = 0; if (!pi->first) { comp = &pi->comps[pi->compno]; goto LABEL_SKIP; } else { int compno, resno; pi->first = 0; pi->dx = 0; pi->dy = 0; for (compno = 0; compno < pi->numcomps; compno++) { comp = &pi->comps[compno]; for (resno = 0; resno < comp->numresolutions; resno++) { int dx, dy; res = &comp->resolutions[resno]; dx = comp->dx * (1 << (res->pdx + comp->numresolutions - 1 - resno)); dy = comp->dy * (1 << (res->pdy + comp->numresolutions - 1 - resno)); pi->dx = !pi->dx ? dx : int_min(pi->dx, dx); pi->dy = !pi->dy ? dy : int_min(pi->dy, dy); } } } if (!pi->tp_on) { pi->poc.ty0 = pi->ty0; pi->poc.tx0 = pi->tx0; pi->poc.ty1 = pi->ty1; pi->poc.tx1 = pi->tx1; } for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1; pi->y += pi->dy - (pi->y % pi->dy)) { for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1; pi->x += pi->dx - (pi->x % pi->dx)) { for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) { comp = &pi->comps[pi->compno]; for (pi->resno = pi->poc.resno0; pi->resno < int_min(pi->poc.resno1, comp->numresolutions); pi->resno++) { int levelno; int trx0, try0; int trx1, try1; int rpx, rpy; int prci, prcj; res = &comp->resolutions[pi->resno]; levelno = comp->numresolutions - 1 - pi->resno; trx0 = int_ceildiv(pi->tx0, comp->dx << levelno); try0 = int_ceildiv(pi->ty0, comp->dy << levelno); trx1 = int_ceildiv(pi->tx1, comp->dx << levelno); try1 = int_ceildiv(pi->ty1, comp->dy << levelno); rpx = res->pdx + levelno; rpy = res->pdy + levelno; /* To avoid divisions by zero / undefined behaviour on shift */ if (rpx >= 31 || ((comp->dx << rpx) >> rpx) != comp->dx || rpy >= 31 || ((comp->dy << rpy) >> rpy) != comp->dy) { continue; } if (!((pi->y % (comp->dy << rpy) == 0) || ((pi->y == pi->ty0) && ((try0 << levelno) % (1 << rpy))))) { continue; } if (!((pi->x % (comp->dx << rpx) == 0) || ((pi->x == pi->tx0) && ((trx0 << levelno) % (1 << rpx))))) { continue; } if ((res->pw == 0) || (res->ph == 0)) { continue; } if ((trx0 == trx1) || (try0 == try1)) { continue; } prci = int_floordivpow2(int_ceildiv(pi->x, comp->dx << levelno), res->pdx) - int_floordivpow2(trx0, res->pdx); prcj = int_floordivpow2(int_ceildiv(pi->y, comp->dy << levelno), res->pdy) - int_floordivpow2(try0, res->pdy); pi->precno = prci + prcj * res->pw; for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) { index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p; if (!pi->include[index]) { pi->include[index] = 1; return OPJ_TRUE; } LABEL_SKIP: ; } } } } } return OPJ_FALSE; } static opj_bool pi_next_cprl(opj_pi_iterator_t * pi) { opj_pi_comp_t *comp = NULL; opj_pi_resolution_t *res = NULL; long index = 0; if (!pi->first) { comp = &pi->comps[pi->compno]; goto LABEL_SKIP; } else { pi->first = 0; } for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) { int resno; comp = &pi->comps[pi->compno]; pi->dx = 0; pi->dy = 0; for (resno = 0; resno < comp->numresolutions; resno++) { int dx, dy; res = &comp->resolutions[resno]; dx = comp->dx * (1 << (res->pdx + comp->numresolutions - 1 - resno)); dy = comp->dy * (1 << (res->pdy + comp->numresolutions - 1 - resno)); pi->dx = !pi->dx ? dx : int_min(pi->dx, dx); pi->dy = !pi->dy ? dy : int_min(pi->dy, dy); } if (!pi->tp_on) { pi->poc.ty0 = pi->ty0; pi->poc.tx0 = pi->tx0; pi->poc.ty1 = pi->ty1; pi->poc.tx1 = pi->tx1; } for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1; pi->y += pi->dy - (pi->y % pi->dy)) { for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1; pi->x += pi->dx - (pi->x % pi->dx)) { for (pi->resno = pi->poc.resno0; pi->resno < int_min(pi->poc.resno1, comp->numresolutions); pi->resno++) { int levelno; int trx0, try0; int trx1, try1; int rpx, rpy; int prci, prcj; res = &comp->resolutions[pi->resno]; levelno = comp->numresolutions - 1 - pi->resno; trx0 = int_ceildiv(pi->tx0, comp->dx << levelno); try0 = int_ceildiv(pi->ty0, comp->dy << levelno); trx1 = int_ceildiv(pi->tx1, comp->dx << levelno); try1 = int_ceildiv(pi->ty1, comp->dy << levelno); rpx = res->pdx + levelno; rpy = res->pdy + levelno; /* To avoid divisions by zero / undefined behaviour on shift */ if (rpx >= 31 || ((comp->dx << rpx) >> rpx) != comp->dx || rpy >= 31 || ((comp->dy << rpy) >> rpy) != comp->dy) { continue; } if (!((pi->y % (comp->dy << rpy) == 0) || ((pi->y == pi->ty0) && ((try0 << levelno) % (1 << rpy))))) { continue; } if (!((pi->x % (comp->dx << rpx) == 0) || ((pi->x == pi->tx0) && ((trx0 << levelno) % (1 << rpx))))) { continue; } if ((res->pw == 0) || (res->ph == 0)) { continue; } if ((trx0 == trx1) || (try0 == try1)) { continue; } prci = int_floordivpow2(int_ceildiv(pi->x, comp->dx << levelno), res->pdx) - int_floordivpow2(trx0, res->pdx); prcj = int_floordivpow2(int_ceildiv(pi->y, comp->dy << levelno), res->pdy) - int_floordivpow2(try0, res->pdy); pi->precno = prci + prcj * res->pw; for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) { index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p; if (!pi->include[index]) { pi->include[index] = 1; return OPJ_TRUE; } LABEL_SKIP: ; } } } } } return OPJ_FALSE; } /* ========================================================== Packet iterator interface ========================================================== */ opj_pi_iterator_t *pi_create_decode(opj_image_t *image, opj_cp_t *cp, int tileno) { int p, q; int compno, resno, pino; opj_pi_iterator_t *pi = NULL; opj_tcp_t *tcp = NULL; opj_tccp_t *tccp = NULL; tcp = &cp->tcps[tileno]; pi = (opj_pi_iterator_t*) opj_calloc((tcp->numpocs + 1), sizeof(opj_pi_iterator_t)); if (!pi) { /* TODO: throw an error */ return NULL; } for (pino = 0; pino < tcp->numpocs + 1; pino++) { /* change */ int maxres = 0; int maxprec = 0; p = tileno % cp->tw; q = tileno / cp->tw; pi[pino].tx0 = int_max(cp->tx0 + p * cp->tdx, image->x0); pi[pino].ty0 = int_max(cp->ty0 + q * cp->tdy, image->y0); pi[pino].tx1 = int_min(cp->tx0 + (p + 1) * cp->tdx, image->x1); pi[pino].ty1 = int_min(cp->ty0 + (q + 1) * cp->tdy, image->y1); pi[pino].numcomps = image->numcomps; pi[pino].comps = (opj_pi_comp_t*) opj_calloc(image->numcomps, sizeof(opj_pi_comp_t)); if (!pi[pino].comps) { /* TODO: throw an error */ pi_destroy(pi, cp, tileno); return NULL; } for (compno = 0; compno < pi->numcomps; compno++) { int tcx0, tcy0, tcx1, tcy1; opj_pi_comp_t *comp = &pi[pino].comps[compno]; tccp = &tcp->tccps[compno]; comp->dx = image->comps[compno].dx; comp->dy = image->comps[compno].dy; comp->numresolutions = tccp->numresolutions; comp->resolutions = (opj_pi_resolution_t*) opj_calloc(comp->numresolutions, sizeof(opj_pi_resolution_t)); if (!comp->resolutions) { /* TODO: throw an error */ pi_destroy(pi, cp, tileno); return NULL; } tcx0 = int_ceildiv(pi->tx0, comp->dx); tcy0 = int_ceildiv(pi->ty0, comp->dy); tcx1 = int_ceildiv(pi->tx1, comp->dx); tcy1 = int_ceildiv(pi->ty1, comp->dy); if (comp->numresolutions > maxres) { maxres = comp->numresolutions; } for (resno = 0; resno < comp->numresolutions; resno++) { int levelno; int rx0, ry0, rx1, ry1; int px0, py0, px1, py1; opj_pi_resolution_t *res = &comp->resolutions[resno]; if (tccp->csty & J2K_CCP_CSTY_PRT) { res->pdx = tccp->prcw[resno]; res->pdy = tccp->prch[resno]; } else { res->pdx = 15; res->pdy = 15; } levelno = comp->numresolutions - 1 - resno; rx0 = int_ceildivpow2(tcx0, levelno); ry0 = int_ceildivpow2(tcy0, levelno); rx1 = int_ceildivpow2(tcx1, levelno); ry1 = int_ceildivpow2(tcy1, levelno); px0 = int_floordivpow2(rx0, res->pdx) << res->pdx; py0 = int_floordivpow2(ry0, res->pdy) << res->pdy; px1 = int_ceildivpow2(rx1, res->pdx) << res->pdx; py1 = int_ceildivpow2(ry1, res->pdy) << res->pdy; res->pw = (rx0 == rx1) ? 0 : ((px1 - px0) >> res->pdx); res->ph = (ry0 == ry1) ? 0 : ((py1 - py0) >> res->pdy); if (res->pw * res->ph > maxprec) { maxprec = res->pw * res->ph; } } } tccp = &tcp->tccps[0]; pi[pino].step_p = 1; pi[pino].step_c = maxprec * pi[pino].step_p; pi[pino].step_r = image->numcomps * pi[pino].step_c; pi[pino].step_l = maxres * pi[pino].step_r; if (pino == 0) { pi[pino].include = (short int*) opj_calloc(image->numcomps * maxres * tcp->numlayers * maxprec, sizeof(short int)); if (!pi[pino].include) { /* TODO: throw an error */ pi_destroy(pi, cp, tileno); return NULL; } } else { pi[pino].include = pi[pino - 1].include; } if (tcp->POC == 0) { pi[pino].first = 1; pi[pino].poc.resno0 = 0; pi[pino].poc.compno0 = 0; pi[pino].poc.layno1 = tcp->numlayers; pi[pino].poc.resno1 = maxres; pi[pino].poc.compno1 = image->numcomps; pi[pino].poc.prg = tcp->prg; } else { pi[pino].first = 1; pi[pino].poc.resno0 = tcp->pocs[pino].resno0; pi[pino].poc.compno0 = tcp->pocs[pino].compno0; pi[pino].poc.layno1 = tcp->pocs[pino].layno1; pi[pino].poc.resno1 = tcp->pocs[pino].resno1; pi[pino].poc.compno1 = tcp->pocs[pino].compno1; pi[pino].poc.prg = tcp->pocs[pino].prg; } pi[pino].poc.layno0 = 0; pi[pino].poc.precno0 = 0; pi[pino].poc.precno1 = maxprec; } return pi; } opj_pi_iterator_t *pi_initialise_encode(opj_image_t *image, opj_cp_t *cp, int tileno, J2K_T2_MODE t2_mode) { int p, q, pino; int compno, resno; int maxres = 0; int maxprec = 0; opj_pi_iterator_t *pi = NULL; opj_tcp_t *tcp = NULL; opj_tccp_t *tccp = NULL; tcp = &cp->tcps[tileno]; pi = (opj_pi_iterator_t*) opj_calloc((tcp->numpocs + 1), sizeof(opj_pi_iterator_t)); if (!pi) { return NULL; } pi->tp_on = cp->tp_on; for (pino = 0; pino < tcp->numpocs + 1 ; pino ++) { p = tileno % cp->tw; q = tileno / cp->tw; pi[pino].tx0 = int_max(cp->tx0 + p * cp->tdx, image->x0); pi[pino].ty0 = int_max(cp->ty0 + q * cp->tdy, image->y0); pi[pino].tx1 = int_min(cp->tx0 + (p + 1) * cp->tdx, image->x1); pi[pino].ty1 = int_min(cp->ty0 + (q + 1) * cp->tdy, image->y1); pi[pino].numcomps = image->numcomps; pi[pino].comps = (opj_pi_comp_t*) opj_calloc(image->numcomps, sizeof(opj_pi_comp_t)); if (!pi[pino].comps) { pi_destroy(pi, cp, tileno); return NULL; } for (compno = 0; compno < pi[pino].numcomps; compno++) { int tcx0, tcy0, tcx1, tcy1; opj_pi_comp_t *comp = &pi[pino].comps[compno]; tccp = &tcp->tccps[compno]; comp->dx = image->comps[compno].dx; comp->dy = image->comps[compno].dy; comp->numresolutions = tccp->numresolutions; comp->resolutions = (opj_pi_resolution_t*) opj_malloc(comp->numresolutions * sizeof(opj_pi_resolution_t)); if (!comp->resolutions) { pi_destroy(pi, cp, tileno); return NULL; } tcx0 = int_ceildiv(pi[pino].tx0, comp->dx); tcy0 = int_ceildiv(pi[pino].ty0, comp->dy); tcx1 = int_ceildiv(pi[pino].tx1, comp->dx); tcy1 = int_ceildiv(pi[pino].ty1, comp->dy); if (comp->numresolutions > maxres) { maxres = comp->numresolutions; } for (resno = 0; resno < comp->numresolutions; resno++) { int levelno; int rx0, ry0, rx1, ry1; int px0, py0, px1, py1; opj_pi_resolution_t *res = &comp->resolutions[resno]; if (tccp->csty & J2K_CCP_CSTY_PRT) { res->pdx = tccp->prcw[resno]; res->pdy = tccp->prch[resno]; } else { res->pdx = 15; res->pdy = 15; } levelno = comp->numresolutions - 1 - resno; rx0 = int_ceildivpow2(tcx0, levelno); ry0 = int_ceildivpow2(tcy0, levelno); rx1 = int_ceildivpow2(tcx1, levelno); ry1 = int_ceildivpow2(tcy1, levelno); px0 = int_floordivpow2(rx0, res->pdx) << res->pdx; py0 = int_floordivpow2(ry0, res->pdy) << res->pdy; px1 = int_ceildivpow2(rx1, res->pdx) << res->pdx; py1 = int_ceildivpow2(ry1, res->pdy) << res->pdy; res->pw = (rx0 == rx1) ? 0 : ((px1 - px0) >> res->pdx); res->ph = (ry0 == ry1) ? 0 : ((py1 - py0) >> res->pdy); if (res->pw * res->ph > maxprec) { maxprec = res->pw * res->ph; } } } tccp = &tcp->tccps[0]; pi[pino].step_p = 1; pi[pino].step_c = maxprec * pi[pino].step_p; pi[pino].step_r = image->numcomps * pi[pino].step_c; pi[pino].step_l = maxres * pi[pino].step_r; for (compno = 0; compno < pi->numcomps; compno++) { opj_pi_comp_t *comp = &pi->comps[compno]; for (resno = 0; resno < comp->numresolutions; resno++) { int dx, dy; opj_pi_resolution_t *res = &comp->resolutions[resno]; dx = comp->dx * (1 << (res->pdx + comp->numresolutions - 1 - resno)); dy = comp->dy * (1 << (res->pdy + comp->numresolutions - 1 - resno)); pi[pino].dx = !pi->dx ? dx : int_min(pi->dx, dx); pi[pino].dy = !pi->dy ? dy : int_min(pi->dy, dy); } } if (pino == 0) { pi[pino].include = (short int*) opj_calloc(tcp->numlayers * pi[pino].step_l, sizeof(short int)); if (!pi[pino].include) { pi_destroy(pi, cp, tileno); return NULL; } } else { pi[pino].include = pi[pino - 1].include; } /* Generation of boundaries for each prog flag*/ if (tcp->POC && (cp->cinema || ((!cp->cinema) && (t2_mode == FINAL_PASS)))) { tcp->pocs[pino].compS = tcp->pocs[pino].compno0; tcp->pocs[pino].compE = tcp->pocs[pino].compno1; tcp->pocs[pino].resS = tcp->pocs[pino].resno0; tcp->pocs[pino].resE = tcp->pocs[pino].resno1; tcp->pocs[pino].layE = tcp->pocs[pino].layno1; tcp->pocs[pino].prg = tcp->pocs[pino].prg1; if (pino > 0) { tcp->pocs[pino].layS = (tcp->pocs[pino].layE > tcp->pocs[pino - 1].layE) ? tcp->pocs[pino - 1].layE : 0; } } else { tcp->pocs[pino].compS = 0; tcp->pocs[pino].compE = image->numcomps; tcp->pocs[pino].resS = 0; tcp->pocs[pino].resE = maxres; tcp->pocs[pino].layS = 0; tcp->pocs[pino].layE = tcp->numlayers; tcp->pocs[pino].prg = tcp->prg; } tcp->pocs[pino].prcS = 0; tcp->pocs[pino].prcE = maxprec;; tcp->pocs[pino].txS = pi[pino].tx0; tcp->pocs[pino].txE = pi[pino].tx1; tcp->pocs[pino].tyS = pi[pino].ty0; tcp->pocs[pino].tyE = pi[pino].ty1; tcp->pocs[pino].dx = pi[pino].dx; tcp->pocs[pino].dy = pi[pino].dy; } return pi; } void pi_destroy(opj_pi_iterator_t *pi, opj_cp_t *cp, int tileno) { int compno, pino; opj_tcp_t *tcp = &cp->tcps[tileno]; if (pi) { for (pino = 0; pino < tcp->numpocs + 1; pino++) { if (pi[pino].comps) { for (compno = 0; compno < pi->numcomps; compno++) { opj_pi_comp_t *comp = &pi[pino].comps[compno]; if (comp->resolutions) { opj_free(comp->resolutions); } } opj_free(pi[pino].comps); } } if (pi->include) { opj_free(pi->include); } opj_free(pi); } } opj_bool pi_next(opj_pi_iterator_t * pi) { switch (pi->poc.prg) { case LRCP: return pi_next_lrcp(pi); case RLCP: return pi_next_rlcp(pi); case RPCL: return pi_next_rpcl(pi); case PCRL: return pi_next_pcrl(pi); case CPRL: return pi_next_cprl(pi); case PROG_UNKNOWN: return OPJ_FALSE; } return OPJ_FALSE; } opj_bool pi_create_encode(opj_pi_iterator_t *pi, opj_cp_t *cp, int tileno, int pino, int tpnum, int tppos, J2K_T2_MODE t2_mode, int cur_totnum_tp) { char prog[4]; int i; int incr_top = 1, resetX = 0; opj_tcp_t *tcps = &cp->tcps[tileno]; opj_poc_t *tcp = &tcps->pocs[pino]; pi[pino].first = 1; pi[pino].poc.prg = tcp->prg; switch (tcp->prg) { case CPRL: strncpy(prog, "CPRL", 4); break; case LRCP: strncpy(prog, "LRCP", 4); break; case PCRL: strncpy(prog, "PCRL", 4); break; case RLCP: strncpy(prog, "RLCP", 4); break; case RPCL: strncpy(prog, "RPCL", 4); break; case PROG_UNKNOWN: return OPJ_TRUE; } if (!(cp->tp_on && ((!cp->cinema && (t2_mode == FINAL_PASS)) || cp->cinema))) { pi[pino].poc.resno0 = tcp->resS; pi[pino].poc.resno1 = tcp->resE; pi[pino].poc.compno0 = tcp->compS; pi[pino].poc.compno1 = tcp->compE; pi[pino].poc.layno0 = tcp->layS; pi[pino].poc.layno1 = tcp->layE; pi[pino].poc.precno0 = tcp->prcS; pi[pino].poc.precno1 = tcp->prcE; pi[pino].poc.tx0 = tcp->txS; pi[pino].poc.ty0 = tcp->tyS; pi[pino].poc.tx1 = tcp->txE; pi[pino].poc.ty1 = tcp->tyE; } else { if (tpnum < cur_totnum_tp) { for (i = 3; i >= 0; i--) { switch (prog[i]) { case 'C': if (i > tppos) { pi[pino].poc.compno0 = tcp->compS; pi[pino].poc.compno1 = tcp->compE; } else { if (tpnum == 0) { tcp->comp_t = tcp->compS; pi[pino].poc.compno0 = tcp->comp_t; pi[pino].poc.compno1 = tcp->comp_t + 1; tcp->comp_t += 1; } else { if (incr_top == 1) { if (tcp->comp_t == tcp->compE) { tcp->comp_t = tcp->compS; pi[pino].poc.compno0 = tcp->comp_t; pi[pino].poc.compno1 = tcp->comp_t + 1; tcp->comp_t += 1; incr_top = 1; } else { pi[pino].poc.compno0 = tcp->comp_t; pi[pino].poc.compno1 = tcp->comp_t + 1; tcp->comp_t += 1; incr_top = 0; } } else { pi[pino].poc.compno0 = tcp->comp_t - 1; pi[pino].poc.compno1 = tcp->comp_t; } } } break; case 'R': if (i > tppos) { pi[pino].poc.resno0 = tcp->resS; pi[pino].poc.resno1 = tcp->resE; } else { if (tpnum == 0) { tcp->res_t = tcp->resS; pi[pino].poc.resno0 = tcp->res_t; pi[pino].poc.resno1 = tcp->res_t + 1; tcp->res_t += 1; } else { if (incr_top == 1) { if (tcp->res_t == tcp->resE) { tcp->res_t = tcp->resS; pi[pino].poc.resno0 = tcp->res_t; pi[pino].poc.resno1 = tcp->res_t + 1; tcp->res_t += 1; incr_top = 1; } else { pi[pino].poc.resno0 = tcp->res_t; pi[pino].poc.resno1 = tcp->res_t + 1; tcp->res_t += 1; incr_top = 0; } } else { pi[pino].poc.resno0 = tcp->res_t - 1; pi[pino].poc.resno1 = tcp->res_t; } } } break; case 'L': if (i > tppos) { pi[pino].poc.layno0 = tcp->layS; pi[pino].poc.layno1 = tcp->layE; } else { if (tpnum == 0) { tcp->lay_t = tcp->layS; pi[pino].poc.layno0 = tcp->lay_t; pi[pino].poc.layno1 = tcp->lay_t + 1; tcp->lay_t += 1; } else { if (incr_top == 1) { if (tcp->lay_t == tcp->layE) { tcp->lay_t = tcp->layS; pi[pino].poc.layno0 = tcp->lay_t; pi[pino].poc.layno1 = tcp->lay_t + 1; tcp->lay_t += 1; incr_top = 1; } else { pi[pino].poc.layno0 = tcp->lay_t; pi[pino].poc.layno1 = tcp->lay_t + 1; tcp->lay_t += 1; incr_top = 0; } } else { pi[pino].poc.layno0 = tcp->lay_t - 1; pi[pino].poc.layno1 = tcp->lay_t; } } } break; case 'P': switch (tcp->prg) { case LRCP: case RLCP: if (i > tppos) { pi[pino].poc.precno0 = tcp->prcS; pi[pino].poc.precno1 = tcp->prcE; } else { if (tpnum == 0) { tcp->prc_t = tcp->prcS; pi[pino].poc.precno0 = tcp->prc_t; pi[pino].poc.precno1 = tcp->prc_t + 1; tcp->prc_t += 1; } else { if (incr_top == 1) { if (tcp->prc_t == tcp->prcE) { tcp->prc_t = tcp->prcS; pi[pino].poc.precno0 = tcp->prc_t; pi[pino].poc.precno1 = tcp->prc_t + 1; tcp->prc_t += 1; incr_top = 1; } else { pi[pino].poc.precno0 = tcp->prc_t; pi[pino].poc.precno1 = tcp->prc_t + 1; tcp->prc_t += 1; incr_top = 0; } } else { pi[pino].poc.precno0 = tcp->prc_t - 1; pi[pino].poc.precno1 = tcp->prc_t; } } } break; default: if (i > tppos) { pi[pino].poc.tx0 = tcp->txS; pi[pino].poc.ty0 = tcp->tyS; pi[pino].poc.tx1 = tcp->txE; pi[pino].poc.ty1 = tcp->tyE; } else { if (tpnum == 0) { tcp->tx0_t = tcp->txS; tcp->ty0_t = tcp->tyS; pi[pino].poc.tx0 = tcp->tx0_t; pi[pino].poc.tx1 = tcp->tx0_t + tcp->dx - (tcp->tx0_t % tcp->dx); pi[pino].poc.ty0 = tcp->ty0_t; pi[pino].poc.ty1 = tcp->ty0_t + tcp->dy - (tcp->ty0_t % tcp->dy); tcp->tx0_t = pi[pino].poc.tx1; tcp->ty0_t = pi[pino].poc.ty1; } else { if (incr_top == 1) { if (tcp->tx0_t >= tcp->txE) { if (tcp->ty0_t >= tcp->tyE) { tcp->ty0_t = tcp->tyS; pi[pino].poc.ty0 = tcp->ty0_t; pi[pino].poc.ty1 = tcp->ty0_t + tcp->dy - (tcp->ty0_t % tcp->dy); tcp->ty0_t = pi[pino].poc.ty1; incr_top = 1; resetX = 1; } else { pi[pino].poc.ty0 = tcp->ty0_t; pi[pino].poc.ty1 = tcp->ty0_t + tcp->dy - (tcp->ty0_t % tcp->dy); tcp->ty0_t = pi[pino].poc.ty1; incr_top = 0; resetX = 1; } if (resetX == 1) { tcp->tx0_t = tcp->txS; pi[pino].poc.tx0 = tcp->tx0_t; pi[pino].poc.tx1 = tcp->tx0_t + tcp->dx - (tcp->tx0_t % tcp->dx); tcp->tx0_t = pi[pino].poc.tx1; } } else { pi[pino].poc.tx0 = tcp->tx0_t; pi[pino].poc.tx1 = tcp->tx0_t + tcp->dx - (tcp->tx0_t % tcp->dx); tcp->tx0_t = pi[pino].poc.tx1; pi[pino].poc.ty0 = tcp->ty0_t - tcp->dy - (tcp->ty0_t % tcp->dy); pi[pino].poc.ty1 = tcp->ty0_t ; incr_top = 0; } } else { pi[pino].poc.tx0 = tcp->tx0_t - tcp->dx - (tcp->tx0_t % tcp->dx); pi[pino].poc.tx1 = tcp->tx0_t ; pi[pino].poc.ty0 = tcp->ty0_t - tcp->dy - (tcp->ty0_t % tcp->dy); pi[pino].poc.ty1 = tcp->ty0_t ; } } } break; } break; } } } } return OPJ_FALSE; }
./CrossVul/dataset_final_sorted/CWE-20/c/bad_539_0
crossvul-cpp_data_good_1276_2
/* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains C code routines that are called by the parser ** to handle SELECT statements in SQLite. */ #include "sqliteInt.h" /* ** Trace output macros */ #if SELECTTRACE_ENABLED /***/ int sqlite3SelectTrace = 0; # define SELECTTRACE(K,P,S,X) \ if(sqlite3SelectTrace&(K)) \ sqlite3DebugPrintf("%u/%d/%p: ",(S)->selId,(P)->addrExplain,(S)),\ sqlite3DebugPrintf X #else # define SELECTTRACE(K,P,S,X) #endif /* ** An instance of the following object is used to record information about ** how to process the DISTINCT keyword, to simplify passing that information ** into the selectInnerLoop() routine. */ typedef struct DistinctCtx DistinctCtx; struct DistinctCtx { u8 isTnct; /* True if the DISTINCT keyword is present */ u8 eTnctType; /* One of the WHERE_DISTINCT_* operators */ int tabTnct; /* Ephemeral table used for DISTINCT processing */ int addrTnct; /* Address of OP_OpenEphemeral opcode for tabTnct */ }; /* ** An instance of the following object is used to record information about ** the ORDER BY (or GROUP BY) clause of query is being coded. ** ** The aDefer[] array is used by the sorter-references optimization. For ** example, assuming there is no index that can be used for the ORDER BY, ** for the query: ** ** SELECT a, bigblob FROM t1 ORDER BY a LIMIT 10; ** ** it may be more efficient to add just the "a" values to the sorter, and ** retrieve the associated "bigblob" values directly from table t1 as the ** 10 smallest "a" values are extracted from the sorter. ** ** When the sorter-reference optimization is used, there is one entry in the ** aDefer[] array for each database table that may be read as values are ** extracted from the sorter. */ typedef struct SortCtx SortCtx; struct SortCtx { ExprList *pOrderBy; /* The ORDER BY (or GROUP BY clause) */ int nOBSat; /* Number of ORDER BY terms satisfied by indices */ int iECursor; /* Cursor number for the sorter */ int regReturn; /* Register holding block-output return address */ int labelBkOut; /* Start label for the block-output subroutine */ int addrSortIndex; /* Address of the OP_SorterOpen or OP_OpenEphemeral */ int labelDone; /* Jump here when done, ex: LIMIT reached */ int labelOBLopt; /* Jump here when sorter is full */ u8 sortFlags; /* Zero or more SORTFLAG_* bits */ #ifdef SQLITE_ENABLE_SORTER_REFERENCES u8 nDefer; /* Number of valid entries in aDefer[] */ struct DeferredCsr { Table *pTab; /* Table definition */ int iCsr; /* Cursor number for table */ int nKey; /* Number of PK columns for table pTab (>=1) */ } aDefer[4]; #endif struct RowLoadInfo *pDeferredRowLoad; /* Deferred row loading info or NULL */ }; #define SORTFLAG_UseSorter 0x01 /* Use SorterOpen instead of OpenEphemeral */ /* ** Delete all the content of a Select structure. Deallocate the structure ** itself only if bFree is true. */ static void clearSelect(sqlite3 *db, Select *p, int bFree){ while( p ){ Select *pPrior = p->pPrior; sqlite3ExprListDelete(db, p->pEList); sqlite3SrcListDelete(db, p->pSrc); sqlite3ExprDelete(db, p->pWhere); sqlite3ExprListDelete(db, p->pGroupBy); sqlite3ExprDelete(db, p->pHaving); sqlite3ExprListDelete(db, p->pOrderBy); sqlite3ExprDelete(db, p->pLimit); #ifndef SQLITE_OMIT_WINDOWFUNC if( OK_IF_ALWAYS_TRUE(p->pWinDefn) ){ sqlite3WindowListDelete(db, p->pWinDefn); } assert( p->pWin==0 ); #endif if( OK_IF_ALWAYS_TRUE(p->pWith) ) sqlite3WithDelete(db, p->pWith); if( bFree ) sqlite3DbFreeNN(db, p); p = pPrior; bFree = 1; } } /* ** Initialize a SelectDest structure. */ void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){ pDest->eDest = (u8)eDest; pDest->iSDParm = iParm; pDest->zAffSdst = 0; pDest->iSdst = 0; pDest->nSdst = 0; } /* ** Allocate a new Select structure and return a pointer to that ** structure. */ Select *sqlite3SelectNew( Parse *pParse, /* Parsing context */ ExprList *pEList, /* which columns to include in the result */ SrcList *pSrc, /* the FROM clause -- which tables to scan */ Expr *pWhere, /* the WHERE clause */ ExprList *pGroupBy, /* the GROUP BY clause */ Expr *pHaving, /* the HAVING clause */ ExprList *pOrderBy, /* the ORDER BY clause */ u32 selFlags, /* Flag parameters, such as SF_Distinct */ Expr *pLimit /* LIMIT value. NULL means not used */ ){ Select *pNew; Select standin; pNew = sqlite3DbMallocRawNN(pParse->db, sizeof(*pNew) ); if( pNew==0 ){ assert( pParse->db->mallocFailed ); pNew = &standin; } if( pEList==0 ){ pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(pParse->db,TK_ASTERISK,0)); } pNew->pEList = pEList; pNew->op = TK_SELECT; pNew->selFlags = selFlags; pNew->iLimit = 0; pNew->iOffset = 0; pNew->selId = ++pParse->nSelect; pNew->addrOpenEphm[0] = -1; pNew->addrOpenEphm[1] = -1; pNew->nSelectRow = 0; if( pSrc==0 ) pSrc = sqlite3DbMallocZero(pParse->db, sizeof(*pSrc)); pNew->pSrc = pSrc; pNew->pWhere = pWhere; pNew->pGroupBy = pGroupBy; pNew->pHaving = pHaving; pNew->pOrderBy = pOrderBy; pNew->pPrior = 0; pNew->pNext = 0; pNew->pLimit = pLimit; pNew->pWith = 0; #ifndef SQLITE_OMIT_WINDOWFUNC pNew->pWin = 0; pNew->pWinDefn = 0; #endif if( pParse->db->mallocFailed ) { clearSelect(pParse->db, pNew, pNew!=&standin); pNew = 0; }else{ assert( pNew->pSrc!=0 || pParse->nErr>0 ); } assert( pNew!=&standin ); return pNew; } /* ** Delete the given Select structure and all of its substructures. */ void sqlite3SelectDelete(sqlite3 *db, Select *p){ if( OK_IF_ALWAYS_TRUE(p) ) clearSelect(db, p, 1); } /* ** Return a pointer to the right-most SELECT statement in a compound. */ static Select *findRightmost(Select *p){ while( p->pNext ) p = p->pNext; return p; } /* ** Given 1 to 3 identifiers preceding the JOIN keyword, determine the ** type of join. Return an integer constant that expresses that type ** in terms of the following bit values: ** ** JT_INNER ** JT_CROSS ** JT_OUTER ** JT_NATURAL ** JT_LEFT ** JT_RIGHT ** ** A full outer join is the combination of JT_LEFT and JT_RIGHT. ** ** If an illegal or unsupported join type is seen, then still return ** a join type, but put an error in the pParse structure. */ int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){ int jointype = 0; Token *apAll[3]; Token *p; /* 0123456789 123456789 123456789 123 */ static const char zKeyText[] = "naturaleftouterightfullinnercross"; static const struct { u8 i; /* Beginning of keyword text in zKeyText[] */ u8 nChar; /* Length of the keyword in characters */ u8 code; /* Join type mask */ } aKeyword[] = { /* natural */ { 0, 7, JT_NATURAL }, /* left */ { 6, 4, JT_LEFT|JT_OUTER }, /* outer */ { 10, 5, JT_OUTER }, /* right */ { 14, 5, JT_RIGHT|JT_OUTER }, /* full */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER }, /* inner */ { 23, 5, JT_INNER }, /* cross */ { 28, 5, JT_INNER|JT_CROSS }, }; int i, j; apAll[0] = pA; apAll[1] = pB; apAll[2] = pC; for(i=0; i<3 && apAll[i]; i++){ p = apAll[i]; for(j=0; j<ArraySize(aKeyword); j++){ if( p->n==aKeyword[j].nChar && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){ jointype |= aKeyword[j].code; break; } } testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 ); if( j>=ArraySize(aKeyword) ){ jointype |= JT_ERROR; break; } } if( (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) || (jointype & JT_ERROR)!=0 ){ const char *zSp = " "; assert( pB!=0 ); if( pC==0 ){ zSp++; } sqlite3ErrorMsg(pParse, "unknown or unsupported join type: " "%T %T%s%T", pA, pB, zSp, pC); jointype = JT_INNER; }else if( (jointype & JT_OUTER)!=0 && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){ sqlite3ErrorMsg(pParse, "RIGHT and FULL OUTER JOINs are not currently supported"); jointype = JT_INNER; } return jointype; } /* ** Return the index of a column in a table. Return -1 if the column ** is not contained in the table. */ static int columnIndex(Table *pTab, const char *zCol){ int i; for(i=0; i<pTab->nCol; i++){ if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i; } return -1; } /* ** Search the first N tables in pSrc, from left to right, looking for a ** table that has a column named zCol. ** ** When found, set *piTab and *piCol to the table index and column index ** of the matching column and return TRUE. ** ** If not found, return FALSE. */ static int tableAndColumnIndex( SrcList *pSrc, /* Array of tables to search */ int N, /* Number of tables in pSrc->a[] to search */ const char *zCol, /* Name of the column we are looking for */ int *piTab, /* Write index of pSrc->a[] here */ int *piCol /* Write index of pSrc->a[*piTab].pTab->aCol[] here */ ){ int i; /* For looping over tables in pSrc */ int iCol; /* Index of column matching zCol */ assert( (piTab==0)==(piCol==0) ); /* Both or neither are NULL */ for(i=0; i<N; i++){ iCol = columnIndex(pSrc->a[i].pTab, zCol); if( iCol>=0 ){ if( piTab ){ *piTab = i; *piCol = iCol; } return 1; } } return 0; } /* ** This function is used to add terms implied by JOIN syntax to the ** WHERE clause expression of a SELECT statement. The new term, which ** is ANDed with the existing WHERE clause, is of the form: ** ** (tab1.col1 = tab2.col2) ** ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is ** column iColRight of tab2. */ static void addWhereTerm( Parse *pParse, /* Parsing context */ SrcList *pSrc, /* List of tables in FROM clause */ int iLeft, /* Index of first table to join in pSrc */ int iColLeft, /* Index of column in first table */ int iRight, /* Index of second table in pSrc */ int iColRight, /* Index of column in second table */ int isOuterJoin, /* True if this is an OUTER join */ Expr **ppWhere /* IN/OUT: The WHERE clause to add to */ ){ sqlite3 *db = pParse->db; Expr *pE1; Expr *pE2; Expr *pEq; assert( iLeft<iRight ); assert( pSrc->nSrc>iRight ); assert( pSrc->a[iLeft].pTab ); assert( pSrc->a[iRight].pTab ); pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft); pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight); pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2); if( pEq && isOuterJoin ){ ExprSetProperty(pEq, EP_FromJoin); assert( !ExprHasProperty(pEq, EP_TokenOnly|EP_Reduced) ); ExprSetVVAProperty(pEq, EP_NoReduce); pEq->iRightJoinTable = (i16)pE2->iTable; } *ppWhere = sqlite3ExprAnd(pParse, *ppWhere, pEq); } /* ** Set the EP_FromJoin property on all terms of the given expression. ** And set the Expr.iRightJoinTable to iTable for every term in the ** expression. ** ** The EP_FromJoin property is used on terms of an expression to tell ** the LEFT OUTER JOIN processing logic that this term is part of the ** join restriction specified in the ON or USING clause and not a part ** of the more general WHERE clause. These terms are moved over to the ** WHERE clause during join processing but we need to remember that they ** originated in the ON or USING clause. ** ** The Expr.iRightJoinTable tells the WHERE clause processing that the ** expression depends on table iRightJoinTable even if that table is not ** explicitly mentioned in the expression. That information is needed ** for cases like this: ** ** SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5 ** ** The where clause needs to defer the handling of the t1.x=5 ** term until after the t2 loop of the join. In that way, a ** NULL t2 row will be inserted whenever t1.x!=5. If we do not ** defer the handling of t1.x=5, it will be processed immediately ** after the t1 loop and rows with t1.x!=5 will never appear in ** the output, which is incorrect. */ void sqlite3SetJoinExpr(Expr *p, int iTable){ while( p ){ ExprSetProperty(p, EP_FromJoin); assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) ); ExprSetVVAProperty(p, EP_NoReduce); p->iRightJoinTable = (i16)iTable; if( p->op==TK_FUNCTION && p->x.pList ){ int i; for(i=0; i<p->x.pList->nExpr; i++){ sqlite3SetJoinExpr(p->x.pList->a[i].pExpr, iTable); } } sqlite3SetJoinExpr(p->pLeft, iTable); p = p->pRight; } } /* Undo the work of sqlite3SetJoinExpr(). In the expression p, convert every ** term that is marked with EP_FromJoin and iRightJoinTable==iTable into ** an ordinary term that omits the EP_FromJoin mark. ** ** This happens when a LEFT JOIN is simplified into an ordinary JOIN. */ static void unsetJoinExpr(Expr *p, int iTable){ while( p ){ if( ExprHasProperty(p, EP_FromJoin) && (iTable<0 || p->iRightJoinTable==iTable) ){ ExprClearProperty(p, EP_FromJoin); } if( p->op==TK_FUNCTION && p->x.pList ){ int i; for(i=0; i<p->x.pList->nExpr; i++){ unsetJoinExpr(p->x.pList->a[i].pExpr, iTable); } } unsetJoinExpr(p->pLeft, iTable); p = p->pRight; } } /* ** This routine processes the join information for a SELECT statement. ** ON and USING clauses are converted into extra terms of the WHERE clause. ** NATURAL joins also create extra WHERE clause terms. ** ** The terms of a FROM clause are contained in the Select.pSrc structure. ** The left most table is the first entry in Select.pSrc. The right-most ** table is the last entry. The join operator is held in the entry to ** the left. Thus entry 0 contains the join operator for the join between ** entries 0 and 1. Any ON or USING clauses associated with the join are ** also attached to the left entry. ** ** This routine returns the number of errors encountered. */ static int sqliteProcessJoin(Parse *pParse, Select *p){ SrcList *pSrc; /* All tables in the FROM clause */ int i, j; /* Loop counters */ struct SrcList_item *pLeft; /* Left table being joined */ struct SrcList_item *pRight; /* Right table being joined */ pSrc = p->pSrc; pLeft = &pSrc->a[0]; pRight = &pLeft[1]; for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){ Table *pRightTab = pRight->pTab; int isOuter; if( NEVER(pLeft->pTab==0 || pRightTab==0) ) continue; isOuter = (pRight->fg.jointype & JT_OUTER)!=0; /* When the NATURAL keyword is present, add WHERE clause terms for ** every column that the two tables have in common. */ if( pRight->fg.jointype & JT_NATURAL ){ if( pRight->pOn || pRight->pUsing ){ sqlite3ErrorMsg(pParse, "a NATURAL join may not have " "an ON or USING clause", 0); return 1; } for(j=0; j<pRightTab->nCol; j++){ char *zName; /* Name of column in the right table */ int iLeft; /* Matching left table */ int iLeftCol; /* Matching column in the left table */ zName = pRightTab->aCol[j].zName; if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){ addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j, isOuter, &p->pWhere); } } } /* Disallow both ON and USING clauses in the same join */ if( pRight->pOn && pRight->pUsing ){ sqlite3ErrorMsg(pParse, "cannot have both ON and USING " "clauses in the same join"); return 1; } /* Add the ON clause to the end of the WHERE clause, connected by ** an AND operator. */ if( pRight->pOn ){ if( isOuter ) sqlite3SetJoinExpr(pRight->pOn, pRight->iCursor); p->pWhere = sqlite3ExprAnd(pParse, p->pWhere, pRight->pOn); pRight->pOn = 0; } /* Create extra terms on the WHERE clause for each column named ** in the USING clause. Example: If the two tables to be joined are ** A and B and the USING clause names X, Y, and Z, then add this ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z ** Report an error if any column mentioned in the USING clause is ** not contained in both tables to be joined. */ if( pRight->pUsing ){ IdList *pList = pRight->pUsing; for(j=0; j<pList->nId; j++){ char *zName; /* Name of the term in the USING clause */ int iLeft; /* Table on the left with matching column name */ int iLeftCol; /* Column number of matching column on the left */ int iRightCol; /* Column number of matching column on the right */ zName = pList->a[j].zName; iRightCol = columnIndex(pRightTab, zName); if( iRightCol<0 || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){ sqlite3ErrorMsg(pParse, "cannot join using column %s - column " "not present in both tables", zName); return 1; } addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol, isOuter, &p->pWhere); } } } return 0; } /* ** An instance of this object holds information (beyond pParse and pSelect) ** needed to load the next result row that is to be added to the sorter. */ typedef struct RowLoadInfo RowLoadInfo; struct RowLoadInfo { int regResult; /* Store results in array of registers here */ u8 ecelFlags; /* Flag argument to ExprCodeExprList() */ #ifdef SQLITE_ENABLE_SORTER_REFERENCES ExprList *pExtra; /* Extra columns needed by sorter refs */ int regExtraResult; /* Where to load the extra columns */ #endif }; /* ** This routine does the work of loading query data into an array of ** registers so that it can be added to the sorter. */ static void innerLoopLoadRow( Parse *pParse, /* Statement under construction */ Select *pSelect, /* The query being coded */ RowLoadInfo *pInfo /* Info needed to complete the row load */ ){ sqlite3ExprCodeExprList(pParse, pSelect->pEList, pInfo->regResult, 0, pInfo->ecelFlags); #ifdef SQLITE_ENABLE_SORTER_REFERENCES if( pInfo->pExtra ){ sqlite3ExprCodeExprList(pParse, pInfo->pExtra, pInfo->regExtraResult, 0, 0); sqlite3ExprListDelete(pParse->db, pInfo->pExtra); } #endif } /* ** Code the OP_MakeRecord instruction that generates the entry to be ** added into the sorter. ** ** Return the register in which the result is stored. */ static int makeSorterRecord( Parse *pParse, SortCtx *pSort, Select *pSelect, int regBase, int nBase ){ int nOBSat = pSort->nOBSat; Vdbe *v = pParse->pVdbe; int regOut = ++pParse->nMem; if( pSort->pDeferredRowLoad ){ innerLoopLoadRow(pParse, pSelect, pSort->pDeferredRowLoad); } sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase+nOBSat, nBase-nOBSat, regOut); return regOut; } /* ** Generate code that will push the record in registers regData ** through regData+nData-1 onto the sorter. */ static void pushOntoSorter( Parse *pParse, /* Parser context */ SortCtx *pSort, /* Information about the ORDER BY clause */ Select *pSelect, /* The whole SELECT statement */ int regData, /* First register holding data to be sorted */ int regOrigData, /* First register holding data before packing */ int nData, /* Number of elements in the regData data array */ int nPrefixReg /* No. of reg prior to regData available for use */ ){ Vdbe *v = pParse->pVdbe; /* Stmt under construction */ int bSeq = ((pSort->sortFlags & SORTFLAG_UseSorter)==0); int nExpr = pSort->pOrderBy->nExpr; /* No. of ORDER BY terms */ int nBase = nExpr + bSeq + nData; /* Fields in sorter record */ int regBase; /* Regs for sorter record */ int regRecord = 0; /* Assembled sorter record */ int nOBSat = pSort->nOBSat; /* ORDER BY terms to skip */ int op; /* Opcode to add sorter record to sorter */ int iLimit; /* LIMIT counter */ int iSkip = 0; /* End of the sorter insert loop */ assert( bSeq==0 || bSeq==1 ); /* Three cases: ** (1) The data to be sorted has already been packed into a Record ** by a prior OP_MakeRecord. In this case nData==1 and regData ** will be completely unrelated to regOrigData. ** (2) All output columns are included in the sort record. In that ** case regData==regOrigData. ** (3) Some output columns are omitted from the sort record due to ** the SQLITE_ENABLE_SORTER_REFERENCE optimization, or due to the ** SQLITE_ECEL_OMITREF optimization, or due to the ** SortCtx.pDeferredRowLoad optimiation. In any of these cases ** regOrigData is 0 to prevent this routine from trying to copy ** values that might not yet exist. */ assert( nData==1 || regData==regOrigData || regOrigData==0 ); if( nPrefixReg ){ assert( nPrefixReg==nExpr+bSeq ); regBase = regData - nPrefixReg; }else{ regBase = pParse->nMem + 1; pParse->nMem += nBase; } assert( pSelect->iOffset==0 || pSelect->iLimit!=0 ); iLimit = pSelect->iOffset ? pSelect->iOffset+1 : pSelect->iLimit; pSort->labelDone = sqlite3VdbeMakeLabel(pParse); sqlite3ExprCodeExprList(pParse, pSort->pOrderBy, regBase, regOrigData, SQLITE_ECEL_DUP | (regOrigData? SQLITE_ECEL_REF : 0)); if( bSeq ){ sqlite3VdbeAddOp2(v, OP_Sequence, pSort->iECursor, regBase+nExpr); } if( nPrefixReg==0 && nData>0 ){ sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+bSeq, nData); } if( nOBSat>0 ){ int regPrevKey; /* The first nOBSat columns of the previous row */ int addrFirst; /* Address of the OP_IfNot opcode */ int addrJmp; /* Address of the OP_Jump opcode */ VdbeOp *pOp; /* Opcode that opens the sorter */ int nKey; /* Number of sorting key columns, including OP_Sequence */ KeyInfo *pKI; /* Original KeyInfo on the sorter table */ regRecord = makeSorterRecord(pParse, pSort, pSelect, regBase, nBase); regPrevKey = pParse->nMem+1; pParse->nMem += pSort->nOBSat; nKey = nExpr - pSort->nOBSat + bSeq; if( bSeq ){ addrFirst = sqlite3VdbeAddOp1(v, OP_IfNot, regBase+nExpr); }else{ addrFirst = sqlite3VdbeAddOp1(v, OP_SequenceTest, pSort->iECursor); } VdbeCoverage(v); sqlite3VdbeAddOp3(v, OP_Compare, regPrevKey, regBase, pSort->nOBSat); pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex); if( pParse->db->mallocFailed ) return; pOp->p2 = nKey + nData; pKI = pOp->p4.pKeyInfo; memset(pKI->aSortFlags, 0, pKI->nKeyField); /* Makes OP_Jump testable */ sqlite3VdbeChangeP4(v, -1, (char*)pKI, P4_KEYINFO); testcase( pKI->nAllField > pKI->nKeyField+2 ); pOp->p4.pKeyInfo = sqlite3KeyInfoFromExprList(pParse,pSort->pOrderBy,nOBSat, pKI->nAllField-pKI->nKeyField-1); pOp = 0; /* Ensure pOp not used after sqltie3VdbeAddOp3() */ addrJmp = sqlite3VdbeCurrentAddr(v); sqlite3VdbeAddOp3(v, OP_Jump, addrJmp+1, 0, addrJmp+1); VdbeCoverage(v); pSort->labelBkOut = sqlite3VdbeMakeLabel(pParse); pSort->regReturn = ++pParse->nMem; sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut); sqlite3VdbeAddOp1(v, OP_ResetSorter, pSort->iECursor); if( iLimit ){ sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, pSort->labelDone); VdbeCoverage(v); } sqlite3VdbeJumpHere(v, addrFirst); sqlite3ExprCodeMove(pParse, regBase, regPrevKey, pSort->nOBSat); sqlite3VdbeJumpHere(v, addrJmp); } if( iLimit ){ /* At this point the values for the new sorter entry are stored ** in an array of registers. They need to be composed into a record ** and inserted into the sorter if either (a) there are currently ** less than LIMIT+OFFSET items or (b) the new record is smaller than ** the largest record currently in the sorter. If (b) is true and there ** are already LIMIT+OFFSET items in the sorter, delete the largest ** entry before inserting the new one. This way there are never more ** than LIMIT+OFFSET items in the sorter. ** ** If the new record does not need to be inserted into the sorter, ** jump to the next iteration of the loop. If the pSort->labelOBLopt ** value is not zero, then it is a label of where to jump. Otherwise, ** just bypass the row insert logic. See the header comment on the ** sqlite3WhereOrderByLimitOptLabel() function for additional info. */ int iCsr = pSort->iECursor; sqlite3VdbeAddOp2(v, OP_IfNotZero, iLimit, sqlite3VdbeCurrentAddr(v)+4); VdbeCoverage(v); sqlite3VdbeAddOp2(v, OP_Last, iCsr, 0); iSkip = sqlite3VdbeAddOp4Int(v, OP_IdxLE, iCsr, 0, regBase+nOBSat, nExpr-nOBSat); VdbeCoverage(v); sqlite3VdbeAddOp1(v, OP_Delete, iCsr); } if( regRecord==0 ){ regRecord = makeSorterRecord(pParse, pSort, pSelect, regBase, nBase); } if( pSort->sortFlags & SORTFLAG_UseSorter ){ op = OP_SorterInsert; }else{ op = OP_IdxInsert; } sqlite3VdbeAddOp4Int(v, op, pSort->iECursor, regRecord, regBase+nOBSat, nBase-nOBSat); if( iSkip ){ sqlite3VdbeChangeP2(v, iSkip, pSort->labelOBLopt ? pSort->labelOBLopt : sqlite3VdbeCurrentAddr(v)); } } /* ** Add code to implement the OFFSET */ static void codeOffset( Vdbe *v, /* Generate code into this VM */ int iOffset, /* Register holding the offset counter */ int iContinue /* Jump here to skip the current record */ ){ if( iOffset>0 ){ sqlite3VdbeAddOp3(v, OP_IfPos, iOffset, iContinue, 1); VdbeCoverage(v); VdbeComment((v, "OFFSET")); } } /* ** Add code that will check to make sure the N registers starting at iMem ** form a distinct entry. iTab is a sorting index that holds previously ** seen combinations of the N values. A new entry is made in iTab ** if the current N values are new. ** ** A jump to addrRepeat is made and the N+1 values are popped from the ** stack if the top N elements are not distinct. */ static void codeDistinct( Parse *pParse, /* Parsing and code generating context */ int iTab, /* A sorting index used to test for distinctness */ int addrRepeat, /* Jump to here if not distinct */ int N, /* Number of elements */ int iMem /* First element */ ){ Vdbe *v; int r1; v = pParse->pVdbe; r1 = sqlite3GetTempReg(pParse); sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N); VdbeCoverage(v); sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1); sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iTab, r1, iMem, N); sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT); sqlite3ReleaseTempReg(pParse, r1); } #ifdef SQLITE_ENABLE_SORTER_REFERENCES /* ** This function is called as part of inner-loop generation for a SELECT ** statement with an ORDER BY that is not optimized by an index. It ** determines the expressions, if any, that the sorter-reference ** optimization should be used for. The sorter-reference optimization ** is used for SELECT queries like: ** ** SELECT a, bigblob FROM t1 ORDER BY a LIMIT 10 ** ** If the optimization is used for expression "bigblob", then instead of ** storing values read from that column in the sorter records, the PK of ** the row from table t1 is stored instead. Then, as records are extracted from ** the sorter to return to the user, the required value of bigblob is ** retrieved directly from table t1. If the values are very large, this ** can be more efficient than storing them directly in the sorter records. ** ** The ExprList_item.bSorterRef flag is set for each expression in pEList ** for which the sorter-reference optimization should be enabled. ** Additionally, the pSort->aDefer[] array is populated with entries ** for all cursors required to evaluate all selected expressions. Finally. ** output variable (*ppExtra) is set to an expression list containing ** expressions for all extra PK values that should be stored in the ** sorter records. */ static void selectExprDefer( Parse *pParse, /* Leave any error here */ SortCtx *pSort, /* Sorter context */ ExprList *pEList, /* Expressions destined for sorter */ ExprList **ppExtra /* Expressions to append to sorter record */ ){ int i; int nDefer = 0; ExprList *pExtra = 0; for(i=0; i<pEList->nExpr; i++){ struct ExprList_item *pItem = &pEList->a[i]; if( pItem->u.x.iOrderByCol==0 ){ Expr *pExpr = pItem->pExpr; Table *pTab = pExpr->y.pTab; if( pExpr->op==TK_COLUMN && pExpr->iColumn>=0 && pTab && !IsVirtual(pTab) && (pTab->aCol[pExpr->iColumn].colFlags & COLFLAG_SORTERREF) ){ int j; for(j=0; j<nDefer; j++){ if( pSort->aDefer[j].iCsr==pExpr->iTable ) break; } if( j==nDefer ){ if( nDefer==ArraySize(pSort->aDefer) ){ continue; }else{ int nKey = 1; int k; Index *pPk = 0; if( !HasRowid(pTab) ){ pPk = sqlite3PrimaryKeyIndex(pTab); nKey = pPk->nKeyCol; } for(k=0; k<nKey; k++){ Expr *pNew = sqlite3PExpr(pParse, TK_COLUMN, 0, 0); if( pNew ){ pNew->iTable = pExpr->iTable; pNew->y.pTab = pExpr->y.pTab; pNew->iColumn = pPk ? pPk->aiColumn[k] : -1; pExtra = sqlite3ExprListAppend(pParse, pExtra, pNew); } } pSort->aDefer[nDefer].pTab = pExpr->y.pTab; pSort->aDefer[nDefer].iCsr = pExpr->iTable; pSort->aDefer[nDefer].nKey = nKey; nDefer++; } } pItem->bSorterRef = 1; } } } pSort->nDefer = (u8)nDefer; *ppExtra = pExtra; } #endif /* ** This routine generates the code for the inside of the inner loop ** of a SELECT. ** ** If srcTab is negative, then the p->pEList expressions ** are evaluated in order to get the data for this row. If srcTab is ** zero or more, then data is pulled from srcTab and p->pEList is used only ** to get the number of columns and the collation sequence for each column. */ static void selectInnerLoop( Parse *pParse, /* The parser context */ Select *p, /* The complete select statement being coded */ int srcTab, /* Pull data from this table if non-negative */ SortCtx *pSort, /* If not NULL, info on how to process ORDER BY */ DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */ SelectDest *pDest, /* How to dispose of the results */ int iContinue, /* Jump here to continue with next row */ int iBreak /* Jump here to break out of the inner loop */ ){ Vdbe *v = pParse->pVdbe; int i; int hasDistinct; /* True if the DISTINCT keyword is present */ int eDest = pDest->eDest; /* How to dispose of results */ int iParm = pDest->iSDParm; /* First argument to disposal method */ int nResultCol; /* Number of result columns */ int nPrefixReg = 0; /* Number of extra registers before regResult */ RowLoadInfo sRowLoadInfo; /* Info for deferred row loading */ /* Usually, regResult is the first cell in an array of memory cells ** containing the current result row. In this case regOrig is set to the ** same value. However, if the results are being sent to the sorter, the ** values for any expressions that are also part of the sort-key are omitted ** from this array. In this case regOrig is set to zero. */ int regResult; /* Start of memory holding current results */ int regOrig; /* Start of memory holding full result (or 0) */ assert( v ); assert( p->pEList!=0 ); hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP; if( pSort && pSort->pOrderBy==0 ) pSort = 0; if( pSort==0 && !hasDistinct ){ assert( iContinue!=0 ); codeOffset(v, p->iOffset, iContinue); } /* Pull the requested columns. */ nResultCol = p->pEList->nExpr; if( pDest->iSdst==0 ){ if( pSort ){ nPrefixReg = pSort->pOrderBy->nExpr; if( !(pSort->sortFlags & SORTFLAG_UseSorter) ) nPrefixReg++; pParse->nMem += nPrefixReg; } pDest->iSdst = pParse->nMem+1; pParse->nMem += nResultCol; }else if( pDest->iSdst+nResultCol > pParse->nMem ){ /* This is an error condition that can result, for example, when a SELECT ** on the right-hand side of an INSERT contains more result columns than ** there are columns in the table on the left. The error will be caught ** and reported later. But we need to make sure enough memory is allocated ** to avoid other spurious errors in the meantime. */ pParse->nMem += nResultCol; } pDest->nSdst = nResultCol; regOrig = regResult = pDest->iSdst; if( srcTab>=0 ){ for(i=0; i<nResultCol; i++){ sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i); VdbeComment((v, "%s", p->pEList->a[i].zName)); } }else if( eDest!=SRT_Exists ){ #ifdef SQLITE_ENABLE_SORTER_REFERENCES ExprList *pExtra = 0; #endif /* If the destination is an EXISTS(...) expression, the actual ** values returned by the SELECT are not required. */ u8 ecelFlags; /* "ecel" is an abbreviation of "ExprCodeExprList" */ ExprList *pEList; if( eDest==SRT_Mem || eDest==SRT_Output || eDest==SRT_Coroutine ){ ecelFlags = SQLITE_ECEL_DUP; }else{ ecelFlags = 0; } if( pSort && hasDistinct==0 && eDest!=SRT_EphemTab && eDest!=SRT_Table ){ /* For each expression in p->pEList that is a copy of an expression in ** the ORDER BY clause (pSort->pOrderBy), set the associated ** iOrderByCol value to one more than the index of the ORDER BY ** expression within the sort-key that pushOntoSorter() will generate. ** This allows the p->pEList field to be omitted from the sorted record, ** saving space and CPU cycles. */ ecelFlags |= (SQLITE_ECEL_OMITREF|SQLITE_ECEL_REF); for(i=pSort->nOBSat; i<pSort->pOrderBy->nExpr; i++){ int j; if( (j = pSort->pOrderBy->a[i].u.x.iOrderByCol)>0 ){ p->pEList->a[j-1].u.x.iOrderByCol = i+1-pSort->nOBSat; } } #ifdef SQLITE_ENABLE_SORTER_REFERENCES selectExprDefer(pParse, pSort, p->pEList, &pExtra); if( pExtra && pParse->db->mallocFailed==0 ){ /* If there are any extra PK columns to add to the sorter records, ** allocate extra memory cells and adjust the OpenEphemeral ** instruction to account for the larger records. This is only ** required if there are one or more WITHOUT ROWID tables with ** composite primary keys in the SortCtx.aDefer[] array. */ VdbeOp *pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex); pOp->p2 += (pExtra->nExpr - pSort->nDefer); pOp->p4.pKeyInfo->nAllField += (pExtra->nExpr - pSort->nDefer); pParse->nMem += pExtra->nExpr; } #endif /* Adjust nResultCol to account for columns that are omitted ** from the sorter by the optimizations in this branch */ pEList = p->pEList; for(i=0; i<pEList->nExpr; i++){ if( pEList->a[i].u.x.iOrderByCol>0 #ifdef SQLITE_ENABLE_SORTER_REFERENCES || pEList->a[i].bSorterRef #endif ){ nResultCol--; regOrig = 0; } } testcase( regOrig ); testcase( eDest==SRT_Set ); testcase( eDest==SRT_Mem ); testcase( eDest==SRT_Coroutine ); testcase( eDest==SRT_Output ); assert( eDest==SRT_Set || eDest==SRT_Mem || eDest==SRT_Coroutine || eDest==SRT_Output ); } sRowLoadInfo.regResult = regResult; sRowLoadInfo.ecelFlags = ecelFlags; #ifdef SQLITE_ENABLE_SORTER_REFERENCES sRowLoadInfo.pExtra = pExtra; sRowLoadInfo.regExtraResult = regResult + nResultCol; if( pExtra ) nResultCol += pExtra->nExpr; #endif if( p->iLimit && (ecelFlags & SQLITE_ECEL_OMITREF)!=0 && nPrefixReg>0 ){ assert( pSort!=0 ); assert( hasDistinct==0 ); pSort->pDeferredRowLoad = &sRowLoadInfo; regOrig = 0; }else{ innerLoopLoadRow(pParse, p, &sRowLoadInfo); } } /* If the DISTINCT keyword was present on the SELECT statement ** and this row has been seen before, then do not make this row ** part of the result. */ if( hasDistinct ){ switch( pDistinct->eTnctType ){ case WHERE_DISTINCT_ORDERED: { VdbeOp *pOp; /* No longer required OpenEphemeral instr. */ int iJump; /* Jump destination */ int regPrev; /* Previous row content */ /* Allocate space for the previous row */ regPrev = pParse->nMem+1; pParse->nMem += nResultCol; /* Change the OP_OpenEphemeral coded earlier to an OP_Null ** sets the MEM_Cleared bit on the first register of the ** previous value. This will cause the OP_Ne below to always ** fail on the first iteration of the loop even if the first ** row is all NULLs. */ sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct); pOp = sqlite3VdbeGetOp(v, pDistinct->addrTnct); pOp->opcode = OP_Null; pOp->p1 = 1; pOp->p2 = regPrev; pOp = 0; /* Ensure pOp is not used after sqlite3VdbeAddOp() */ iJump = sqlite3VdbeCurrentAddr(v) + nResultCol; for(i=0; i<nResultCol; i++){ CollSeq *pColl = sqlite3ExprCollSeq(pParse, p->pEList->a[i].pExpr); if( i<nResultCol-1 ){ sqlite3VdbeAddOp3(v, OP_Ne, regResult+i, iJump, regPrev+i); VdbeCoverage(v); }else{ sqlite3VdbeAddOp3(v, OP_Eq, regResult+i, iContinue, regPrev+i); VdbeCoverage(v); } sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ); sqlite3VdbeChangeP5(v, SQLITE_NULLEQ); } assert( sqlite3VdbeCurrentAddr(v)==iJump || pParse->db->mallocFailed ); sqlite3VdbeAddOp3(v, OP_Copy, regResult, regPrev, nResultCol-1); break; } case WHERE_DISTINCT_UNIQUE: { sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct); break; } default: { assert( pDistinct->eTnctType==WHERE_DISTINCT_UNORDERED ); codeDistinct(pParse, pDistinct->tabTnct, iContinue, nResultCol, regResult); break; } } if( pSort==0 ){ codeOffset(v, p->iOffset, iContinue); } } switch( eDest ){ /* In this mode, write each query result to the key of the temporary ** table iParm. */ #ifndef SQLITE_OMIT_COMPOUND_SELECT case SRT_Union: { int r1; r1 = sqlite3GetTempReg(pParse); sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1); sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, nResultCol); sqlite3ReleaseTempReg(pParse, r1); break; } /* Construct a record from the query result, but instead of ** saving that record, use it as a key to delete elements from ** the temporary table iParm. */ case SRT_Except: { sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nResultCol); break; } #endif /* SQLITE_OMIT_COMPOUND_SELECT */ /* Store the result as data using a unique key. */ case SRT_Fifo: case SRT_DistFifo: case SRT_Table: case SRT_EphemTab: { int r1 = sqlite3GetTempRange(pParse, nPrefixReg+1); testcase( eDest==SRT_Table ); testcase( eDest==SRT_EphemTab ); testcase( eDest==SRT_Fifo ); testcase( eDest==SRT_DistFifo ); sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1+nPrefixReg); #ifndef SQLITE_OMIT_CTE if( eDest==SRT_DistFifo ){ /* If the destination is DistFifo, then cursor (iParm+1) is open ** on an ephemeral index. If the current row is already present ** in the index, do not write it to the output. If not, add the ** current row to the index and proceed with writing it to the ** output table as well. */ int addr = sqlite3VdbeCurrentAddr(v) + 4; sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, addr, r1, 0); VdbeCoverage(v); sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm+1, r1,regResult,nResultCol); assert( pSort==0 ); } #endif if( pSort ){ assert( regResult==regOrig ); pushOntoSorter(pParse, pSort, p, r1+nPrefixReg, regOrig, 1, nPrefixReg); }else{ int r2 = sqlite3GetTempReg(pParse); sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2); sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2); sqlite3VdbeChangeP5(v, OPFLAG_APPEND); sqlite3ReleaseTempReg(pParse, r2); } sqlite3ReleaseTempRange(pParse, r1, nPrefixReg+1); break; } #ifndef SQLITE_OMIT_SUBQUERY /* If we are creating a set for an "expr IN (SELECT ...)" construct, ** then there should be a single item on the stack. Write this ** item into the set table with bogus data. */ case SRT_Set: { if( pSort ){ /* At first glance you would think we could optimize out the ** ORDER BY in this case since the order of entries in the set ** does not matter. But there might be a LIMIT clause, in which ** case the order does matter */ pushOntoSorter( pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg); }else{ int r1 = sqlite3GetTempReg(pParse); assert( sqlite3Strlen30(pDest->zAffSdst)==nResultCol ); sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, nResultCol, r1, pDest->zAffSdst, nResultCol); sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, nResultCol); sqlite3ReleaseTempReg(pParse, r1); } break; } /* If any row exist in the result set, record that fact and abort. */ case SRT_Exists: { sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm); /* The LIMIT clause will terminate the loop for us */ break; } /* If this is a scalar select that is part of an expression, then ** store the results in the appropriate memory cell or array of ** memory cells and break out of the scan loop. */ case SRT_Mem: { if( pSort ){ assert( nResultCol<=pDest->nSdst ); pushOntoSorter( pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg); }else{ assert( nResultCol==pDest->nSdst ); assert( regResult==iParm ); /* The LIMIT clause will jump out of the loop for us */ } break; } #endif /* #ifndef SQLITE_OMIT_SUBQUERY */ case SRT_Coroutine: /* Send data to a co-routine */ case SRT_Output: { /* Return the results */ testcase( eDest==SRT_Coroutine ); testcase( eDest==SRT_Output ); if( pSort ){ pushOntoSorter(pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg); }else if( eDest==SRT_Coroutine ){ sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm); }else{ sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nResultCol); } break; } #ifndef SQLITE_OMIT_CTE /* Write the results into a priority queue that is order according to ** pDest->pOrderBy (in pSO). pDest->iSDParm (in iParm) is the cursor for an ** index with pSO->nExpr+2 columns. Build a key using pSO for the first ** pSO->nExpr columns, then make sure all keys are unique by adding a ** final OP_Sequence column. The last column is the record as a blob. */ case SRT_DistQueue: case SRT_Queue: { int nKey; int r1, r2, r3; int addrTest = 0; ExprList *pSO; pSO = pDest->pOrderBy; assert( pSO ); nKey = pSO->nExpr; r1 = sqlite3GetTempReg(pParse); r2 = sqlite3GetTempRange(pParse, nKey+2); r3 = r2+nKey+1; if( eDest==SRT_DistQueue ){ /* If the destination is DistQueue, then cursor (iParm+1) is open ** on a second ephemeral index that holds all values every previously ** added to the queue. */ addrTest = sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, 0, regResult, nResultCol); VdbeCoverage(v); } sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r3); if( eDest==SRT_DistQueue ){ sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r3); sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT); } for(i=0; i<nKey; i++){ sqlite3VdbeAddOp2(v, OP_SCopy, regResult + pSO->a[i].u.x.iOrderByCol - 1, r2+i); } sqlite3VdbeAddOp2(v, OP_Sequence, iParm, r2+nKey); sqlite3VdbeAddOp3(v, OP_MakeRecord, r2, nKey+2, r1); sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, r2, nKey+2); if( addrTest ) sqlite3VdbeJumpHere(v, addrTest); sqlite3ReleaseTempReg(pParse, r1); sqlite3ReleaseTempRange(pParse, r2, nKey+2); break; } #endif /* SQLITE_OMIT_CTE */ #if !defined(SQLITE_OMIT_TRIGGER) /* Discard the results. This is used for SELECT statements inside ** the body of a TRIGGER. The purpose of such selects is to call ** user-defined functions that have side effects. We do not care ** about the actual results of the select. */ default: { assert( eDest==SRT_Discard ); break; } #endif } /* Jump to the end of the loop if the LIMIT is reached. Except, if ** there is a sorter, in which case the sorter has already limited ** the output for us. */ if( pSort==0 && p->iLimit ){ sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v); } } /* ** Allocate a KeyInfo object sufficient for an index of N key columns and ** X extra columns. */ KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N, int X){ int nExtra = (N+X)*(sizeof(CollSeq*)+1) - sizeof(CollSeq*); KeyInfo *p = sqlite3DbMallocRawNN(db, sizeof(KeyInfo) + nExtra); if( p ){ p->aSortFlags = (u8*)&p->aColl[N+X]; p->nKeyField = (u16)N; p->nAllField = (u16)(N+X); p->enc = ENC(db); p->db = db; p->nRef = 1; memset(&p[1], 0, nExtra); }else{ sqlite3OomFault(db); } return p; } /* ** Deallocate a KeyInfo object */ void sqlite3KeyInfoUnref(KeyInfo *p){ if( p ){ assert( p->nRef>0 ); p->nRef--; if( p->nRef==0 ) sqlite3DbFreeNN(p->db, p); } } /* ** Make a new pointer to a KeyInfo object */ KeyInfo *sqlite3KeyInfoRef(KeyInfo *p){ if( p ){ assert( p->nRef>0 ); p->nRef++; } return p; } #ifdef SQLITE_DEBUG /* ** Return TRUE if a KeyInfo object can be change. The KeyInfo object ** can only be changed if this is just a single reference to the object. ** ** This routine is used only inside of assert() statements. */ int sqlite3KeyInfoIsWriteable(KeyInfo *p){ return p->nRef==1; } #endif /* SQLITE_DEBUG */ /* ** Given an expression list, generate a KeyInfo structure that records ** the collating sequence for each expression in that expression list. ** ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting ** KeyInfo structure is appropriate for initializing a virtual index to ** implement that clause. If the ExprList is the result set of a SELECT ** then the KeyInfo structure is appropriate for initializing a virtual ** index to implement a DISTINCT test. ** ** Space to hold the KeyInfo structure is obtained from malloc. The calling ** function is responsible for seeing that this structure is eventually ** freed. */ KeyInfo *sqlite3KeyInfoFromExprList( Parse *pParse, /* Parsing context */ ExprList *pList, /* Form the KeyInfo object from this ExprList */ int iStart, /* Begin with this column of pList */ int nExtra /* Add this many extra columns to the end */ ){ int nExpr; KeyInfo *pInfo; struct ExprList_item *pItem; sqlite3 *db = pParse->db; int i; nExpr = pList->nExpr; pInfo = sqlite3KeyInfoAlloc(db, nExpr-iStart, nExtra+1); if( pInfo ){ assert( sqlite3KeyInfoIsWriteable(pInfo) ); for(i=iStart, pItem=pList->a+iStart; i<nExpr; i++, pItem++){ pInfo->aColl[i-iStart] = sqlite3ExprNNCollSeq(pParse, pItem->pExpr); pInfo->aSortFlags[i-iStart] = pItem->sortFlags; } } return pInfo; } /* ** Name of the connection operator, used for error messages. */ static const char *selectOpName(int id){ char *z; switch( id ){ case TK_ALL: z = "UNION ALL"; break; case TK_INTERSECT: z = "INTERSECT"; break; case TK_EXCEPT: z = "EXCEPT"; break; default: z = "UNION"; break; } return z; } #ifndef SQLITE_OMIT_EXPLAIN /* ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function ** is a no-op. Otherwise, it adds a single row of output to the EQP result, ** where the caption is of the form: ** ** "USE TEMP B-TREE FOR xxx" ** ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which ** is determined by the zUsage argument. */ static void explainTempTable(Parse *pParse, const char *zUsage){ ExplainQueryPlan((pParse, 0, "USE TEMP B-TREE FOR %s", zUsage)); } /* ** Assign expression b to lvalue a. A second, no-op, version of this macro ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code ** in sqlite3Select() to assign values to structure member variables that ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the ** code with #ifndef directives. */ # define explainSetInteger(a, b) a = b #else /* No-op versions of the explainXXX() functions and macros. */ # define explainTempTable(y,z) # define explainSetInteger(y,z) #endif /* ** If the inner loop was generated using a non-null pOrderBy argument, ** then the results were placed in a sorter. After the loop is terminated ** we need to run the sorter and output the results. The following ** routine generates the code needed to do that. */ static void generateSortTail( Parse *pParse, /* Parsing context */ Select *p, /* The SELECT statement */ SortCtx *pSort, /* Information on the ORDER BY clause */ int nColumn, /* Number of columns of data */ SelectDest *pDest /* Write the sorted results here */ ){ Vdbe *v = pParse->pVdbe; /* The prepared statement */ int addrBreak = pSort->labelDone; /* Jump here to exit loop */ int addrContinue = sqlite3VdbeMakeLabel(pParse);/* Jump here for next cycle */ int addr; /* Top of output loop. Jump for Next. */ int addrOnce = 0; int iTab; ExprList *pOrderBy = pSort->pOrderBy; int eDest = pDest->eDest; int iParm = pDest->iSDParm; int regRow; int regRowid; int iCol; int nKey; /* Number of key columns in sorter record */ int iSortTab; /* Sorter cursor to read from */ int i; int bSeq; /* True if sorter record includes seq. no. */ int nRefKey = 0; struct ExprList_item *aOutEx = p->pEList->a; assert( addrBreak<0 ); if( pSort->labelBkOut ){ sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut); sqlite3VdbeGoto(v, addrBreak); sqlite3VdbeResolveLabel(v, pSort->labelBkOut); } #ifdef SQLITE_ENABLE_SORTER_REFERENCES /* Open any cursors needed for sorter-reference expressions */ for(i=0; i<pSort->nDefer; i++){ Table *pTab = pSort->aDefer[i].pTab; int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); sqlite3OpenTable(pParse, pSort->aDefer[i].iCsr, iDb, pTab, OP_OpenRead); nRefKey = MAX(nRefKey, pSort->aDefer[i].nKey); } #endif iTab = pSort->iECursor; if( eDest==SRT_Output || eDest==SRT_Coroutine || eDest==SRT_Mem ){ regRowid = 0; regRow = pDest->iSdst; }else{ regRowid = sqlite3GetTempReg(pParse); if( eDest==SRT_EphemTab || eDest==SRT_Table ){ regRow = sqlite3GetTempReg(pParse); nColumn = 0; }else{ regRow = sqlite3GetTempRange(pParse, nColumn); } } nKey = pOrderBy->nExpr - pSort->nOBSat; if( pSort->sortFlags & SORTFLAG_UseSorter ){ int regSortOut = ++pParse->nMem; iSortTab = pParse->nTab++; if( pSort->labelBkOut ){ addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v); } sqlite3VdbeAddOp3(v, OP_OpenPseudo, iSortTab, regSortOut, nKey+1+nColumn+nRefKey); if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce); addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak); VdbeCoverage(v); codeOffset(v, p->iOffset, addrContinue); sqlite3VdbeAddOp3(v, OP_SorterData, iTab, regSortOut, iSortTab); bSeq = 0; }else{ addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak); VdbeCoverage(v); codeOffset(v, p->iOffset, addrContinue); iSortTab = iTab; bSeq = 1; } for(i=0, iCol=nKey+bSeq-1; i<nColumn; i++){ #ifdef SQLITE_ENABLE_SORTER_REFERENCES if( aOutEx[i].bSorterRef ) continue; #endif if( aOutEx[i].u.x.iOrderByCol==0 ) iCol++; } #ifdef SQLITE_ENABLE_SORTER_REFERENCES if( pSort->nDefer ){ int iKey = iCol+1; int regKey = sqlite3GetTempRange(pParse, nRefKey); for(i=0; i<pSort->nDefer; i++){ int iCsr = pSort->aDefer[i].iCsr; Table *pTab = pSort->aDefer[i].pTab; int nKey = pSort->aDefer[i].nKey; sqlite3VdbeAddOp1(v, OP_NullRow, iCsr); if( HasRowid(pTab) ){ sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iKey++, regKey); sqlite3VdbeAddOp3(v, OP_SeekRowid, iCsr, sqlite3VdbeCurrentAddr(v)+1, regKey); }else{ int k; int iJmp; assert( sqlite3PrimaryKeyIndex(pTab)->nKeyCol==nKey ); for(k=0; k<nKey; k++){ sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iKey++, regKey+k); } iJmp = sqlite3VdbeCurrentAddr(v); sqlite3VdbeAddOp4Int(v, OP_SeekGE, iCsr, iJmp+2, regKey, nKey); sqlite3VdbeAddOp4Int(v, OP_IdxLE, iCsr, iJmp+3, regKey, nKey); sqlite3VdbeAddOp1(v, OP_NullRow, iCsr); } } sqlite3ReleaseTempRange(pParse, regKey, nRefKey); } #endif for(i=nColumn-1; i>=0; i--){ #ifdef SQLITE_ENABLE_SORTER_REFERENCES if( aOutEx[i].bSorterRef ){ sqlite3ExprCode(pParse, aOutEx[i].pExpr, regRow+i); }else #endif { int iRead; if( aOutEx[i].u.x.iOrderByCol ){ iRead = aOutEx[i].u.x.iOrderByCol-1; }else{ iRead = iCol--; } sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iRead, regRow+i); VdbeComment((v, "%s", aOutEx[i].zName?aOutEx[i].zName : aOutEx[i].zSpan)); } } switch( eDest ){ case SRT_Table: case SRT_EphemTab: { sqlite3VdbeAddOp3(v, OP_Column, iSortTab, nKey+bSeq, regRow); sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid); sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid); sqlite3VdbeChangeP5(v, OPFLAG_APPEND); break; } #ifndef SQLITE_OMIT_SUBQUERY case SRT_Set: { assert( nColumn==sqlite3Strlen30(pDest->zAffSdst) ); sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, nColumn, regRowid, pDest->zAffSdst, nColumn); sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, regRowid, regRow, nColumn); break; } case SRT_Mem: { /* The LIMIT clause will terminate the loop for us */ break; } #endif default: { assert( eDest==SRT_Output || eDest==SRT_Coroutine ); testcase( eDest==SRT_Output ); testcase( eDest==SRT_Coroutine ); if( eDest==SRT_Output ){ sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn); }else{ sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm); } break; } } if( regRowid ){ if( eDest==SRT_Set ){ sqlite3ReleaseTempRange(pParse, regRow, nColumn); }else{ sqlite3ReleaseTempReg(pParse, regRow); } sqlite3ReleaseTempReg(pParse, regRowid); } /* The bottom of the loop */ sqlite3VdbeResolveLabel(v, addrContinue); if( pSort->sortFlags & SORTFLAG_UseSorter ){ sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr); VdbeCoverage(v); }else{ sqlite3VdbeAddOp2(v, OP_Next, iTab, addr); VdbeCoverage(v); } if( pSort->regReturn ) sqlite3VdbeAddOp1(v, OP_Return, pSort->regReturn); sqlite3VdbeResolveLabel(v, addrBreak); } /* ** Return a pointer to a string containing the 'declaration type' of the ** expression pExpr. The string may be treated as static by the caller. ** ** Also try to estimate the size of the returned value and return that ** result in *pEstWidth. ** ** The declaration type is the exact datatype definition extracted from the ** original CREATE TABLE statement if the expression is a column. The ** declaration type for a ROWID field is INTEGER. Exactly when an expression ** is considered a column can be complex in the presence of subqueries. The ** result-set expression in all of the following SELECT statements is ** considered a column by this function. ** ** SELECT col FROM tbl; ** SELECT (SELECT col FROM tbl; ** SELECT (SELECT col FROM tbl); ** SELECT abc FROM (SELECT col AS abc FROM tbl); ** ** The declaration type for any expression other than a column is NULL. ** ** This routine has either 3 or 6 parameters depending on whether or not ** the SQLITE_ENABLE_COLUMN_METADATA compile-time option is used. */ #ifdef SQLITE_ENABLE_COLUMN_METADATA # define columnType(A,B,C,D,E) columnTypeImpl(A,B,C,D,E) #else /* if !defined(SQLITE_ENABLE_COLUMN_METADATA) */ # define columnType(A,B,C,D,E) columnTypeImpl(A,B) #endif static const char *columnTypeImpl( NameContext *pNC, #ifndef SQLITE_ENABLE_COLUMN_METADATA Expr *pExpr #else Expr *pExpr, const char **pzOrigDb, const char **pzOrigTab, const char **pzOrigCol #endif ){ char const *zType = 0; int j; #ifdef SQLITE_ENABLE_COLUMN_METADATA char const *zOrigDb = 0; char const *zOrigTab = 0; char const *zOrigCol = 0; #endif assert( pExpr!=0 ); assert( pNC->pSrcList!=0 ); switch( pExpr->op ){ case TK_COLUMN: { /* The expression is a column. Locate the table the column is being ** extracted from in NameContext.pSrcList. This table may be real ** database table or a subquery. */ Table *pTab = 0; /* Table structure column is extracted from */ Select *pS = 0; /* Select the column is extracted from */ int iCol = pExpr->iColumn; /* Index of column in pTab */ while( pNC && !pTab ){ SrcList *pTabList = pNC->pSrcList; for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++); if( j<pTabList->nSrc ){ pTab = pTabList->a[j].pTab; pS = pTabList->a[j].pSelect; }else{ pNC = pNC->pNext; } } if( pTab==0 ){ /* At one time, code such as "SELECT new.x" within a trigger would ** cause this condition to run. Since then, we have restructured how ** trigger code is generated and so this condition is no longer ** possible. However, it can still be true for statements like ** the following: ** ** CREATE TABLE t1(col INTEGER); ** SELECT (SELECT t1.col) FROM FROM t1; ** ** when columnType() is called on the expression "t1.col" in the ** sub-select. In this case, set the column type to NULL, even ** though it should really be "INTEGER". ** ** This is not a problem, as the column type of "t1.col" is never ** used. When columnType() is called on the expression ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT ** branch below. */ break; } assert( pTab && pExpr->y.pTab==pTab ); if( pS ){ /* The "table" is actually a sub-select or a view in the FROM clause ** of the SELECT statement. Return the declaration type and origin ** data for the result-set column of the sub-select. */ if( iCol>=0 && iCol<pS->pEList->nExpr ){ /* If iCol is less than zero, then the expression requests the ** rowid of the sub-select or view. This expression is legal (see ** test case misc2.2.2) - it always evaluates to NULL. */ NameContext sNC; Expr *p = pS->pEList->a[iCol].pExpr; sNC.pSrcList = pS->pSrc; sNC.pNext = pNC; sNC.pParse = pNC->pParse; zType = columnType(&sNC, p,&zOrigDb,&zOrigTab,&zOrigCol); } }else{ /* A real table or a CTE table */ assert( !pS ); #ifdef SQLITE_ENABLE_COLUMN_METADATA if( iCol<0 ) iCol = pTab->iPKey; assert( iCol==XN_ROWID || (iCol>=0 && iCol<pTab->nCol) ); if( iCol<0 ){ zType = "INTEGER"; zOrigCol = "rowid"; }else{ zOrigCol = pTab->aCol[iCol].zName; zType = sqlite3ColumnType(&pTab->aCol[iCol],0); } zOrigTab = pTab->zName; if( pNC->pParse && pTab->pSchema ){ int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema); zOrigDb = pNC->pParse->db->aDb[iDb].zDbSName; } #else assert( iCol==XN_ROWID || (iCol>=0 && iCol<pTab->nCol) ); if( iCol<0 ){ zType = "INTEGER"; }else{ zType = sqlite3ColumnType(&pTab->aCol[iCol],0); } #endif } break; } #ifndef SQLITE_OMIT_SUBQUERY case TK_SELECT: { /* The expression is a sub-select. Return the declaration type and ** origin info for the single column in the result set of the SELECT ** statement. */ NameContext sNC; Select *pS = pExpr->x.pSelect; Expr *p = pS->pEList->a[0].pExpr; assert( ExprHasProperty(pExpr, EP_xIsSelect) ); sNC.pSrcList = pS->pSrc; sNC.pNext = pNC; sNC.pParse = pNC->pParse; zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol); break; } #endif } #ifdef SQLITE_ENABLE_COLUMN_METADATA if( pzOrigDb ){ assert( pzOrigTab && pzOrigCol ); *pzOrigDb = zOrigDb; *pzOrigTab = zOrigTab; *pzOrigCol = zOrigCol; } #endif return zType; } /* ** Generate code that will tell the VDBE the declaration types of columns ** in the result set. */ static void generateColumnTypes( Parse *pParse, /* Parser context */ SrcList *pTabList, /* List of tables */ ExprList *pEList /* Expressions defining the result set */ ){ #ifndef SQLITE_OMIT_DECLTYPE Vdbe *v = pParse->pVdbe; int i; NameContext sNC; sNC.pSrcList = pTabList; sNC.pParse = pParse; sNC.pNext = 0; for(i=0; i<pEList->nExpr; i++){ Expr *p = pEList->a[i].pExpr; const char *zType; #ifdef SQLITE_ENABLE_COLUMN_METADATA const char *zOrigDb = 0; const char *zOrigTab = 0; const char *zOrigCol = 0; zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol); /* The vdbe must make its own copy of the column-type and other ** column specific strings, in case the schema is reset before this ** virtual machine is deleted. */ sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT); sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT); sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT); #else zType = columnType(&sNC, p, 0, 0, 0); #endif sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT); } #endif /* !defined(SQLITE_OMIT_DECLTYPE) */ } /* ** Compute the column names for a SELECT statement. ** ** The only guarantee that SQLite makes about column names is that if the ** column has an AS clause assigning it a name, that will be the name used. ** That is the only documented guarantee. However, countless applications ** developed over the years have made baseless assumptions about column names ** and will break if those assumptions changes. Hence, use extreme caution ** when modifying this routine to avoid breaking legacy. ** ** See Also: sqlite3ColumnsFromExprList() ** ** The PRAGMA short_column_names and PRAGMA full_column_names settings are ** deprecated. The default setting is short=ON, full=OFF. 99.9% of all ** applications should operate this way. Nevertheless, we need to support the ** other modes for legacy: ** ** short=OFF, full=OFF: Column name is the text of the expression has it ** originally appears in the SELECT statement. In ** other words, the zSpan of the result expression. ** ** short=ON, full=OFF: (This is the default setting). If the result ** refers directly to a table column, then the ** result column name is just the table column ** name: COLUMN. Otherwise use zSpan. ** ** full=ON, short=ANY: If the result refers directly to a table column, ** then the result column name with the table name ** prefix, ex: TABLE.COLUMN. Otherwise use zSpan. */ static void generateColumnNames( Parse *pParse, /* Parser context */ Select *pSelect /* Generate column names for this SELECT statement */ ){ Vdbe *v = pParse->pVdbe; int i; Table *pTab; SrcList *pTabList; ExprList *pEList; sqlite3 *db = pParse->db; int fullName; /* TABLE.COLUMN if no AS clause and is a direct table ref */ int srcName; /* COLUMN or TABLE.COLUMN if no AS clause and is direct */ #ifndef SQLITE_OMIT_EXPLAIN /* If this is an EXPLAIN, skip this step */ if( pParse->explain ){ return; } #endif if( pParse->colNamesSet ) return; /* Column names are determined by the left-most term of a compound select */ while( pSelect->pPrior ) pSelect = pSelect->pPrior; SELECTTRACE(1,pParse,pSelect,("generating column names\n")); pTabList = pSelect->pSrc; pEList = pSelect->pEList; assert( v!=0 ); assert( pTabList!=0 ); pParse->colNamesSet = 1; fullName = (db->flags & SQLITE_FullColNames)!=0; srcName = (db->flags & SQLITE_ShortColNames)!=0 || fullName; sqlite3VdbeSetNumCols(v, pEList->nExpr); for(i=0; i<pEList->nExpr; i++){ Expr *p = pEList->a[i].pExpr; assert( p!=0 ); assert( p->op!=TK_AGG_COLUMN ); /* Agg processing has not run yet */ assert( p->op!=TK_COLUMN || p->y.pTab!=0 ); /* Covering idx not yet coded */ if( pEList->a[i].zName ){ /* An AS clause always takes first priority */ char *zName = pEList->a[i].zName; sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT); }else if( srcName && p->op==TK_COLUMN ){ char *zCol; int iCol = p->iColumn; pTab = p->y.pTab; assert( pTab!=0 ); if( iCol<0 ) iCol = pTab->iPKey; assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) ); if( iCol<0 ){ zCol = "rowid"; }else{ zCol = pTab->aCol[iCol].zName; } if( fullName ){ char *zName = 0; zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol); sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC); }else{ sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT); } }else{ const char *z = pEList->a[i].zSpan; z = z==0 ? sqlite3MPrintf(db, "column%d", i+1) : sqlite3DbStrDup(db, z); sqlite3VdbeSetColName(v, i, COLNAME_NAME, z, SQLITE_DYNAMIC); } } generateColumnTypes(pParse, pTabList, pEList); } /* ** Given an expression list (which is really the list of expressions ** that form the result set of a SELECT statement) compute appropriate ** column names for a table that would hold the expression list. ** ** All column names will be unique. ** ** Only the column names are computed. Column.zType, Column.zColl, ** and other fields of Column are zeroed. ** ** Return SQLITE_OK on success. If a memory allocation error occurs, ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM. ** ** The only guarantee that SQLite makes about column names is that if the ** column has an AS clause assigning it a name, that will be the name used. ** That is the only documented guarantee. However, countless applications ** developed over the years have made baseless assumptions about column names ** and will break if those assumptions changes. Hence, use extreme caution ** when modifying this routine to avoid breaking legacy. ** ** See Also: generateColumnNames() */ int sqlite3ColumnsFromExprList( Parse *pParse, /* Parsing context */ ExprList *pEList, /* Expr list from which to derive column names */ i16 *pnCol, /* Write the number of columns here */ Column **paCol /* Write the new column list here */ ){ sqlite3 *db = pParse->db; /* Database connection */ int i, j; /* Loop counters */ u32 cnt; /* Index added to make the name unique */ Column *aCol, *pCol; /* For looping over result columns */ int nCol; /* Number of columns in the result set */ char *zName; /* Column name */ int nName; /* Size of name in zName[] */ Hash ht; /* Hash table of column names */ sqlite3HashInit(&ht); if( pEList ){ nCol = pEList->nExpr; aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol); testcase( aCol==0 ); if( nCol>32767 ) nCol = 32767; }else{ nCol = 0; aCol = 0; } assert( nCol==(i16)nCol ); *pnCol = nCol; *paCol = aCol; for(i=0, pCol=aCol; i<nCol && !db->mallocFailed; i++, pCol++){ /* Get an appropriate name for the column */ if( (zName = pEList->a[i].zName)!=0 ){ /* If the column contains an "AS <name>" phrase, use <name> as the name */ }else{ Expr *pColExpr = sqlite3ExprSkipCollateAndLikely(pEList->a[i].pExpr); while( pColExpr->op==TK_DOT ){ pColExpr = pColExpr->pRight; assert( pColExpr!=0 ); } if( pColExpr->op==TK_COLUMN ){ /* For columns use the column name name */ int iCol = pColExpr->iColumn; Table *pTab = pColExpr->y.pTab; assert( pTab!=0 ); if( iCol<0 ) iCol = pTab->iPKey; zName = iCol>=0 ? pTab->aCol[iCol].zName : "rowid"; }else if( pColExpr->op==TK_ID ){ assert( !ExprHasProperty(pColExpr, EP_IntValue) ); zName = pColExpr->u.zToken; }else{ /* Use the original text of the column expression as its name */ zName = pEList->a[i].zSpan; } } if( zName ){ zName = sqlite3DbStrDup(db, zName); }else{ zName = sqlite3MPrintf(db,"column%d",i+1); } /* Make sure the column name is unique. If the name is not unique, ** append an integer to the name so that it becomes unique. */ cnt = 0; while( zName && sqlite3HashFind(&ht, zName)!=0 ){ nName = sqlite3Strlen30(zName); if( nName>0 ){ for(j=nName-1; j>0 && sqlite3Isdigit(zName[j]); j--){} if( zName[j]==':' ) nName = j; } zName = sqlite3MPrintf(db, "%.*z:%u", nName, zName, ++cnt); if( cnt>3 ) sqlite3_randomness(sizeof(cnt), &cnt); } pCol->zName = zName; sqlite3ColumnPropertiesFromName(0, pCol); if( zName && sqlite3HashInsert(&ht, zName, pCol)==pCol ){ sqlite3OomFault(db); } } sqlite3HashClear(&ht); if( db->mallocFailed ){ for(j=0; j<i; j++){ sqlite3DbFree(db, aCol[j].zName); } sqlite3DbFree(db, aCol); *paCol = 0; *pnCol = 0; return SQLITE_NOMEM_BKPT; } return SQLITE_OK; } /* ** Add type and collation information to a column list based on ** a SELECT statement. ** ** The column list presumably came from selectColumnNamesFromExprList(). ** The column list has only names, not types or collations. This ** routine goes through and adds the types and collations. ** ** This routine requires that all identifiers in the SELECT ** statement be resolved. */ void sqlite3SelectAddColumnTypeAndCollation( Parse *pParse, /* Parsing contexts */ Table *pTab, /* Add column type information to this table */ Select *pSelect, /* SELECT used to determine types and collations */ char aff /* Default affinity for columns */ ){ sqlite3 *db = pParse->db; NameContext sNC; Column *pCol; CollSeq *pColl; int i; Expr *p; struct ExprList_item *a; assert( pSelect!=0 ); assert( (pSelect->selFlags & SF_Resolved)!=0 ); assert( pTab->nCol==pSelect->pEList->nExpr || db->mallocFailed ); if( db->mallocFailed ) return; memset(&sNC, 0, sizeof(sNC)); sNC.pSrcList = pSelect->pSrc; a = pSelect->pEList->a; for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){ const char *zType; int n, m; p = a[i].pExpr; zType = columnType(&sNC, p, 0, 0, 0); /* pCol->szEst = ... // Column size est for SELECT tables never used */ pCol->affinity = sqlite3ExprAffinity(p); if( zType ){ m = sqlite3Strlen30(zType); n = sqlite3Strlen30(pCol->zName); pCol->zName = sqlite3DbReallocOrFree(db, pCol->zName, n+m+2); if( pCol->zName ){ memcpy(&pCol->zName[n+1], zType, m+1); pCol->colFlags |= COLFLAG_HASTYPE; } } if( pCol->affinity<=SQLITE_AFF_NONE ) pCol->affinity = aff; pColl = sqlite3ExprCollSeq(pParse, p); if( pColl && pCol->zColl==0 ){ pCol->zColl = sqlite3DbStrDup(db, pColl->zName); } } pTab->szTabRow = 1; /* Any non-zero value works */ } /* ** Given a SELECT statement, generate a Table structure that describes ** the result set of that SELECT. */ Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect, char aff){ Table *pTab; sqlite3 *db = pParse->db; u64 savedFlags; savedFlags = db->flags; db->flags &= ~(u64)SQLITE_FullColNames; db->flags |= SQLITE_ShortColNames; sqlite3SelectPrep(pParse, pSelect, 0); db->flags = savedFlags; if( pParse->nErr ) return 0; while( pSelect->pPrior ) pSelect = pSelect->pPrior; pTab = sqlite3DbMallocZero(db, sizeof(Table) ); if( pTab==0 ){ return 0; } pTab->nTabRef = 1; pTab->zName = 0; pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) ); sqlite3ColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol); sqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSelect, aff); pTab->iPKey = -1; if( db->mallocFailed ){ sqlite3DeleteTable(db, pTab); return 0; } return pTab; } /* ** Get a VDBE for the given parser context. Create a new one if necessary. ** If an error occurs, return NULL and leave a message in pParse. */ Vdbe *sqlite3GetVdbe(Parse *pParse){ if( pParse->pVdbe ){ return pParse->pVdbe; } if( pParse->pToplevel==0 && OptimizationEnabled(pParse->db,SQLITE_FactorOutConst) ){ pParse->okConstFactor = 1; } return sqlite3VdbeCreate(pParse); } /* ** Compute the iLimit and iOffset fields of the SELECT based on the ** pLimit expressions. pLimit->pLeft and pLimit->pRight hold the expressions ** that appear in the original SQL statement after the LIMIT and OFFSET ** keywords. Or NULL if those keywords are omitted. iLimit and iOffset ** are the integer memory register numbers for counters used to compute ** the limit and offset. If there is no limit and/or offset, then ** iLimit and iOffset are negative. ** ** This routine changes the values of iLimit and iOffset only if ** a limit or offset is defined by pLimit->pLeft and pLimit->pRight. iLimit ** and iOffset should have been preset to appropriate default values (zero) ** prior to calling this routine. ** ** The iOffset register (if it exists) is initialized to the value ** of the OFFSET. The iLimit register is initialized to LIMIT. Register ** iOffset+1 is initialized to LIMIT+OFFSET. ** ** Only if pLimit->pLeft!=0 do the limit registers get ** redefined. The UNION ALL operator uses this property to force ** the reuse of the same limit and offset registers across multiple ** SELECT statements. */ static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){ Vdbe *v = 0; int iLimit = 0; int iOffset; int n; Expr *pLimit = p->pLimit; if( p->iLimit ) return; /* ** "LIMIT -1" always shows all rows. There is some ** controversy about what the correct behavior should be. ** The current implementation interprets "LIMIT 0" to mean ** no rows. */ if( pLimit ){ assert( pLimit->op==TK_LIMIT ); assert( pLimit->pLeft!=0 ); p->iLimit = iLimit = ++pParse->nMem; v = sqlite3GetVdbe(pParse); assert( v!=0 ); if( sqlite3ExprIsInteger(pLimit->pLeft, &n) ){ sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit); VdbeComment((v, "LIMIT counter")); if( n==0 ){ sqlite3VdbeGoto(v, iBreak); }else if( n>=0 && p->nSelectRow>sqlite3LogEst((u64)n) ){ p->nSelectRow = sqlite3LogEst((u64)n); p->selFlags |= SF_FixedLimit; } }else{ sqlite3ExprCode(pParse, pLimit->pLeft, iLimit); sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit); VdbeCoverage(v); VdbeComment((v, "LIMIT counter")); sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, iBreak); VdbeCoverage(v); } if( pLimit->pRight ){ p->iOffset = iOffset = ++pParse->nMem; pParse->nMem++; /* Allocate an extra register for limit+offset */ sqlite3ExprCode(pParse, pLimit->pRight, iOffset); sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset); VdbeCoverage(v); VdbeComment((v, "OFFSET counter")); sqlite3VdbeAddOp3(v, OP_OffsetLimit, iLimit, iOffset+1, iOffset); VdbeComment((v, "LIMIT+OFFSET")); } } } #ifndef SQLITE_OMIT_COMPOUND_SELECT /* ** Return the appropriate collating sequence for the iCol-th column of ** the result set for the compound-select statement "p". Return NULL if ** the column has no default collating sequence. ** ** The collating sequence for the compound select is taken from the ** left-most term of the select that has a collating sequence. */ static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){ CollSeq *pRet; if( p->pPrior ){ pRet = multiSelectCollSeq(pParse, p->pPrior, iCol); }else{ pRet = 0; } assert( iCol>=0 ); /* iCol must be less than p->pEList->nExpr. Otherwise an error would ** have been thrown during name resolution and we would not have gotten ** this far */ if( pRet==0 && ALWAYS(iCol<p->pEList->nExpr) ){ pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr); } return pRet; } /* ** The select statement passed as the second parameter is a compound SELECT ** with an ORDER BY clause. This function allocates and returns a KeyInfo ** structure suitable for implementing the ORDER BY. ** ** Space to hold the KeyInfo structure is obtained from malloc. The calling ** function is responsible for ensuring that this structure is eventually ** freed. */ static KeyInfo *multiSelectOrderByKeyInfo(Parse *pParse, Select *p, int nExtra){ ExprList *pOrderBy = p->pOrderBy; int nOrderBy = p->pOrderBy->nExpr; sqlite3 *db = pParse->db; KeyInfo *pRet = sqlite3KeyInfoAlloc(db, nOrderBy+nExtra, 1); if( pRet ){ int i; for(i=0; i<nOrderBy; i++){ struct ExprList_item *pItem = &pOrderBy->a[i]; Expr *pTerm = pItem->pExpr; CollSeq *pColl; if( pTerm->flags & EP_Collate ){ pColl = sqlite3ExprCollSeq(pParse, pTerm); }else{ pColl = multiSelectCollSeq(pParse, p, pItem->u.x.iOrderByCol-1); if( pColl==0 ) pColl = db->pDfltColl; pOrderBy->a[i].pExpr = sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName); } assert( sqlite3KeyInfoIsWriteable(pRet) ); pRet->aColl[i] = pColl; pRet->aSortFlags[i] = pOrderBy->a[i].sortFlags; } } return pRet; } #ifndef SQLITE_OMIT_CTE /* ** This routine generates VDBE code to compute the content of a WITH RECURSIVE ** query of the form: ** ** <recursive-table> AS (<setup-query> UNION [ALL] <recursive-query>) ** \___________/ \_______________/ ** p->pPrior p ** ** ** There is exactly one reference to the recursive-table in the FROM clause ** of recursive-query, marked with the SrcList->a[].fg.isRecursive flag. ** ** The setup-query runs once to generate an initial set of rows that go ** into a Queue table. Rows are extracted from the Queue table one by ** one. Each row extracted from Queue is output to pDest. Then the single ** extracted row (now in the iCurrent table) becomes the content of the ** recursive-table for a recursive-query run. The output of the recursive-query ** is added back into the Queue table. Then another row is extracted from Queue ** and the iteration continues until the Queue table is empty. ** ** If the compound query operator is UNION then no duplicate rows are ever ** inserted into the Queue table. The iDistinct table keeps a copy of all rows ** that have ever been inserted into Queue and causes duplicates to be ** discarded. If the operator is UNION ALL, then duplicates are allowed. ** ** If the query has an ORDER BY, then entries in the Queue table are kept in ** ORDER BY order and the first entry is extracted for each cycle. Without ** an ORDER BY, the Queue table is just a FIFO. ** ** If a LIMIT clause is provided, then the iteration stops after LIMIT rows ** have been output to pDest. A LIMIT of zero means to output no rows and a ** negative LIMIT means to output all rows. If there is also an OFFSET clause ** with a positive value, then the first OFFSET outputs are discarded rather ** than being sent to pDest. The LIMIT count does not begin until after OFFSET ** rows have been skipped. */ static void generateWithRecursiveQuery( Parse *pParse, /* Parsing context */ Select *p, /* The recursive SELECT to be coded */ SelectDest *pDest /* What to do with query results */ ){ SrcList *pSrc = p->pSrc; /* The FROM clause of the recursive query */ int nCol = p->pEList->nExpr; /* Number of columns in the recursive table */ Vdbe *v = pParse->pVdbe; /* The prepared statement under construction */ Select *pSetup = p->pPrior; /* The setup query */ int addrTop; /* Top of the loop */ int addrCont, addrBreak; /* CONTINUE and BREAK addresses */ int iCurrent = 0; /* The Current table */ int regCurrent; /* Register holding Current table */ int iQueue; /* The Queue table */ int iDistinct = 0; /* To ensure unique results if UNION */ int eDest = SRT_Fifo; /* How to write to Queue */ SelectDest destQueue; /* SelectDest targetting the Queue table */ int i; /* Loop counter */ int rc; /* Result code */ ExprList *pOrderBy; /* The ORDER BY clause */ Expr *pLimit; /* Saved LIMIT and OFFSET */ int regLimit, regOffset; /* Registers used by LIMIT and OFFSET */ #ifndef SQLITE_OMIT_WINDOWFUNC if( p->pWin ){ sqlite3ErrorMsg(pParse, "cannot use window functions in recursive queries"); return; } #endif /* Obtain authorization to do a recursive query */ if( sqlite3AuthCheck(pParse, SQLITE_RECURSIVE, 0, 0, 0) ) return; /* Process the LIMIT and OFFSET clauses, if they exist */ addrBreak = sqlite3VdbeMakeLabel(pParse); p->nSelectRow = 320; /* 4 billion rows */ computeLimitRegisters(pParse, p, addrBreak); pLimit = p->pLimit; regLimit = p->iLimit; regOffset = p->iOffset; p->pLimit = 0; p->iLimit = p->iOffset = 0; pOrderBy = p->pOrderBy; /* Locate the cursor number of the Current table */ for(i=0; ALWAYS(i<pSrc->nSrc); i++){ if( pSrc->a[i].fg.isRecursive ){ iCurrent = pSrc->a[i].iCursor; break; } } /* Allocate cursors numbers for Queue and Distinct. The cursor number for ** the Distinct table must be exactly one greater than Queue in order ** for the SRT_DistFifo and SRT_DistQueue destinations to work. */ iQueue = pParse->nTab++; if( p->op==TK_UNION ){ eDest = pOrderBy ? SRT_DistQueue : SRT_DistFifo; iDistinct = pParse->nTab++; }else{ eDest = pOrderBy ? SRT_Queue : SRT_Fifo; } sqlite3SelectDestInit(&destQueue, eDest, iQueue); /* Allocate cursors for Current, Queue, and Distinct. */ regCurrent = ++pParse->nMem; sqlite3VdbeAddOp3(v, OP_OpenPseudo, iCurrent, regCurrent, nCol); if( pOrderBy ){ KeyInfo *pKeyInfo = multiSelectOrderByKeyInfo(pParse, p, 1); sqlite3VdbeAddOp4(v, OP_OpenEphemeral, iQueue, pOrderBy->nExpr+2, 0, (char*)pKeyInfo, P4_KEYINFO); destQueue.pOrderBy = pOrderBy; }else{ sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iQueue, nCol); } VdbeComment((v, "Queue table")); if( iDistinct ){ p->addrOpenEphm[0] = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iDistinct, 0); p->selFlags |= SF_UsesEphemeral; } /* Detach the ORDER BY clause from the compound SELECT */ p->pOrderBy = 0; /* Store the results of the setup-query in Queue. */ pSetup->pNext = 0; ExplainQueryPlan((pParse, 1, "SETUP")); rc = sqlite3Select(pParse, pSetup, &destQueue); pSetup->pNext = p; if( rc ) goto end_of_recursive_query; /* Find the next row in the Queue and output that row */ addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iQueue, addrBreak); VdbeCoverage(v); /* Transfer the next row in Queue over to Current */ sqlite3VdbeAddOp1(v, OP_NullRow, iCurrent); /* To reset column cache */ if( pOrderBy ){ sqlite3VdbeAddOp3(v, OP_Column, iQueue, pOrderBy->nExpr+1, regCurrent); }else{ sqlite3VdbeAddOp2(v, OP_RowData, iQueue, regCurrent); } sqlite3VdbeAddOp1(v, OP_Delete, iQueue); /* Output the single row in Current */ addrCont = sqlite3VdbeMakeLabel(pParse); codeOffset(v, regOffset, addrCont); selectInnerLoop(pParse, p, iCurrent, 0, 0, pDest, addrCont, addrBreak); if( regLimit ){ sqlite3VdbeAddOp2(v, OP_DecrJumpZero, regLimit, addrBreak); VdbeCoverage(v); } sqlite3VdbeResolveLabel(v, addrCont); /* Execute the recursive SELECT taking the single row in Current as ** the value for the recursive-table. Store the results in the Queue. */ if( p->selFlags & SF_Aggregate ){ sqlite3ErrorMsg(pParse, "recursive aggregate queries not supported"); }else{ p->pPrior = 0; ExplainQueryPlan((pParse, 1, "RECURSIVE STEP")); sqlite3Select(pParse, p, &destQueue); assert( p->pPrior==0 ); p->pPrior = pSetup; } /* Keep running the loop until the Queue is empty */ sqlite3VdbeGoto(v, addrTop); sqlite3VdbeResolveLabel(v, addrBreak); end_of_recursive_query: sqlite3ExprListDelete(pParse->db, p->pOrderBy); p->pOrderBy = pOrderBy; p->pLimit = pLimit; return; } #endif /* SQLITE_OMIT_CTE */ /* Forward references */ static int multiSelectOrderBy( Parse *pParse, /* Parsing context */ Select *p, /* The right-most of SELECTs to be coded */ SelectDest *pDest /* What to do with query results */ ); /* ** Handle the special case of a compound-select that originates from a ** VALUES clause. By handling this as a special case, we avoid deep ** recursion, and thus do not need to enforce the SQLITE_LIMIT_COMPOUND_SELECT ** on a VALUES clause. ** ** Because the Select object originates from a VALUES clause: ** (1) There is no LIMIT or OFFSET or else there is a LIMIT of exactly 1 ** (2) All terms are UNION ALL ** (3) There is no ORDER BY clause ** ** The "LIMIT of exactly 1" case of condition (1) comes about when a VALUES ** clause occurs within scalar expression (ex: "SELECT (VALUES(1),(2),(3))"). ** The sqlite3CodeSubselect will have added the LIMIT 1 clause in tht case. ** Since the limit is exactly 1, we only need to evalutes the left-most VALUES. */ static int multiSelectValues( Parse *pParse, /* Parsing context */ Select *p, /* The right-most of SELECTs to be coded */ SelectDest *pDest /* What to do with query results */ ){ int nRow = 1; int rc = 0; int bShowAll = p->pLimit==0; assert( p->selFlags & SF_MultiValue ); do{ assert( p->selFlags & SF_Values ); assert( p->op==TK_ALL || (p->op==TK_SELECT && p->pPrior==0) ); assert( p->pNext==0 || p->pEList->nExpr==p->pNext->pEList->nExpr ); if( p->pPrior==0 ) break; assert( p->pPrior->pNext==p ); p = p->pPrior; nRow += bShowAll; }while(1); ExplainQueryPlan((pParse, 0, "SCAN %d CONSTANT ROW%s", nRow, nRow==1 ? "" : "S")); while( p ){ selectInnerLoop(pParse, p, -1, 0, 0, pDest, 1, 1); if( !bShowAll ) break; p->nSelectRow = nRow; p = p->pNext; } return rc; } /* ** This routine is called to process a compound query form from ** two or more separate queries using UNION, UNION ALL, EXCEPT, or ** INTERSECT ** ** "p" points to the right-most of the two queries. the query on the ** left is p->pPrior. The left query could also be a compound query ** in which case this routine will be called recursively. ** ** The results of the total query are to be written into a destination ** of type eDest with parameter iParm. ** ** Example 1: Consider a three-way compound SQL statement. ** ** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3 ** ** This statement is parsed up as follows: ** ** SELECT c FROM t3 ** | ** `-----> SELECT b FROM t2 ** | ** `------> SELECT a FROM t1 ** ** The arrows in the diagram above represent the Select.pPrior pointer. ** So if this routine is called with p equal to the t3 query, then ** pPrior will be the t2 query. p->op will be TK_UNION in this case. ** ** Notice that because of the way SQLite parses compound SELECTs, the ** individual selects always group from left to right. */ static int multiSelect( Parse *pParse, /* Parsing context */ Select *p, /* The right-most of SELECTs to be coded */ SelectDest *pDest /* What to do with query results */ ){ int rc = SQLITE_OK; /* Success code from a subroutine */ Select *pPrior; /* Another SELECT immediately to our left */ Vdbe *v; /* Generate code to this VDBE */ SelectDest dest; /* Alternative data destination */ Select *pDelete = 0; /* Chain of simple selects to delete */ sqlite3 *db; /* Database connection */ /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT. */ assert( p && p->pPrior ); /* Calling function guarantees this much */ assert( (p->selFlags & SF_Recursive)==0 || p->op==TK_ALL || p->op==TK_UNION ); assert( p->selFlags & SF_Compound ); db = pParse->db; pPrior = p->pPrior; dest = *pDest; if( pPrior->pOrderBy || pPrior->pLimit ){ sqlite3ErrorMsg(pParse,"%s clause should come after %s not before", pPrior->pOrderBy!=0 ? "ORDER BY" : "LIMIT", selectOpName(p->op)); rc = 1; goto multi_select_end; } v = sqlite3GetVdbe(pParse); assert( v!=0 ); /* The VDBE already created by calling function */ /* Create the destination temporary table if necessary */ if( dest.eDest==SRT_EphemTab ){ assert( p->pEList ); sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr); dest.eDest = SRT_Table; } /* Special handling for a compound-select that originates as a VALUES clause. */ if( p->selFlags & SF_MultiValue ){ rc = multiSelectValues(pParse, p, &dest); goto multi_select_end; } /* Make sure all SELECTs in the statement have the same number of elements ** in their result sets. */ assert( p->pEList && pPrior->pEList ); assert( p->pEList->nExpr==pPrior->pEList->nExpr ); #ifndef SQLITE_OMIT_CTE if( p->selFlags & SF_Recursive ){ generateWithRecursiveQuery(pParse, p, &dest); }else #endif /* Compound SELECTs that have an ORDER BY clause are handled separately. */ if( p->pOrderBy ){ return multiSelectOrderBy(pParse, p, pDest); }else{ #ifndef SQLITE_OMIT_EXPLAIN if( pPrior->pPrior==0 ){ ExplainQueryPlan((pParse, 1, "COMPOUND QUERY")); ExplainQueryPlan((pParse, 1, "LEFT-MOST SUBQUERY")); } #endif /* Generate code for the left and right SELECT statements. */ switch( p->op ){ case TK_ALL: { int addr = 0; int nLimit; assert( !pPrior->pLimit ); pPrior->iLimit = p->iLimit; pPrior->iOffset = p->iOffset; pPrior->pLimit = p->pLimit; rc = sqlite3Select(pParse, pPrior, &dest); p->pLimit = 0; if( rc ){ goto multi_select_end; } p->pPrior = 0; p->iLimit = pPrior->iLimit; p->iOffset = pPrior->iOffset; if( p->iLimit ){ addr = sqlite3VdbeAddOp1(v, OP_IfNot, p->iLimit); VdbeCoverage(v); VdbeComment((v, "Jump ahead if LIMIT reached")); if( p->iOffset ){ sqlite3VdbeAddOp3(v, OP_OffsetLimit, p->iLimit, p->iOffset+1, p->iOffset); } } ExplainQueryPlan((pParse, 1, "UNION ALL")); rc = sqlite3Select(pParse, p, &dest); testcase( rc!=SQLITE_OK ); pDelete = p->pPrior; p->pPrior = pPrior; p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow); if( pPrior->pLimit && sqlite3ExprIsInteger(pPrior->pLimit->pLeft, &nLimit) && nLimit>0 && p->nSelectRow > sqlite3LogEst((u64)nLimit) ){ p->nSelectRow = sqlite3LogEst((u64)nLimit); } if( addr ){ sqlite3VdbeJumpHere(v, addr); } break; } case TK_EXCEPT: case TK_UNION: { int unionTab; /* Cursor number of the temp table holding result */ u8 op = 0; /* One of the SRT_ operations to apply to self */ int priorOp; /* The SRT_ operation to apply to prior selects */ Expr *pLimit; /* Saved values of p->nLimit */ int addr; SelectDest uniondest; testcase( p->op==TK_EXCEPT ); testcase( p->op==TK_UNION ); priorOp = SRT_Union; if( dest.eDest==priorOp ){ /* We can reuse a temporary table generated by a SELECT to our ** right. */ assert( p->pLimit==0 ); /* Not allowed on leftward elements */ unionTab = dest.iSDParm; }else{ /* We will need to create our own temporary table to hold the ** intermediate results. */ unionTab = pParse->nTab++; assert( p->pOrderBy==0 ); addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0); assert( p->addrOpenEphm[0] == -1 ); p->addrOpenEphm[0] = addr; findRightmost(p)->selFlags |= SF_UsesEphemeral; assert( p->pEList ); } /* Code the SELECT statements to our left */ assert( !pPrior->pOrderBy ); sqlite3SelectDestInit(&uniondest, priorOp, unionTab); rc = sqlite3Select(pParse, pPrior, &uniondest); if( rc ){ goto multi_select_end; } /* Code the current SELECT statement */ if( p->op==TK_EXCEPT ){ op = SRT_Except; }else{ assert( p->op==TK_UNION ); op = SRT_Union; } p->pPrior = 0; pLimit = p->pLimit; p->pLimit = 0; uniondest.eDest = op; ExplainQueryPlan((pParse, 1, "%s USING TEMP B-TREE", selectOpName(p->op))); rc = sqlite3Select(pParse, p, &uniondest); testcase( rc!=SQLITE_OK ); /* Query flattening in sqlite3Select() might refill p->pOrderBy. ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */ sqlite3ExprListDelete(db, p->pOrderBy); pDelete = p->pPrior; p->pPrior = pPrior; p->pOrderBy = 0; if( p->op==TK_UNION ){ p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow); } sqlite3ExprDelete(db, p->pLimit); p->pLimit = pLimit; p->iLimit = 0; p->iOffset = 0; /* Convert the data in the temporary table into whatever form ** it is that we currently need. */ assert( unionTab==dest.iSDParm || dest.eDest!=priorOp ); if( dest.eDest!=priorOp ){ int iCont, iBreak, iStart; assert( p->pEList ); iBreak = sqlite3VdbeMakeLabel(pParse); iCont = sqlite3VdbeMakeLabel(pParse); computeLimitRegisters(pParse, p, iBreak); sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); VdbeCoverage(v); iStart = sqlite3VdbeCurrentAddr(v); selectInnerLoop(pParse, p, unionTab, 0, 0, &dest, iCont, iBreak); sqlite3VdbeResolveLabel(v, iCont); sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); VdbeCoverage(v); sqlite3VdbeResolveLabel(v, iBreak); sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0); } break; } default: assert( p->op==TK_INTERSECT ); { int tab1, tab2; int iCont, iBreak, iStart; Expr *pLimit; int addr; SelectDest intersectdest; int r1; /* INTERSECT is different from the others since it requires ** two temporary tables. Hence it has its own case. Begin ** by allocating the tables we will need. */ tab1 = pParse->nTab++; tab2 = pParse->nTab++; assert( p->pOrderBy==0 ); addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0); assert( p->addrOpenEphm[0] == -1 ); p->addrOpenEphm[0] = addr; findRightmost(p)->selFlags |= SF_UsesEphemeral; assert( p->pEList ); /* Code the SELECTs to our left into temporary table "tab1". */ sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1); rc = sqlite3Select(pParse, pPrior, &intersectdest); if( rc ){ goto multi_select_end; } /* Code the current SELECT into temporary table "tab2" */ addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0); assert( p->addrOpenEphm[1] == -1 ); p->addrOpenEphm[1] = addr; p->pPrior = 0; pLimit = p->pLimit; p->pLimit = 0; intersectdest.iSDParm = tab2; ExplainQueryPlan((pParse, 1, "%s USING TEMP B-TREE", selectOpName(p->op))); rc = sqlite3Select(pParse, p, &intersectdest); testcase( rc!=SQLITE_OK ); pDelete = p->pPrior; p->pPrior = pPrior; if( p->nSelectRow>pPrior->nSelectRow ){ p->nSelectRow = pPrior->nSelectRow; } sqlite3ExprDelete(db, p->pLimit); p->pLimit = pLimit; /* Generate code to take the intersection of the two temporary ** tables. */ assert( p->pEList ); iBreak = sqlite3VdbeMakeLabel(pParse); iCont = sqlite3VdbeMakeLabel(pParse); computeLimitRegisters(pParse, p, iBreak); sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); VdbeCoverage(v); r1 = sqlite3GetTempReg(pParse); iStart = sqlite3VdbeAddOp2(v, OP_RowData, tab1, r1); sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0); VdbeCoverage(v); sqlite3ReleaseTempReg(pParse, r1); selectInnerLoop(pParse, p, tab1, 0, 0, &dest, iCont, iBreak); sqlite3VdbeResolveLabel(v, iCont); sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); VdbeCoverage(v); sqlite3VdbeResolveLabel(v, iBreak); sqlite3VdbeAddOp2(v, OP_Close, tab2, 0); sqlite3VdbeAddOp2(v, OP_Close, tab1, 0); break; } } #ifndef SQLITE_OMIT_EXPLAIN if( p->pNext==0 ){ ExplainQueryPlanPop(pParse); } #endif } /* Compute collating sequences used by ** temporary tables needed to implement the compound select. ** Attach the KeyInfo structure to all temporary tables. ** ** This section is run by the right-most SELECT statement only. ** SELECT statements to the left always skip this part. The right-most ** SELECT might also skip this part if it has no ORDER BY clause and ** no temp tables are required. */ if( p->selFlags & SF_UsesEphemeral ){ int i; /* Loop counter */ KeyInfo *pKeyInfo; /* Collating sequence for the result set */ Select *pLoop; /* For looping through SELECT statements */ CollSeq **apColl; /* For looping through pKeyInfo->aColl[] */ int nCol; /* Number of columns in result set */ assert( p->pNext==0 ); nCol = p->pEList->nExpr; pKeyInfo = sqlite3KeyInfoAlloc(db, nCol, 1); if( !pKeyInfo ){ rc = SQLITE_NOMEM_BKPT; goto multi_select_end; } for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){ *apColl = multiSelectCollSeq(pParse, p, i); if( 0==*apColl ){ *apColl = db->pDfltColl; } } for(pLoop=p; pLoop; pLoop=pLoop->pPrior){ for(i=0; i<2; i++){ int addr = pLoop->addrOpenEphm[i]; if( addr<0 ){ /* If [0] is unused then [1] is also unused. So we can ** always safely abort as soon as the first unused slot is found */ assert( pLoop->addrOpenEphm[1]<0 ); break; } sqlite3VdbeChangeP2(v, addr, nCol); sqlite3VdbeChangeP4(v, addr, (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO); pLoop->addrOpenEphm[i] = -1; } } sqlite3KeyInfoUnref(pKeyInfo); } multi_select_end: pDest->iSdst = dest.iSdst; pDest->nSdst = dest.nSdst; sqlite3SelectDelete(db, pDelete); return rc; } #endif /* SQLITE_OMIT_COMPOUND_SELECT */ /* ** Error message for when two or more terms of a compound select have different ** size result sets. */ void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p){ if( p->selFlags & SF_Values ){ sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms"); }else{ sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s" " do not have the same number of result columns", selectOpName(p->op)); } } /* ** Code an output subroutine for a coroutine implementation of a ** SELECT statment. ** ** The data to be output is contained in pIn->iSdst. There are ** pIn->nSdst columns to be output. pDest is where the output should ** be sent. ** ** regReturn is the number of the register holding the subroutine ** return address. ** ** If regPrev>0 then it is the first register in a vector that ** records the previous output. mem[regPrev] is a flag that is false ** if there has been no previous output. If regPrev>0 then code is ** generated to suppress duplicates. pKeyInfo is used for comparing ** keys. ** ** If the LIMIT found in p->iLimit is reached, jump immediately to ** iBreak. */ static int generateOutputSubroutine( Parse *pParse, /* Parsing context */ Select *p, /* The SELECT statement */ SelectDest *pIn, /* Coroutine supplying data */ SelectDest *pDest, /* Where to send the data */ int regReturn, /* The return address register */ int regPrev, /* Previous result register. No uniqueness if 0 */ KeyInfo *pKeyInfo, /* For comparing with previous entry */ int iBreak /* Jump here if we hit the LIMIT */ ){ Vdbe *v = pParse->pVdbe; int iContinue; int addr; addr = sqlite3VdbeCurrentAddr(v); iContinue = sqlite3VdbeMakeLabel(pParse); /* Suppress duplicates for UNION, EXCEPT, and INTERSECT */ if( regPrev ){ int addr1, addr2; addr1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev); VdbeCoverage(v); addr2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst, (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO); sqlite3VdbeAddOp3(v, OP_Jump, addr2+2, iContinue, addr2+2); VdbeCoverage(v); sqlite3VdbeJumpHere(v, addr1); sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1); sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev); } if( pParse->db->mallocFailed ) return 0; /* Suppress the first OFFSET entries if there is an OFFSET clause */ codeOffset(v, p->iOffset, iContinue); assert( pDest->eDest!=SRT_Exists ); assert( pDest->eDest!=SRT_Table ); switch( pDest->eDest ){ /* Store the result as data using a unique key. */ case SRT_EphemTab: { int r1 = sqlite3GetTempReg(pParse); int r2 = sqlite3GetTempReg(pParse); sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1); sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2); sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2); sqlite3VdbeChangeP5(v, OPFLAG_APPEND); sqlite3ReleaseTempReg(pParse, r2); sqlite3ReleaseTempReg(pParse, r1); break; } #ifndef SQLITE_OMIT_SUBQUERY /* If we are creating a set for an "expr IN (SELECT ...)". */ case SRT_Set: { int r1; testcase( pIn->nSdst>1 ); r1 = sqlite3GetTempReg(pParse); sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1, pDest->zAffSdst, pIn->nSdst); sqlite3VdbeAddOp4Int(v, OP_IdxInsert, pDest->iSDParm, r1, pIn->iSdst, pIn->nSdst); sqlite3ReleaseTempReg(pParse, r1); break; } /* If this is a scalar select that is part of an expression, then ** store the results in the appropriate memory cell and break out ** of the scan loop. Note that the select might return multiple columns ** if it is the RHS of a row-value IN operator. */ case SRT_Mem: { if( pParse->nErr==0 ){ testcase( pIn->nSdst>1 ); sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, pIn->nSdst); } /* The LIMIT clause will jump out of the loop for us */ break; } #endif /* #ifndef SQLITE_OMIT_SUBQUERY */ /* The results are stored in a sequence of registers ** starting at pDest->iSdst. Then the co-routine yields. */ case SRT_Coroutine: { if( pDest->iSdst==0 ){ pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst); pDest->nSdst = pIn->nSdst; } sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pIn->nSdst); sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm); break; } /* If none of the above, then the result destination must be ** SRT_Output. This routine is never called with any other ** destination other than the ones handled above or SRT_Output. ** ** For SRT_Output, results are stored in a sequence of registers. ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to ** return the next row of result. */ default: { assert( pDest->eDest==SRT_Output ); sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst); break; } } /* Jump to the end of the loop if the LIMIT is reached. */ if( p->iLimit ){ sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v); } /* Generate the subroutine return */ sqlite3VdbeResolveLabel(v, iContinue); sqlite3VdbeAddOp1(v, OP_Return, regReturn); return addr; } /* ** Alternative compound select code generator for cases when there ** is an ORDER BY clause. ** ** We assume a query of the following form: ** ** <selectA> <operator> <selectB> ORDER BY <orderbylist> ** ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT. The idea ** is to code both <selectA> and <selectB> with the ORDER BY clause as ** co-routines. Then run the co-routines in parallel and merge the results ** into the output. In addition to the two coroutines (called selectA and ** selectB) there are 7 subroutines: ** ** outA: Move the output of the selectA coroutine into the output ** of the compound query. ** ** outB: Move the output of the selectB coroutine into the output ** of the compound query. (Only generated for UNION and ** UNION ALL. EXCEPT and INSERTSECT never output a row that ** appears only in B.) ** ** AltB: Called when there is data from both coroutines and A<B. ** ** AeqB: Called when there is data from both coroutines and A==B. ** ** AgtB: Called when there is data from both coroutines and A>B. ** ** EofA: Called when data is exhausted from selectA. ** ** EofB: Called when data is exhausted from selectB. ** ** The implementation of the latter five subroutines depend on which ** <operator> is used: ** ** ** UNION ALL UNION EXCEPT INTERSECT ** ------------- ----------------- -------------- ----------------- ** AltB: outA, nextA outA, nextA outA, nextA nextA ** ** AeqB: outA, nextA nextA nextA outA, nextA ** ** AgtB: outB, nextB outB, nextB nextB nextB ** ** EofA: outB, nextB outB, nextB halt halt ** ** EofB: outA, nextA outA, nextA outA, nextA halt ** ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA ** causes an immediate jump to EofA and an EOF on B following nextB causes ** an immediate jump to EofB. Within EofA and EofB, and EOF on entry or ** following nextX causes a jump to the end of the select processing. ** ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled ** within the output subroutine. The regPrev register set holds the previously ** output value. A comparison is made against this value and the output ** is skipped if the next results would be the same as the previous. ** ** The implementation plan is to implement the two coroutines and seven ** subroutines first, then put the control logic at the bottom. Like this: ** ** goto Init ** coA: coroutine for left query (A) ** coB: coroutine for right query (B) ** outA: output one row of A ** outB: output one row of B (UNION and UNION ALL only) ** EofA: ... ** EofB: ... ** AltB: ... ** AeqB: ... ** AgtB: ... ** Init: initialize coroutine registers ** yield coA ** if eof(A) goto EofA ** yield coB ** if eof(B) goto EofB ** Cmpr: Compare A, B ** Jump AltB, AeqB, AgtB ** End: ... ** ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not ** actually called using Gosub and they do not Return. EofA and EofB loop ** until all data is exhausted then jump to the "end" labe. AltB, AeqB, ** and AgtB jump to either L2 or to one of EofA or EofB. */ #ifndef SQLITE_OMIT_COMPOUND_SELECT static int multiSelectOrderBy( Parse *pParse, /* Parsing context */ Select *p, /* The right-most of SELECTs to be coded */ SelectDest *pDest /* What to do with query results */ ){ int i, j; /* Loop counters */ Select *pPrior; /* Another SELECT immediately to our left */ Vdbe *v; /* Generate code to this VDBE */ SelectDest destA; /* Destination for coroutine A */ SelectDest destB; /* Destination for coroutine B */ int regAddrA; /* Address register for select-A coroutine */ int regAddrB; /* Address register for select-B coroutine */ int addrSelectA; /* Address of the select-A coroutine */ int addrSelectB; /* Address of the select-B coroutine */ int regOutA; /* Address register for the output-A subroutine */ int regOutB; /* Address register for the output-B subroutine */ int addrOutA; /* Address of the output-A subroutine */ int addrOutB = 0; /* Address of the output-B subroutine */ int addrEofA; /* Address of the select-A-exhausted subroutine */ int addrEofA_noB; /* Alternate addrEofA if B is uninitialized */ int addrEofB; /* Address of the select-B-exhausted subroutine */ int addrAltB; /* Address of the A<B subroutine */ int addrAeqB; /* Address of the A==B subroutine */ int addrAgtB; /* Address of the A>B subroutine */ int regLimitA; /* Limit register for select-A */ int regLimitB; /* Limit register for select-A */ int regPrev; /* A range of registers to hold previous output */ int savedLimit; /* Saved value of p->iLimit */ int savedOffset; /* Saved value of p->iOffset */ int labelCmpr; /* Label for the start of the merge algorithm */ int labelEnd; /* Label for the end of the overall SELECT stmt */ int addr1; /* Jump instructions that get retargetted */ int op; /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */ KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */ KeyInfo *pKeyMerge; /* Comparison information for merging rows */ sqlite3 *db; /* Database connection */ ExprList *pOrderBy; /* The ORDER BY clause */ int nOrderBy; /* Number of terms in the ORDER BY clause */ int *aPermute; /* Mapping from ORDER BY terms to result set columns */ assert( p->pOrderBy!=0 ); assert( pKeyDup==0 ); /* "Managed" code needs this. Ticket #3382. */ db = pParse->db; v = pParse->pVdbe; assert( v!=0 ); /* Already thrown the error if VDBE alloc failed */ labelEnd = sqlite3VdbeMakeLabel(pParse); labelCmpr = sqlite3VdbeMakeLabel(pParse); /* Patch up the ORDER BY clause */ op = p->op; pPrior = p->pPrior; assert( pPrior->pOrderBy==0 ); pOrderBy = p->pOrderBy; assert( pOrderBy ); nOrderBy = pOrderBy->nExpr; /* For operators other than UNION ALL we have to make sure that ** the ORDER BY clause covers every term of the result set. Add ** terms to the ORDER BY clause as necessary. */ if( op!=TK_ALL ){ for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){ struct ExprList_item *pItem; for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){ assert( pItem->u.x.iOrderByCol>0 ); if( pItem->u.x.iOrderByCol==i ) break; } if( j==nOrderBy ){ Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0); if( pNew==0 ) return SQLITE_NOMEM_BKPT; pNew->flags |= EP_IntValue; pNew->u.iValue = i; p->pOrderBy = pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew); if( pOrderBy ) pOrderBy->a[nOrderBy++].u.x.iOrderByCol = (u16)i; } } } /* Compute the comparison permutation and keyinfo that is used with ** the permutation used to determine if the next ** row of results comes from selectA or selectB. Also add explicit ** collations to the ORDER BY clause terms so that when the subqueries ** to the right and the left are evaluated, they use the correct ** collation. */ aPermute = sqlite3DbMallocRawNN(db, sizeof(int)*(nOrderBy + 1)); if( aPermute ){ struct ExprList_item *pItem; aPermute[0] = nOrderBy; for(i=1, pItem=pOrderBy->a; i<=nOrderBy; i++, pItem++){ assert( pItem->u.x.iOrderByCol>0 ); assert( pItem->u.x.iOrderByCol<=p->pEList->nExpr ); aPermute[i] = pItem->u.x.iOrderByCol - 1; } pKeyMerge = multiSelectOrderByKeyInfo(pParse, p, 1); }else{ pKeyMerge = 0; } /* Reattach the ORDER BY clause to the query. */ p->pOrderBy = pOrderBy; pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0); /* Allocate a range of temporary registers and the KeyInfo needed ** for the logic that removes duplicate result rows when the ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL). */ if( op==TK_ALL ){ regPrev = 0; }else{ int nExpr = p->pEList->nExpr; assert( nOrderBy>=nExpr || db->mallocFailed ); regPrev = pParse->nMem+1; pParse->nMem += nExpr+1; sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev); pKeyDup = sqlite3KeyInfoAlloc(db, nExpr, 1); if( pKeyDup ){ assert( sqlite3KeyInfoIsWriteable(pKeyDup) ); for(i=0; i<nExpr; i++){ pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i); pKeyDup->aSortFlags[i] = 0; } } } /* Separate the left and the right query from one another */ p->pPrior = 0; pPrior->pNext = 0; sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER"); if( pPrior->pPrior==0 ){ sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER"); } /* Compute the limit registers */ computeLimitRegisters(pParse, p, labelEnd); if( p->iLimit && op==TK_ALL ){ regLimitA = ++pParse->nMem; regLimitB = ++pParse->nMem; sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit, regLimitA); sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB); }else{ regLimitA = regLimitB = 0; } sqlite3ExprDelete(db, p->pLimit); p->pLimit = 0; regAddrA = ++pParse->nMem; regAddrB = ++pParse->nMem; regOutA = ++pParse->nMem; regOutB = ++pParse->nMem; sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA); sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB); ExplainQueryPlan((pParse, 1, "MERGE (%s)", selectOpName(p->op))); /* Generate a coroutine to evaluate the SELECT statement to the ** left of the compound operator - the "A" select. */ addrSelectA = sqlite3VdbeCurrentAddr(v) + 1; addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrA, 0, addrSelectA); VdbeComment((v, "left SELECT")); pPrior->iLimit = regLimitA; ExplainQueryPlan((pParse, 1, "LEFT")); sqlite3Select(pParse, pPrior, &destA); sqlite3VdbeEndCoroutine(v, regAddrA); sqlite3VdbeJumpHere(v, addr1); /* Generate a coroutine to evaluate the SELECT statement on ** the right - the "B" select */ addrSelectB = sqlite3VdbeCurrentAddr(v) + 1; addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrB, 0, addrSelectB); VdbeComment((v, "right SELECT")); savedLimit = p->iLimit; savedOffset = p->iOffset; p->iLimit = regLimitB; p->iOffset = 0; ExplainQueryPlan((pParse, 1, "RIGHT")); sqlite3Select(pParse, p, &destB); p->iLimit = savedLimit; p->iOffset = savedOffset; sqlite3VdbeEndCoroutine(v, regAddrB); /* Generate a subroutine that outputs the current row of the A ** select as the next output row of the compound select. */ VdbeNoopComment((v, "Output routine for A")); addrOutA = generateOutputSubroutine(pParse, p, &destA, pDest, regOutA, regPrev, pKeyDup, labelEnd); /* Generate a subroutine that outputs the current row of the B ** select as the next output row of the compound select. */ if( op==TK_ALL || op==TK_UNION ){ VdbeNoopComment((v, "Output routine for B")); addrOutB = generateOutputSubroutine(pParse, p, &destB, pDest, regOutB, regPrev, pKeyDup, labelEnd); } sqlite3KeyInfoUnref(pKeyDup); /* Generate a subroutine to run when the results from select A ** are exhausted and only data in select B remains. */ if( op==TK_EXCEPT || op==TK_INTERSECT ){ addrEofA_noB = addrEofA = labelEnd; }else{ VdbeNoopComment((v, "eof-A subroutine")); addrEofA = sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB); addrEofA_noB = sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, labelEnd); VdbeCoverage(v); sqlite3VdbeGoto(v, addrEofA); p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow); } /* Generate a subroutine to run when the results from select B ** are exhausted and only data in select A remains. */ if( op==TK_INTERSECT ){ addrEofB = addrEofA; if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow; }else{ VdbeNoopComment((v, "eof-B subroutine")); addrEofB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA); sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, labelEnd); VdbeCoverage(v); sqlite3VdbeGoto(v, addrEofB); } /* Generate code to handle the case of A<B */ VdbeNoopComment((v, "A-lt-B subroutine")); addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA); sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v); sqlite3VdbeGoto(v, labelCmpr); /* Generate code to handle the case of A==B */ if( op==TK_ALL ){ addrAeqB = addrAltB; }else if( op==TK_INTERSECT ){ addrAeqB = addrAltB; addrAltB++; }else{ VdbeNoopComment((v, "A-eq-B subroutine")); addrAeqB = sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v); sqlite3VdbeGoto(v, labelCmpr); } /* Generate code to handle the case of A>B */ VdbeNoopComment((v, "A-gt-B subroutine")); addrAgtB = sqlite3VdbeCurrentAddr(v); if( op==TK_ALL || op==TK_UNION ){ sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB); } sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v); sqlite3VdbeGoto(v, labelCmpr); /* This code runs once to initialize everything. */ sqlite3VdbeJumpHere(v, addr1); sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA_noB); VdbeCoverage(v); sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v); /* Implement the main merge loop */ sqlite3VdbeResolveLabel(v, labelCmpr); sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY); sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy, (char*)pKeyMerge, P4_KEYINFO); sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE); sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB); VdbeCoverage(v); /* Jump to the this point in order to terminate the query. */ sqlite3VdbeResolveLabel(v, labelEnd); /* Reassembly the compound query so that it will be freed correctly ** by the calling function */ if( p->pPrior ){ sqlite3SelectDelete(db, p->pPrior); } p->pPrior = pPrior; pPrior->pNext = p; /*** TBD: Insert subroutine calls to close cursors on incomplete **** subqueries ****/ ExplainQueryPlanPop(pParse); return pParse->nErr!=0; } #endif #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) /* An instance of the SubstContext object describes an substitution edit ** to be performed on a parse tree. ** ** All references to columns in table iTable are to be replaced by corresponding ** expressions in pEList. */ typedef struct SubstContext { Parse *pParse; /* The parsing context */ int iTable; /* Replace references to this table */ int iNewTable; /* New table number */ int isLeftJoin; /* Add TK_IF_NULL_ROW opcodes on each replacement */ ExprList *pEList; /* Replacement expressions */ } SubstContext; /* Forward Declarations */ static void substExprList(SubstContext*, ExprList*); static void substSelect(SubstContext*, Select*, int); /* ** Scan through the expression pExpr. Replace every reference to ** a column in table number iTable with a copy of the iColumn-th ** entry in pEList. (But leave references to the ROWID column ** unchanged.) ** ** This routine is part of the flattening procedure. A subquery ** whose result set is defined by pEList appears as entry in the ** FROM clause of a SELECT such that the VDBE cursor assigned to that ** FORM clause entry is iTable. This routine makes the necessary ** changes to pExpr so that it refers directly to the source table ** of the subquery rather the result set of the subquery. */ static Expr *substExpr( SubstContext *pSubst, /* Description of the substitution */ Expr *pExpr /* Expr in which substitution occurs */ ){ if( pExpr==0 ) return 0; if( ExprHasProperty(pExpr, EP_FromJoin) && pExpr->iRightJoinTable==pSubst->iTable ){ pExpr->iRightJoinTable = pSubst->iNewTable; } if( pExpr->op==TK_COLUMN && pExpr->iTable==pSubst->iTable ){ if( pExpr->iColumn<0 ){ pExpr->op = TK_NULL; }else{ Expr *pNew; Expr *pCopy = pSubst->pEList->a[pExpr->iColumn].pExpr; Expr ifNullRow; assert( pSubst->pEList!=0 && pExpr->iColumn<pSubst->pEList->nExpr ); assert( pExpr->pRight==0 ); if( sqlite3ExprIsVector(pCopy) ){ sqlite3VectorErrorMsg(pSubst->pParse, pCopy); }else{ sqlite3 *db = pSubst->pParse->db; if( pSubst->isLeftJoin && pCopy->op!=TK_COLUMN ){ memset(&ifNullRow, 0, sizeof(ifNullRow)); ifNullRow.op = TK_IF_NULL_ROW; ifNullRow.pLeft = pCopy; ifNullRow.iTable = pSubst->iNewTable; pCopy = &ifNullRow; } testcase( ExprHasProperty(pCopy, EP_Subquery) ); pNew = sqlite3ExprDup(db, pCopy, 0); if( pNew && pSubst->isLeftJoin ){ ExprSetProperty(pNew, EP_CanBeNull); } if( pNew && ExprHasProperty(pExpr,EP_FromJoin) ){ pNew->iRightJoinTable = pExpr->iRightJoinTable; ExprSetProperty(pNew, EP_FromJoin); } sqlite3ExprDelete(db, pExpr); pExpr = pNew; /* Ensure that the expression now has an implicit collation sequence, ** just as it did when it was a column of a view or sub-query. */ if( pExpr ){ if( pExpr->op!=TK_COLUMN && pExpr->op!=TK_COLLATE ){ CollSeq *pColl = sqlite3ExprCollSeq(pSubst->pParse, pExpr); pExpr = sqlite3ExprAddCollateString(pSubst->pParse, pExpr, (pColl ? pColl->zName : "BINARY") ); } ExprClearProperty(pExpr, EP_Collate); } } } }else{ if( pExpr->op==TK_IF_NULL_ROW && pExpr->iTable==pSubst->iTable ){ pExpr->iTable = pSubst->iNewTable; } pExpr->pLeft = substExpr(pSubst, pExpr->pLeft); pExpr->pRight = substExpr(pSubst, pExpr->pRight); if( ExprHasProperty(pExpr, EP_xIsSelect) ){ substSelect(pSubst, pExpr->x.pSelect, 1); }else{ substExprList(pSubst, pExpr->x.pList); } #ifndef SQLITE_OMIT_WINDOWFUNC if( ExprHasProperty(pExpr, EP_WinFunc) ){ Window *pWin = pExpr->y.pWin; pWin->pFilter = substExpr(pSubst, pWin->pFilter); substExprList(pSubst, pWin->pPartition); substExprList(pSubst, pWin->pOrderBy); } #endif } return pExpr; } static void substExprList( SubstContext *pSubst, /* Description of the substitution */ ExprList *pList /* List to scan and in which to make substitutes */ ){ int i; if( pList==0 ) return; for(i=0; i<pList->nExpr; i++){ pList->a[i].pExpr = substExpr(pSubst, pList->a[i].pExpr); } } static void substSelect( SubstContext *pSubst, /* Description of the substitution */ Select *p, /* SELECT statement in which to make substitutions */ int doPrior /* Do substitutes on p->pPrior too */ ){ SrcList *pSrc; struct SrcList_item *pItem; int i; if( !p ) return; do{ substExprList(pSubst, p->pEList); substExprList(pSubst, p->pGroupBy); substExprList(pSubst, p->pOrderBy); p->pHaving = substExpr(pSubst, p->pHaving); p->pWhere = substExpr(pSubst, p->pWhere); pSrc = p->pSrc; assert( pSrc!=0 ); for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){ substSelect(pSubst, pItem->pSelect, 1); if( pItem->fg.isTabFunc ){ substExprList(pSubst, pItem->u1.pFuncArg); } } }while( doPrior && (p = p->pPrior)!=0 ); } #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */ #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) /* ** This routine attempts to flatten subqueries as a performance optimization. ** This routine returns 1 if it makes changes and 0 if no flattening occurs. ** ** To understand the concept of flattening, consider the following ** query: ** ** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5 ** ** The default way of implementing this query is to execute the ** subquery first and store the results in a temporary table, then ** run the outer query on that temporary table. This requires two ** passes over the data. Furthermore, because the temporary table ** has no indices, the WHERE clause on the outer query cannot be ** optimized. ** ** This routine attempts to rewrite queries such as the above into ** a single flat select, like this: ** ** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5 ** ** The code generated for this simplification gives the same result ** but only has to scan the data once. And because indices might ** exist on the table t1, a complete scan of the data might be ** avoided. ** ** Flattening is subject to the following constraints: ** ** (**) We no longer attempt to flatten aggregate subqueries. Was: ** The subquery and the outer query cannot both be aggregates. ** ** (**) We no longer attempt to flatten aggregate subqueries. Was: ** (2) If the subquery is an aggregate then ** (2a) the outer query must not be a join and ** (2b) the outer query must not use subqueries ** other than the one FROM-clause subquery that is a candidate ** for flattening. (This is due to ticket [2f7170d73bf9abf80] ** from 2015-02-09.) ** ** (3) If the subquery is the right operand of a LEFT JOIN then ** (3a) the subquery may not be a join and ** (3b) the FROM clause of the subquery may not contain a virtual ** table and ** (3c) the outer query may not be an aggregate. ** ** (4) The subquery can not be DISTINCT. ** ** (**) At one point restrictions (4) and (5) defined a subset of DISTINCT ** sub-queries that were excluded from this optimization. Restriction ** (4) has since been expanded to exclude all DISTINCT subqueries. ** ** (**) We no longer attempt to flatten aggregate subqueries. Was: ** If the subquery is aggregate, the outer query may not be DISTINCT. ** ** (7) The subquery must have a FROM clause. TODO: For subqueries without ** A FROM clause, consider adding a FROM clause with the special ** table sqlite_once that consists of a single row containing a ** single NULL. ** ** (8) If the subquery uses LIMIT then the outer query may not be a join. ** ** (9) If the subquery uses LIMIT then the outer query may not be aggregate. ** ** (**) Restriction (10) was removed from the code on 2005-02-05 but we ** accidently carried the comment forward until 2014-09-15. Original ** constraint: "If the subquery is aggregate then the outer query ** may not use LIMIT." ** ** (11) The subquery and the outer query may not both have ORDER BY clauses. ** ** (**) Not implemented. Subsumed into restriction (3). Was previously ** a separate restriction deriving from ticket #350. ** ** (13) The subquery and outer query may not both use LIMIT. ** ** (14) The subquery may not use OFFSET. ** ** (15) If the outer query is part of a compound select, then the ** subquery may not use LIMIT. ** (See ticket #2339 and ticket [02a8e81d44]). ** ** (16) If the outer query is aggregate, then the subquery may not ** use ORDER BY. (Ticket #2942) This used to not matter ** until we introduced the group_concat() function. ** ** (17) If the subquery is a compound select, then ** (17a) all compound operators must be a UNION ALL, and ** (17b) no terms within the subquery compound may be aggregate ** or DISTINCT, and ** (17c) every term within the subquery compound must have a FROM clause ** (17d) the outer query may not be ** (17d1) aggregate, or ** (17d2) DISTINCT, or ** (17d3) a join. ** ** The parent and sub-query may contain WHERE clauses. Subject to ** rules (11), (13) and (14), they may also contain ORDER BY, ** LIMIT and OFFSET clauses. The subquery cannot use any compound ** operator other than UNION ALL because all the other compound ** operators have an implied DISTINCT which is disallowed by ** restriction (4). ** ** Also, each component of the sub-query must return the same number ** of result columns. This is actually a requirement for any compound ** SELECT statement, but all the code here does is make sure that no ** such (illegal) sub-query is flattened. The caller will detect the ** syntax error and return a detailed message. ** ** (18) If the sub-query is a compound select, then all terms of the ** ORDER BY clause of the parent must be simple references to ** columns of the sub-query. ** ** (19) If the subquery uses LIMIT then the outer query may not ** have a WHERE clause. ** ** (20) If the sub-query is a compound select, then it must not use ** an ORDER BY clause. Ticket #3773. We could relax this constraint ** somewhat by saying that the terms of the ORDER BY clause must ** appear as unmodified result columns in the outer query. But we ** have other optimizations in mind to deal with that case. ** ** (21) If the subquery uses LIMIT then the outer query may not be ** DISTINCT. (See ticket [752e1646fc]). ** ** (22) The subquery may not be a recursive CTE. ** ** (**) Subsumed into restriction (17d3). Was: If the outer query is ** a recursive CTE, then the sub-query may not be a compound query. ** This restriction is because transforming the ** parent to a compound query confuses the code that handles ** recursive queries in multiSelect(). ** ** (**) We no longer attempt to flatten aggregate subqueries. Was: ** The subquery may not be an aggregate that uses the built-in min() or ** or max() functions. (Without this restriction, a query like: ** "SELECT x FROM (SELECT max(y), x FROM t1)" would not necessarily ** return the value X for which Y was maximal.) ** ** (25) If either the subquery or the parent query contains a window ** function in the select list or ORDER BY clause, flattening ** is not attempted. ** ** ** In this routine, the "p" parameter is a pointer to the outer query. ** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query ** uses aggregates. ** ** If flattening is not attempted, this routine is a no-op and returns 0. ** If flattening is attempted this routine returns 1. ** ** All of the expression analysis must occur on both the outer query and ** the subquery before this routine runs. */ static int flattenSubquery( Parse *pParse, /* Parsing context */ Select *p, /* The parent or outer SELECT statement */ int iFrom, /* Index in p->pSrc->a[] of the inner subquery */ int isAgg /* True if outer SELECT uses aggregate functions */ ){ const char *zSavedAuthContext = pParse->zAuthContext; Select *pParent; /* Current UNION ALL term of the other query */ Select *pSub; /* The inner query or "subquery" */ Select *pSub1; /* Pointer to the rightmost select in sub-query */ SrcList *pSrc; /* The FROM clause of the outer query */ SrcList *pSubSrc; /* The FROM clause of the subquery */ int iParent; /* VDBE cursor number of the pSub result set temp table */ int iNewParent = -1;/* Replacement table for iParent */ int isLeftJoin = 0; /* True if pSub is the right side of a LEFT JOIN */ int i; /* Loop counter */ Expr *pWhere; /* The WHERE clause */ struct SrcList_item *pSubitem; /* The subquery */ sqlite3 *db = pParse->db; /* Check to see if flattening is permitted. Return 0 if not. */ assert( p!=0 ); assert( p->pPrior==0 ); if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0; pSrc = p->pSrc; assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc ); pSubitem = &pSrc->a[iFrom]; iParent = pSubitem->iCursor; pSub = pSubitem->pSelect; assert( pSub!=0 ); #ifndef SQLITE_OMIT_WINDOWFUNC if( p->pWin || pSub->pWin ) return 0; /* Restriction (25) */ #endif pSubSrc = pSub->pSrc; assert( pSubSrc ); /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants, ** not arbitrary expressions, we allowed some combining of LIMIT and OFFSET ** because they could be computed at compile-time. But when LIMIT and OFFSET ** became arbitrary expressions, we were forced to add restrictions (13) ** and (14). */ if( pSub->pLimit && p->pLimit ) return 0; /* Restriction (13) */ if( pSub->pLimit && pSub->pLimit->pRight ) return 0; /* Restriction (14) */ if( (p->selFlags & SF_Compound)!=0 && pSub->pLimit ){ return 0; /* Restriction (15) */ } if( pSubSrc->nSrc==0 ) return 0; /* Restriction (7) */ if( pSub->selFlags & SF_Distinct ) return 0; /* Restriction (4) */ if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){ return 0; /* Restrictions (8)(9) */ } if( p->pOrderBy && pSub->pOrderBy ){ return 0; /* Restriction (11) */ } if( isAgg && pSub->pOrderBy ) return 0; /* Restriction (16) */ if( pSub->pLimit && p->pWhere ) return 0; /* Restriction (19) */ if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){ return 0; /* Restriction (21) */ } if( pSub->selFlags & (SF_Recursive) ){ return 0; /* Restrictions (22) */ } /* ** If the subquery is the right operand of a LEFT JOIN, then the ** subquery may not be a join itself (3a). Example of why this is not ** allowed: ** ** t1 LEFT OUTER JOIN (t2 JOIN t3) ** ** If we flatten the above, we would get ** ** (t1 LEFT OUTER JOIN t2) JOIN t3 ** ** which is not at all the same thing. ** ** If the subquery is the right operand of a LEFT JOIN, then the outer ** query cannot be an aggregate. (3c) This is an artifact of the way ** aggregates are processed - there is no mechanism to determine if ** the LEFT JOIN table should be all-NULL. ** ** See also tickets #306, #350, and #3300. */ if( (pSubitem->fg.jointype & JT_OUTER)!=0 ){ isLeftJoin = 1; if( pSubSrc->nSrc>1 || isAgg || IsVirtual(pSubSrc->a[0].pTab) ){ /* (3a) (3c) (3b) */ return 0; } } #ifdef SQLITE_EXTRA_IFNULLROW else if( iFrom>0 && !isAgg ){ /* Setting isLeftJoin to -1 causes OP_IfNullRow opcodes to be generated for ** every reference to any result column from subquery in a join, even ** though they are not necessary. This will stress-test the OP_IfNullRow ** opcode. */ isLeftJoin = -1; } #endif /* Restriction (17): If the sub-query is a compound SELECT, then it must ** use only the UNION ALL operator. And none of the simple select queries ** that make up the compound SELECT are allowed to be aggregate or distinct ** queries. */ if( pSub->pPrior ){ if( pSub->pOrderBy ){ return 0; /* Restriction (20) */ } if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){ return 0; /* (17d1), (17d2), or (17d3) */ } for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){ testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct ); testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate ); assert( pSub->pSrc!=0 ); assert( pSub->pEList->nExpr==pSub1->pEList->nExpr ); if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0 /* (17b) */ || (pSub1->pPrior && pSub1->op!=TK_ALL) /* (17a) */ || pSub1->pSrc->nSrc<1 /* (17c) */ ){ return 0; } testcase( pSub1->pSrc->nSrc>1 ); } /* Restriction (18). */ if( p->pOrderBy ){ int ii; for(ii=0; ii<p->pOrderBy->nExpr; ii++){ if( p->pOrderBy->a[ii].u.x.iOrderByCol==0 ) return 0; } } } /* Ex-restriction (23): ** The only way that the recursive part of a CTE can contain a compound ** subquery is for the subquery to be one term of a join. But if the ** subquery is a join, then the flattening has already been stopped by ** restriction (17d3) */ assert( (p->selFlags & SF_Recursive)==0 || pSub->pPrior==0 ); /***** If we reach this point, flattening is permitted. *****/ SELECTTRACE(1,pParse,p,("flatten %u.%p from term %d\n", pSub->selId, pSub, iFrom)); /* Authorize the subquery */ pParse->zAuthContext = pSubitem->zName; TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0); testcase( i==SQLITE_DENY ); pParse->zAuthContext = zSavedAuthContext; /* If the sub-query is a compound SELECT statement, then (by restrictions ** 17 and 18 above) it must be a UNION ALL and the parent query must ** be of the form: ** ** SELECT <expr-list> FROM (<sub-query>) <where-clause> ** ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or ** OFFSET clauses and joins them to the left-hand-side of the original ** using UNION ALL operators. In this case N is the number of simple ** select statements in the compound sub-query. ** ** Example: ** ** SELECT a+1 FROM ( ** SELECT x FROM tab ** UNION ALL ** SELECT y FROM tab ** UNION ALL ** SELECT abs(z*2) FROM tab2 ** ) WHERE a!=5 ORDER BY 1 ** ** Transformed into: ** ** SELECT x+1 FROM tab WHERE x+1!=5 ** UNION ALL ** SELECT y+1 FROM tab WHERE y+1!=5 ** UNION ALL ** SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5 ** ORDER BY 1 ** ** We call this the "compound-subquery flattening". */ for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){ Select *pNew; ExprList *pOrderBy = p->pOrderBy; Expr *pLimit = p->pLimit; Select *pPrior = p->pPrior; p->pOrderBy = 0; p->pSrc = 0; p->pPrior = 0; p->pLimit = 0; pNew = sqlite3SelectDup(db, p, 0); p->pLimit = pLimit; p->pOrderBy = pOrderBy; p->pSrc = pSrc; p->op = TK_ALL; if( pNew==0 ){ p->pPrior = pPrior; }else{ pNew->pPrior = pPrior; if( pPrior ) pPrior->pNext = pNew; pNew->pNext = p; p->pPrior = pNew; SELECTTRACE(2,pParse,p,("compound-subquery flattener" " creates %u as peer\n",pNew->selId)); } if( db->mallocFailed ) return 1; } /* Begin flattening the iFrom-th entry of the FROM clause ** in the outer query. */ pSub = pSub1 = pSubitem->pSelect; /* Delete the transient table structure associated with the ** subquery */ sqlite3DbFree(db, pSubitem->zDatabase); sqlite3DbFree(db, pSubitem->zName); sqlite3DbFree(db, pSubitem->zAlias); pSubitem->zDatabase = 0; pSubitem->zName = 0; pSubitem->zAlias = 0; pSubitem->pSelect = 0; /* Defer deleting the Table object associated with the ** subquery until code generation is ** complete, since there may still exist Expr.pTab entries that ** refer to the subquery even after flattening. Ticket #3346. ** ** pSubitem->pTab is always non-NULL by test restrictions and tests above. */ if( ALWAYS(pSubitem->pTab!=0) ){ Table *pTabToDel = pSubitem->pTab; if( pTabToDel->nTabRef==1 ){ Parse *pToplevel = sqlite3ParseToplevel(pParse); pTabToDel->pNextZombie = pToplevel->pZombieTab; pToplevel->pZombieTab = pTabToDel; }else{ pTabToDel->nTabRef--; } pSubitem->pTab = 0; } /* The following loop runs once for each term in a compound-subquery ** flattening (as described above). If we are doing a different kind ** of flattening - a flattening other than a compound-subquery flattening - ** then this loop only runs once. ** ** This loop moves all of the FROM elements of the subquery into the ** the FROM clause of the outer query. Before doing this, remember ** the cursor number for the original outer query FROM element in ** iParent. The iParent cursor will never be used. Subsequent code ** will scan expressions looking for iParent references and replace ** those references with expressions that resolve to the subquery FROM ** elements we are now copying in. */ for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){ int nSubSrc; u8 jointype = 0; assert( pSub!=0 ); pSubSrc = pSub->pSrc; /* FROM clause of subquery */ nSubSrc = pSubSrc->nSrc; /* Number of terms in subquery FROM clause */ pSrc = pParent->pSrc; /* FROM clause of the outer query */ if( pSrc ){ assert( pParent==p ); /* First time through the loop */ jointype = pSubitem->fg.jointype; }else{ assert( pParent!=p ); /* 2nd and subsequent times through the loop */ pSrc = sqlite3SrcListAppend(pParse, 0, 0, 0); if( pSrc==0 ) break; pParent->pSrc = pSrc; } /* The subquery uses a single slot of the FROM clause of the outer ** query. If the subquery has more than one element in its FROM clause, ** then expand the outer query to make space for it to hold all elements ** of the subquery. ** ** Example: ** ** SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB; ** ** The outer query has 3 slots in its FROM clause. One slot of the ** outer query (the middle slot) is used by the subquery. The next ** block of code will expand the outer query FROM clause to 4 slots. ** The middle slot is expanded to two slots in order to make space ** for the two elements in the FROM clause of the subquery. */ if( nSubSrc>1 ){ pSrc = sqlite3SrcListEnlarge(pParse, pSrc, nSubSrc-1,iFrom+1); if( pSrc==0 ) break; pParent->pSrc = pSrc; } /* Transfer the FROM clause terms from the subquery into the ** outer query. */ for(i=0; i<nSubSrc; i++){ sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing); assert( pSrc->a[i+iFrom].fg.isTabFunc==0 ); pSrc->a[i+iFrom] = pSubSrc->a[i]; iNewParent = pSubSrc->a[i].iCursor; memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i])); } pSrc->a[iFrom].fg.jointype = jointype; /* Now begin substituting subquery result set expressions for ** references to the iParent in the outer query. ** ** Example: ** ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b; ** \ \_____________ subquery __________/ / ** \_____________________ outer query ______________________________/ ** ** We look at every expression in the outer query and every place we see ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10". */ if( pSub->pOrderBy ){ /* At this point, any non-zero iOrderByCol values indicate that the ** ORDER BY column expression is identical to the iOrderByCol'th ** expression returned by SELECT statement pSub. Since these values ** do not necessarily correspond to columns in SELECT statement pParent, ** zero them before transfering the ORDER BY clause. ** ** Not doing this may cause an error if a subsequent call to this ** function attempts to flatten a compound sub-query into pParent ** (the only way this can happen is if the compound sub-query is ** currently part of pSub->pSrc). See ticket [d11a6e908f]. */ ExprList *pOrderBy = pSub->pOrderBy; for(i=0; i<pOrderBy->nExpr; i++){ pOrderBy->a[i].u.x.iOrderByCol = 0; } assert( pParent->pOrderBy==0 ); pParent->pOrderBy = pOrderBy; pSub->pOrderBy = 0; } pWhere = pSub->pWhere; pSub->pWhere = 0; if( isLeftJoin>0 ){ sqlite3SetJoinExpr(pWhere, iNewParent); } pParent->pWhere = sqlite3ExprAnd(pParse, pWhere, pParent->pWhere); if( db->mallocFailed==0 ){ SubstContext x; x.pParse = pParse; x.iTable = iParent; x.iNewTable = iNewParent; x.isLeftJoin = isLeftJoin; x.pEList = pSub->pEList; substSelect(&x, pParent, 0); } /* The flattened query is a compound if either the inner or the ** outer query is a compound. */ pParent->selFlags |= pSub->selFlags & SF_Compound; assert( (pSub->selFlags & SF_Distinct)==0 ); /* restriction (17b) */ /* ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y; ** ** One is tempted to try to add a and b to combine the limits. But this ** does not work if either limit is negative. */ if( pSub->pLimit ){ pParent->pLimit = pSub->pLimit; pSub->pLimit = 0; } } /* Finially, delete what is left of the subquery and return ** success. */ sqlite3SelectDelete(db, pSub1); #if SELECTTRACE_ENABLED if( sqlite3SelectTrace & 0x100 ){ SELECTTRACE(0x100,pParse,p,("After flattening:\n")); sqlite3TreeViewSelect(0, p, 0); } #endif return 1; } #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */ /* ** A structure to keep track of all of the column values that are fixed to ** a known value due to WHERE clause constraints of the form COLUMN=VALUE. */ typedef struct WhereConst WhereConst; struct WhereConst { Parse *pParse; /* Parsing context */ int nConst; /* Number for COLUMN=CONSTANT terms */ int nChng; /* Number of times a constant is propagated */ Expr **apExpr; /* [i*2] is COLUMN and [i*2+1] is VALUE */ }; /* ** Add a new entry to the pConst object. Except, do not add duplicate ** pColumn entires. */ static void constInsert( WhereConst *pConst, /* The WhereConst into which we are inserting */ Expr *pColumn, /* The COLUMN part of the constraint */ Expr *pValue /* The VALUE part of the constraint */ ){ int i; assert( pColumn->op==TK_COLUMN ); /* 2018-10-25 ticket [cf5ed20f] ** Make sure the same pColumn is not inserted more than once */ for(i=0; i<pConst->nConst; i++){ const Expr *pExpr = pConst->apExpr[i*2]; assert( pExpr->op==TK_COLUMN ); if( pExpr->iTable==pColumn->iTable && pExpr->iColumn==pColumn->iColumn ){ return; /* Already present. Return without doing anything. */ } } pConst->nConst++; pConst->apExpr = sqlite3DbReallocOrFree(pConst->pParse->db, pConst->apExpr, pConst->nConst*2*sizeof(Expr*)); if( pConst->apExpr==0 ){ pConst->nConst = 0; }else{ if( ExprHasProperty(pValue, EP_FixedCol) ) pValue = pValue->pLeft; pConst->apExpr[pConst->nConst*2-2] = pColumn; pConst->apExpr[pConst->nConst*2-1] = pValue; } } /* ** Find all terms of COLUMN=VALUE or VALUE=COLUMN in pExpr where VALUE ** is a constant expression and where the term must be true because it ** is part of the AND-connected terms of the expression. For each term ** found, add it to the pConst structure. */ static void findConstInWhere(WhereConst *pConst, Expr *pExpr){ Expr *pRight, *pLeft; if( pExpr==0 ) return; if( ExprHasProperty(pExpr, EP_FromJoin) ) return; if( pExpr->op==TK_AND ){ findConstInWhere(pConst, pExpr->pRight); findConstInWhere(pConst, pExpr->pLeft); return; } if( pExpr->op!=TK_EQ ) return; pRight = pExpr->pRight; pLeft = pExpr->pLeft; assert( pRight!=0 ); assert( pLeft!=0 ); if( pRight->op==TK_COLUMN && !ExprHasProperty(pRight, EP_FixedCol) && sqlite3ExprIsConstant(pLeft) && sqlite3IsBinary(sqlite3ExprCompareCollSeq(pConst->pParse,pExpr)) ){ constInsert(pConst, pRight, pLeft); }else if( pLeft->op==TK_COLUMN && !ExprHasProperty(pLeft, EP_FixedCol) && sqlite3ExprIsConstant(pRight) && sqlite3IsBinary(sqlite3ExprCompareCollSeq(pConst->pParse,pExpr)) ){ constInsert(pConst, pLeft, pRight); } } /* ** This is a Walker expression callback. pExpr is a candidate expression ** to be replaced by a value. If pExpr is equivalent to one of the ** columns named in pWalker->u.pConst, then overwrite it with its ** corresponding value. */ static int propagateConstantExprRewrite(Walker *pWalker, Expr *pExpr){ int i; WhereConst *pConst; if( pExpr->op!=TK_COLUMN ) return WRC_Continue; if( ExprHasProperty(pExpr, EP_FixedCol) ) return WRC_Continue; pConst = pWalker->u.pConst; for(i=0; i<pConst->nConst; i++){ Expr *pColumn = pConst->apExpr[i*2]; if( pColumn==pExpr ) continue; if( pColumn->iTable!=pExpr->iTable ) continue; if( pColumn->iColumn!=pExpr->iColumn ) continue; /* A match is found. Add the EP_FixedCol property */ pConst->nChng++; ExprClearProperty(pExpr, EP_Leaf); ExprSetProperty(pExpr, EP_FixedCol); assert( pExpr->pLeft==0 ); pExpr->pLeft = sqlite3ExprDup(pConst->pParse->db, pConst->apExpr[i*2+1], 0); break; } return WRC_Prune; } /* ** The WHERE-clause constant propagation optimization. ** ** If the WHERE clause contains terms of the form COLUMN=CONSTANT or ** CONSTANT=COLUMN that must be tree (in other words, if the terms top-level ** AND-connected terms that are not part of a ON clause from a LEFT JOIN) ** then throughout the query replace all other occurrences of COLUMN ** with CONSTANT within the WHERE clause. ** ** For example, the query: ** ** SELECT * FROM t1, t2, t3 WHERE t1.a=39 AND t2.b=t1.a AND t3.c=t2.b ** ** Is transformed into ** ** SELECT * FROM t1, t2, t3 WHERE t1.a=39 AND t2.b=39 AND t3.c=39 ** ** Return true if any transformations where made and false if not. ** ** Implementation note: Constant propagation is tricky due to affinity ** and collating sequence interactions. Consider this example: ** ** CREATE TABLE t1(a INT,b TEXT); ** INSERT INTO t1 VALUES(123,'0123'); ** SELECT * FROM t1 WHERE a=123 AND b=a; ** SELECT * FROM t1 WHERE a=123 AND b=123; ** ** The two SELECT statements above should return different answers. b=a ** is alway true because the comparison uses numeric affinity, but b=123 ** is false because it uses text affinity and '0123' is not the same as '123'. ** To work around this, the expression tree is not actually changed from ** "b=a" to "b=123" but rather the "a" in "b=a" is tagged with EP_FixedCol ** and the "123" value is hung off of the pLeft pointer. Code generator ** routines know to generate the constant "123" instead of looking up the ** column value. Also, to avoid collation problems, this optimization is ** only attempted if the "a=123" term uses the default BINARY collation. */ static int propagateConstants( Parse *pParse, /* The parsing context */ Select *p /* The query in which to propagate constants */ ){ WhereConst x; Walker w; int nChng = 0; x.pParse = pParse; do{ x.nConst = 0; x.nChng = 0; x.apExpr = 0; findConstInWhere(&x, p->pWhere); if( x.nConst ){ memset(&w, 0, sizeof(w)); w.pParse = pParse; w.xExprCallback = propagateConstantExprRewrite; w.xSelectCallback = sqlite3SelectWalkNoop; w.xSelectCallback2 = 0; w.walkerDepth = 0; w.u.pConst = &x; sqlite3WalkExpr(&w, p->pWhere); sqlite3DbFree(x.pParse->db, x.apExpr); nChng += x.nChng; } }while( x.nChng ); return nChng; } #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) /* ** Make copies of relevant WHERE clause terms of the outer query into ** the WHERE clause of subquery. Example: ** ** SELECT * FROM (SELECT a AS x, c-d AS y FROM t1) WHERE x=5 AND y=10; ** ** Transformed into: ** ** SELECT * FROM (SELECT a AS x, c-d AS y FROM t1 WHERE a=5 AND c-d=10) ** WHERE x=5 AND y=10; ** ** The hope is that the terms added to the inner query will make it more ** efficient. ** ** Do not attempt this optimization if: ** ** (1) (** This restriction was removed on 2017-09-29. We used to ** disallow this optimization for aggregate subqueries, but now ** it is allowed by putting the extra terms on the HAVING clause. ** The added HAVING clause is pointless if the subquery lacks ** a GROUP BY clause. But such a HAVING clause is also harmless ** so there does not appear to be any reason to add extra logic ** to suppress it. **) ** ** (2) The inner query is the recursive part of a common table expression. ** ** (3) The inner query has a LIMIT clause (since the changes to the WHERE ** clause would change the meaning of the LIMIT). ** ** (4) The inner query is the right operand of a LEFT JOIN and the ** expression to be pushed down does not come from the ON clause ** on that LEFT JOIN. ** ** (5) The WHERE clause expression originates in the ON or USING clause ** of a LEFT JOIN where iCursor is not the right-hand table of that ** left join. An example: ** ** SELECT * ** FROM (SELECT 1 AS a1 UNION ALL SELECT 2) AS aa ** JOIN (SELECT 1 AS b2 UNION ALL SELECT 2) AS bb ON (a1=b2) ** LEFT JOIN (SELECT 8 AS c3 UNION ALL SELECT 9) AS cc ON (b2=2); ** ** The correct answer is three rows: (1,1,NULL),(2,2,8),(2,2,9). ** But if the (b2=2) term were to be pushed down into the bb subquery, ** then the (1,1,NULL) row would be suppressed. ** ** (6) The inner query features one or more window-functions (since ** changes to the WHERE clause of the inner query could change the ** window over which window functions are calculated). ** ** Return 0 if no changes are made and non-zero if one or more WHERE clause ** terms are duplicated into the subquery. */ static int pushDownWhereTerms( Parse *pParse, /* Parse context (for malloc() and error reporting) */ Select *pSubq, /* The subquery whose WHERE clause is to be augmented */ Expr *pWhere, /* The WHERE clause of the outer query */ int iCursor, /* Cursor number of the subquery */ int isLeftJoin /* True if pSubq is the right term of a LEFT JOIN */ ){ Expr *pNew; int nChng = 0; if( pWhere==0 ) return 0; if( pSubq->selFlags & SF_Recursive ) return 0; /* restriction (2) */ #ifndef SQLITE_OMIT_WINDOWFUNC if( pSubq->pWin ) return 0; /* restriction (6) */ #endif #ifdef SQLITE_DEBUG /* Only the first term of a compound can have a WITH clause. But make ** sure no other terms are marked SF_Recursive in case something changes ** in the future. */ { Select *pX; for(pX=pSubq; pX; pX=pX->pPrior){ assert( (pX->selFlags & (SF_Recursive))==0 ); } } #endif if( pSubq->pLimit!=0 ){ return 0; /* restriction (3) */ } while( pWhere->op==TK_AND ){ nChng += pushDownWhereTerms(pParse, pSubq, pWhere->pRight, iCursor, isLeftJoin); pWhere = pWhere->pLeft; } if( isLeftJoin && (ExprHasProperty(pWhere,EP_FromJoin)==0 || pWhere->iRightJoinTable!=iCursor) ){ return 0; /* restriction (4) */ } if( ExprHasProperty(pWhere,EP_FromJoin) && pWhere->iRightJoinTable!=iCursor ){ return 0; /* restriction (5) */ } if( sqlite3ExprIsTableConstant(pWhere, iCursor) ){ nChng++; while( pSubq ){ SubstContext x; pNew = sqlite3ExprDup(pParse->db, pWhere, 0); unsetJoinExpr(pNew, -1); x.pParse = pParse; x.iTable = iCursor; x.iNewTable = iCursor; x.isLeftJoin = 0; x.pEList = pSubq->pEList; pNew = substExpr(&x, pNew); if( pSubq->selFlags & SF_Aggregate ){ pSubq->pHaving = sqlite3ExprAnd(pParse, pSubq->pHaving, pNew); }else{ pSubq->pWhere = sqlite3ExprAnd(pParse, pSubq->pWhere, pNew); } pSubq = pSubq->pPrior; } } return nChng; } #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */ /* ** The pFunc is the only aggregate function in the query. Check to see ** if the query is a candidate for the min/max optimization. ** ** If the query is a candidate for the min/max optimization, then set ** *ppMinMax to be an ORDER BY clause to be used for the optimization ** and return either WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX depending on ** whether pFunc is a min() or max() function. ** ** If the query is not a candidate for the min/max optimization, return ** WHERE_ORDERBY_NORMAL (which must be zero). ** ** This routine must be called after aggregate functions have been ** located but before their arguments have been subjected to aggregate ** analysis. */ static u8 minMaxQuery(sqlite3 *db, Expr *pFunc, ExprList **ppMinMax){ int eRet = WHERE_ORDERBY_NORMAL; /* Return value */ ExprList *pEList = pFunc->x.pList; /* Arguments to agg function */ const char *zFunc; /* Name of aggregate function pFunc */ ExprList *pOrderBy; u8 sortFlags; assert( *ppMinMax==0 ); assert( pFunc->op==TK_AGG_FUNCTION ); assert( !IsWindowFunc(pFunc) ); if( pEList==0 || pEList->nExpr!=1 || ExprHasProperty(pFunc, EP_WinFunc) ){ return eRet; } zFunc = pFunc->u.zToken; if( sqlite3StrICmp(zFunc, "min")==0 ){ eRet = WHERE_ORDERBY_MIN; sortFlags = KEYINFO_ORDER_BIGNULL; }else if( sqlite3StrICmp(zFunc, "max")==0 ){ eRet = WHERE_ORDERBY_MAX; sortFlags = KEYINFO_ORDER_DESC; }else{ return eRet; } *ppMinMax = pOrderBy = sqlite3ExprListDup(db, pEList, 0); assert( pOrderBy!=0 || db->mallocFailed ); if( pOrderBy ) pOrderBy->a[0].sortFlags = sortFlags; return eRet; } /* ** The select statement passed as the first argument is an aggregate query. ** The second argument is the associated aggregate-info object. This ** function tests if the SELECT is of the form: ** ** SELECT count(*) FROM <tbl> ** ** where table is a database table, not a sub-select or view. If the query ** does match this pattern, then a pointer to the Table object representing ** <tbl> is returned. Otherwise, 0 is returned. */ static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){ Table *pTab; Expr *pExpr; assert( !p->pGroupBy ); if( p->pWhere || p->pEList->nExpr!=1 || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect ){ return 0; } pTab = p->pSrc->a[0].pTab; pExpr = p->pEList->a[0].pExpr; assert( pTab && !pTab->pSelect && pExpr ); if( IsVirtual(pTab) ) return 0; if( pExpr->op!=TK_AGG_FUNCTION ) return 0; if( NEVER(pAggInfo->nFunc==0) ) return 0; if( (pAggInfo->aFunc[0].pFunc->funcFlags&SQLITE_FUNC_COUNT)==0 ) return 0; if( ExprHasProperty(pExpr, EP_Distinct|EP_WinFunc) ) return 0; return pTab; } /* ** If the source-list item passed as an argument was augmented with an ** INDEXED BY clause, then try to locate the specified index. If there ** was such a clause and the named index cannot be found, return ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate ** pFrom->pIndex and return SQLITE_OK. */ int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){ if( pFrom->pTab && pFrom->fg.isIndexedBy ){ Table *pTab = pFrom->pTab; char *zIndexedBy = pFrom->u1.zIndexedBy; Index *pIdx; for(pIdx=pTab->pIndex; pIdx && sqlite3StrICmp(pIdx->zName, zIndexedBy); pIdx=pIdx->pNext ); if( !pIdx ){ sqlite3ErrorMsg(pParse, "no such index: %s", zIndexedBy, 0); pParse->checkSchema = 1; return SQLITE_ERROR; } pFrom->pIBIndex = pIdx; } return SQLITE_OK; } /* ** Detect compound SELECT statements that use an ORDER BY clause with ** an alternative collating sequence. ** ** SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ... ** ** These are rewritten as a subquery: ** ** SELECT * FROM (SELECT ... FROM t1 EXCEPT SELECT ... FROM t2) ** ORDER BY ... COLLATE ... ** ** This transformation is necessary because the multiSelectOrderBy() routine ** above that generates the code for a compound SELECT with an ORDER BY clause ** uses a merge algorithm that requires the same collating sequence on the ** result columns as on the ORDER BY clause. See ticket ** http://www.sqlite.org/src/info/6709574d2a ** ** This transformation is only needed for EXCEPT, INTERSECT, and UNION. ** The UNION ALL operator works fine with multiSelectOrderBy() even when ** there are COLLATE terms in the ORDER BY. */ static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){ int i; Select *pNew; Select *pX; sqlite3 *db; struct ExprList_item *a; SrcList *pNewSrc; Parse *pParse; Token dummy; if( p->pPrior==0 ) return WRC_Continue; if( p->pOrderBy==0 ) return WRC_Continue; for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){} if( pX==0 ) return WRC_Continue; a = p->pOrderBy->a; for(i=p->pOrderBy->nExpr-1; i>=0; i--){ if( a[i].pExpr->flags & EP_Collate ) break; } if( i<0 ) return WRC_Continue; /* If we reach this point, that means the transformation is required. */ pParse = pWalker->pParse; db = pParse->db; pNew = sqlite3DbMallocZero(db, sizeof(*pNew) ); if( pNew==0 ) return WRC_Abort; memset(&dummy, 0, sizeof(dummy)); pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0,0); if( pNewSrc==0 ) return WRC_Abort; *pNew = *p; p->pSrc = pNewSrc; p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ASTERISK, 0)); p->op = TK_SELECT; p->pWhere = 0; pNew->pGroupBy = 0; pNew->pHaving = 0; pNew->pOrderBy = 0; p->pPrior = 0; p->pNext = 0; p->pWith = 0; p->selFlags &= ~SF_Compound; assert( (p->selFlags & SF_Converted)==0 ); p->selFlags |= SF_Converted; assert( pNew->pPrior!=0 ); pNew->pPrior->pNext = pNew; pNew->pLimit = 0; return WRC_Continue; } /* ** Check to see if the FROM clause term pFrom has table-valued function ** arguments. If it does, leave an error message in pParse and return ** non-zero, since pFrom is not allowed to be a table-valued function. */ static int cannotBeFunction(Parse *pParse, struct SrcList_item *pFrom){ if( pFrom->fg.isTabFunc ){ sqlite3ErrorMsg(pParse, "'%s' is not a function", pFrom->zName); return 1; } return 0; } #ifndef SQLITE_OMIT_CTE /* ** Argument pWith (which may be NULL) points to a linked list of nested ** WITH contexts, from inner to outermost. If the table identified by ** FROM clause element pItem is really a common-table-expression (CTE) ** then return a pointer to the CTE definition for that table. Otherwise ** return NULL. ** ** If a non-NULL value is returned, set *ppContext to point to the With ** object that the returned CTE belongs to. */ static struct Cte *searchWith( With *pWith, /* Current innermost WITH clause */ struct SrcList_item *pItem, /* FROM clause element to resolve */ With **ppContext /* OUT: WITH clause return value belongs to */ ){ const char *zName; if( pItem->zDatabase==0 && (zName = pItem->zName)!=0 ){ With *p; for(p=pWith; p; p=p->pOuter){ int i; for(i=0; i<p->nCte; i++){ if( sqlite3StrICmp(zName, p->a[i].zName)==0 ){ *ppContext = p; return &p->a[i]; } } } } return 0; } /* The code generator maintains a stack of active WITH clauses ** with the inner-most WITH clause being at the top of the stack. ** ** This routine pushes the WITH clause passed as the second argument ** onto the top of the stack. If argument bFree is true, then this ** WITH clause will never be popped from the stack. In this case it ** should be freed along with the Parse object. In other cases, when ** bFree==0, the With object will be freed along with the SELECT ** statement with which it is associated. */ void sqlite3WithPush(Parse *pParse, With *pWith, u8 bFree){ assert( bFree==0 || (pParse->pWith==0 && pParse->pWithToFree==0) ); if( pWith ){ assert( pParse->pWith!=pWith ); pWith->pOuter = pParse->pWith; pParse->pWith = pWith; if( bFree ) pParse->pWithToFree = pWith; } } /* ** This function checks if argument pFrom refers to a CTE declared by ** a WITH clause on the stack currently maintained by the parser. And, ** if currently processing a CTE expression, if it is a recursive ** reference to the current CTE. ** ** If pFrom falls into either of the two categories above, pFrom->pTab ** and other fields are populated accordingly. The caller should check ** (pFrom->pTab!=0) to determine whether or not a successful match ** was found. ** ** Whether or not a match is found, SQLITE_OK is returned if no error ** occurs. If an error does occur, an error message is stored in the ** parser and some error code other than SQLITE_OK returned. */ static int withExpand( Walker *pWalker, struct SrcList_item *pFrom ){ Parse *pParse = pWalker->pParse; sqlite3 *db = pParse->db; struct Cte *pCte; /* Matched CTE (or NULL if no match) */ With *pWith; /* WITH clause that pCte belongs to */ assert( pFrom->pTab==0 ); if( pParse->nErr ){ return SQLITE_ERROR; } pCte = searchWith(pParse->pWith, pFrom, &pWith); if( pCte ){ Table *pTab; ExprList *pEList; Select *pSel; Select *pLeft; /* Left-most SELECT statement */ int bMayRecursive; /* True if compound joined by UNION [ALL] */ With *pSavedWith; /* Initial value of pParse->pWith */ /* If pCte->zCteErr is non-NULL at this point, then this is an illegal ** recursive reference to CTE pCte. Leave an error in pParse and return ** early. If pCte->zCteErr is NULL, then this is not a recursive reference. ** In this case, proceed. */ if( pCte->zCteErr ){ sqlite3ErrorMsg(pParse, pCte->zCteErr, pCte->zName); return SQLITE_ERROR; } if( cannotBeFunction(pParse, pFrom) ) return SQLITE_ERROR; assert( pFrom->pTab==0 ); pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table)); if( pTab==0 ) return WRC_Abort; pTab->nTabRef = 1; pTab->zName = sqlite3DbStrDup(db, pCte->zName); pTab->iPKey = -1; pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) ); pTab->tabFlags |= TF_Ephemeral | TF_NoVisibleRowid; pFrom->pSelect = sqlite3SelectDup(db, pCte->pSelect, 0); if( db->mallocFailed ) return SQLITE_NOMEM_BKPT; assert( pFrom->pSelect ); /* Check if this is a recursive CTE. */ pSel = pFrom->pSelect; bMayRecursive = ( pSel->op==TK_ALL || pSel->op==TK_UNION ); if( bMayRecursive ){ int i; SrcList *pSrc = pFrom->pSelect->pSrc; for(i=0; i<pSrc->nSrc; i++){ struct SrcList_item *pItem = &pSrc->a[i]; if( pItem->zDatabase==0 && pItem->zName!=0 && 0==sqlite3StrICmp(pItem->zName, pCte->zName) ){ pItem->pTab = pTab; pItem->fg.isRecursive = 1; pTab->nTabRef++; pSel->selFlags |= SF_Recursive; } } } /* Only one recursive reference is permitted. */ if( pTab->nTabRef>2 ){ sqlite3ErrorMsg( pParse, "multiple references to recursive table: %s", pCte->zName ); return SQLITE_ERROR; } assert( pTab->nTabRef==1 || ((pSel->selFlags&SF_Recursive) && pTab->nTabRef==2 )); pCte->zCteErr = "circular reference: %s"; pSavedWith = pParse->pWith; pParse->pWith = pWith; if( bMayRecursive ){ Select *pPrior = pSel->pPrior; assert( pPrior->pWith==0 ); pPrior->pWith = pSel->pWith; sqlite3WalkSelect(pWalker, pPrior); pPrior->pWith = 0; }else{ sqlite3WalkSelect(pWalker, pSel); } pParse->pWith = pWith; for(pLeft=pSel; pLeft->pPrior; pLeft=pLeft->pPrior); pEList = pLeft->pEList; if( pCte->pCols ){ if( pEList && pEList->nExpr!=pCte->pCols->nExpr ){ sqlite3ErrorMsg(pParse, "table %s has %d values for %d columns", pCte->zName, pEList->nExpr, pCte->pCols->nExpr ); pParse->pWith = pSavedWith; return SQLITE_ERROR; } pEList = pCte->pCols; } sqlite3ColumnsFromExprList(pParse, pEList, &pTab->nCol, &pTab->aCol); if( bMayRecursive ){ if( pSel->selFlags & SF_Recursive ){ pCte->zCteErr = "multiple recursive references: %s"; }else{ pCte->zCteErr = "recursive reference in a subquery: %s"; } sqlite3WalkSelect(pWalker, pSel); } pCte->zCteErr = 0; pParse->pWith = pSavedWith; } return SQLITE_OK; } #endif #ifndef SQLITE_OMIT_CTE /* ** If the SELECT passed as the second argument has an associated WITH ** clause, pop it from the stack stored as part of the Parse object. ** ** This function is used as the xSelectCallback2() callback by ** sqlite3SelectExpand() when walking a SELECT tree to resolve table ** names and other FROM clause elements. */ static void selectPopWith(Walker *pWalker, Select *p){ Parse *pParse = pWalker->pParse; if( OK_IF_ALWAYS_TRUE(pParse->pWith) && p->pPrior==0 ){ With *pWith = findRightmost(p)->pWith; if( pWith!=0 ){ assert( pParse->pWith==pWith ); pParse->pWith = pWith->pOuter; } } } #else #define selectPopWith 0 #endif /* ** The SrcList_item structure passed as the second argument represents a ** sub-query in the FROM clause of a SELECT statement. This function ** allocates and populates the SrcList_item.pTab object. If successful, ** SQLITE_OK is returned. Otherwise, if an OOM error is encountered, ** SQLITE_NOMEM. */ int sqlite3ExpandSubquery(Parse *pParse, struct SrcList_item *pFrom){ Select *pSel = pFrom->pSelect; Table *pTab; assert( pSel ); pFrom->pTab = pTab = sqlite3DbMallocZero(pParse->db, sizeof(Table)); if( pTab==0 ) return SQLITE_NOMEM; pTab->nTabRef = 1; if( pFrom->zAlias ){ pTab->zName = sqlite3DbStrDup(pParse->db, pFrom->zAlias); }else{ pTab->zName = sqlite3MPrintf(pParse->db, "subquery_%u", pSel->selId); } while( pSel->pPrior ){ pSel = pSel->pPrior; } sqlite3ColumnsFromExprList(pParse, pSel->pEList,&pTab->nCol,&pTab->aCol); pTab->iPKey = -1; pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) ); pTab->tabFlags |= TF_Ephemeral; return pParse->nErr ? SQLITE_ERROR : SQLITE_OK; } /* ** This routine is a Walker callback for "expanding" a SELECT statement. ** "Expanding" means to do the following: ** ** (1) Make sure VDBE cursor numbers have been assigned to every ** element of the FROM clause. ** ** (2) Fill in the pTabList->a[].pTab fields in the SrcList that ** defines FROM clause. When views appear in the FROM clause, ** fill pTabList->a[].pSelect with a copy of the SELECT statement ** that implements the view. A copy is made of the view's SELECT ** statement so that we can freely modify or delete that statement ** without worrying about messing up the persistent representation ** of the view. ** ** (3) Add terms to the WHERE clause to accommodate the NATURAL keyword ** on joins and the ON and USING clause of joins. ** ** (4) Scan the list of columns in the result set (pEList) looking ** for instances of the "*" operator or the TABLE.* operator. ** If found, expand each "*" to be every column in every table ** and TABLE.* to be every column in TABLE. ** */ static int selectExpander(Walker *pWalker, Select *p){ Parse *pParse = pWalker->pParse; int i, j, k; SrcList *pTabList; ExprList *pEList; struct SrcList_item *pFrom; sqlite3 *db = pParse->db; Expr *pE, *pRight, *pExpr; u16 selFlags = p->selFlags; u32 elistFlags = 0; p->selFlags |= SF_Expanded; if( db->mallocFailed ){ return WRC_Abort; } assert( p->pSrc!=0 ); if( (selFlags & SF_Expanded)!=0 ){ return WRC_Prune; } if( pWalker->eCode ){ /* Renumber selId because it has been copied from a view */ p->selId = ++pParse->nSelect; } pTabList = p->pSrc; pEList = p->pEList; sqlite3WithPush(pParse, p->pWith, 0); /* Make sure cursor numbers have been assigned to all entries in ** the FROM clause of the SELECT statement. */ sqlite3SrcListAssignCursors(pParse, pTabList); /* Look up every table named in the FROM clause of the select. If ** an entry of the FROM clause is a subquery instead of a table or view, ** then create a transient table structure to describe the subquery. */ for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){ Table *pTab; assert( pFrom->fg.isRecursive==0 || pFrom->pTab!=0 ); if( pFrom->fg.isRecursive ) continue; assert( pFrom->pTab==0 ); #ifndef SQLITE_OMIT_CTE if( withExpand(pWalker, pFrom) ) return WRC_Abort; if( pFrom->pTab ) {} else #endif if( pFrom->zName==0 ){ #ifndef SQLITE_OMIT_SUBQUERY Select *pSel = pFrom->pSelect; /* A sub-query in the FROM clause of a SELECT */ assert( pSel!=0 ); assert( pFrom->pTab==0 ); if( sqlite3WalkSelect(pWalker, pSel) ) return WRC_Abort; if( sqlite3ExpandSubquery(pParse, pFrom) ) return WRC_Abort; #endif }else{ /* An ordinary table or view name in the FROM clause */ assert( pFrom->pTab==0 ); pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom); if( pTab==0 ) return WRC_Abort; if( pTab->nTabRef>=0xffff ){ sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535", pTab->zName); pFrom->pTab = 0; return WRC_Abort; } pTab->nTabRef++; if( !IsVirtual(pTab) && cannotBeFunction(pParse, pFrom) ){ return WRC_Abort; } #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE) if( IsVirtual(pTab) || pTab->pSelect ){ i16 nCol; u8 eCodeOrig = pWalker->eCode; if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort; assert( pFrom->pSelect==0 ); if( pTab->pSelect && (db->flags & SQLITE_EnableView)==0 ){ sqlite3ErrorMsg(pParse, "access to view \"%s\" prohibited", pTab->zName); } pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0); nCol = pTab->nCol; pTab->nCol = -1; pWalker->eCode = 1; /* Turn on Select.selId renumbering */ sqlite3WalkSelect(pWalker, pFrom->pSelect); pWalker->eCode = eCodeOrig; pTab->nCol = nCol; } #endif } /* Locate the index named by the INDEXED BY clause, if any. */ if( sqlite3IndexedByLookup(pParse, pFrom) ){ return WRC_Abort; } } /* Process NATURAL keywords, and ON and USING clauses of joins. */ if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){ return WRC_Abort; } /* For every "*" that occurs in the column list, insert the names of ** all columns in all tables. And for every TABLE.* insert the names ** of all columns in TABLE. The parser inserted a special expression ** with the TK_ASTERISK operator for each "*" that it found in the column ** list. The following code just has to locate the TK_ASTERISK ** expressions and expand each one to the list of all columns in ** all tables. ** ** The first loop just checks to see if there are any "*" operators ** that need expanding. */ for(k=0; k<pEList->nExpr; k++){ pE = pEList->a[k].pExpr; if( pE->op==TK_ASTERISK ) break; assert( pE->op!=TK_DOT || pE->pRight!=0 ); assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) ); if( pE->op==TK_DOT && pE->pRight->op==TK_ASTERISK ) break; elistFlags |= pE->flags; } if( k<pEList->nExpr ){ /* ** If we get here it means the result set contains one or more "*" ** operators that need to be expanded. Loop through each expression ** in the result set and expand them one by one. */ struct ExprList_item *a = pEList->a; ExprList *pNew = 0; int flags = pParse->db->flags; int longNames = (flags & SQLITE_FullColNames)!=0 && (flags & SQLITE_ShortColNames)==0; for(k=0; k<pEList->nExpr; k++){ pE = a[k].pExpr; elistFlags |= pE->flags; pRight = pE->pRight; assert( pE->op!=TK_DOT || pRight!=0 ); if( pE->op!=TK_ASTERISK && (pE->op!=TK_DOT || pRight->op!=TK_ASTERISK) ){ /* This particular expression does not need to be expanded. */ pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr); if( pNew ){ pNew->a[pNew->nExpr-1].zName = a[k].zName; pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan; a[k].zName = 0; a[k].zSpan = 0; } a[k].pExpr = 0; }else{ /* This expression is a "*" or a "TABLE.*" and needs to be ** expanded. */ int tableSeen = 0; /* Set to 1 when TABLE matches */ char *zTName = 0; /* text of name of TABLE */ if( pE->op==TK_DOT ){ assert( pE->pLeft!=0 ); assert( !ExprHasProperty(pE->pLeft, EP_IntValue) ); zTName = pE->pLeft->u.zToken; } for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){ Table *pTab = pFrom->pTab; Select *pSub = pFrom->pSelect; char *zTabName = pFrom->zAlias; const char *zSchemaName = 0; int iDb; if( zTabName==0 ){ zTabName = pTab->zName; } if( db->mallocFailed ) break; if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){ pSub = 0; if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){ continue; } iDb = sqlite3SchemaToIndex(db, pTab->pSchema); zSchemaName = iDb>=0 ? db->aDb[iDb].zDbSName : "*"; } for(j=0; j<pTab->nCol; j++){ char *zName = pTab->aCol[j].zName; char *zColname; /* The computed column name */ char *zToFree; /* Malloced string that needs to be freed */ Token sColname; /* Computed column name as a token */ assert( zName ); if( zTName && pSub && sqlite3MatchSpanName(pSub->pEList->a[j].zSpan, 0, zTName, 0)==0 ){ continue; } /* If a column is marked as 'hidden', omit it from the expanded ** result-set list unless the SELECT has the SF_IncludeHidden ** bit set. */ if( (p->selFlags & SF_IncludeHidden)==0 && IsHiddenColumn(&pTab->aCol[j]) ){ continue; } tableSeen = 1; if( i>0 && zTName==0 ){ if( (pFrom->fg.jointype & JT_NATURAL)!=0 && tableAndColumnIndex(pTabList, i, zName, 0, 0) ){ /* In a NATURAL join, omit the join columns from the ** table to the right of the join */ continue; } if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){ /* In a join with a USING clause, omit columns in the ** using clause from the table on the right. */ continue; } } pRight = sqlite3Expr(db, TK_ID, zName); zColname = zName; zToFree = 0; if( longNames || pTabList->nSrc>1 ){ Expr *pLeft; pLeft = sqlite3Expr(db, TK_ID, zTabName); pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight); if( zSchemaName ){ pLeft = sqlite3Expr(db, TK_ID, zSchemaName); pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr); } if( longNames ){ zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName); zToFree = zColname; } }else{ pExpr = pRight; } pNew = sqlite3ExprListAppend(pParse, pNew, pExpr); sqlite3TokenInit(&sColname, zColname); sqlite3ExprListSetName(pParse, pNew, &sColname, 0); if( pNew && (p->selFlags & SF_NestedFrom)!=0 ){ struct ExprList_item *pX = &pNew->a[pNew->nExpr-1]; if( pSub ){ pX->zSpan = sqlite3DbStrDup(db, pSub->pEList->a[j].zSpan); testcase( pX->zSpan==0 ); }else{ pX->zSpan = sqlite3MPrintf(db, "%s.%s.%s", zSchemaName, zTabName, zColname); testcase( pX->zSpan==0 ); } pX->bSpanIsTab = 1; } sqlite3DbFree(db, zToFree); } } if( !tableSeen ){ if( zTName ){ sqlite3ErrorMsg(pParse, "no such table: %s", zTName); }else{ sqlite3ErrorMsg(pParse, "no tables specified"); } } } } sqlite3ExprListDelete(db, pEList); p->pEList = pNew; } if( p->pEList ){ if( p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){ sqlite3ErrorMsg(pParse, "too many columns in result set"); return WRC_Abort; } if( (elistFlags & (EP_HasFunc|EP_Subquery))!=0 ){ p->selFlags |= SF_ComplexResult; } } return WRC_Continue; } /* ** No-op routine for the parse-tree walker. ** ** When this routine is the Walker.xExprCallback then expression trees ** are walked without any actions being taken at each node. Presumably, ** when this routine is used for Walker.xExprCallback then ** Walker.xSelectCallback is set to do something useful for every ** subquery in the parser tree. */ int sqlite3ExprWalkNoop(Walker *NotUsed, Expr *NotUsed2){ UNUSED_PARAMETER2(NotUsed, NotUsed2); return WRC_Continue; } /* ** No-op routine for the parse-tree walker for SELECT statements. ** subquery in the parser tree. */ int sqlite3SelectWalkNoop(Walker *NotUsed, Select *NotUsed2){ UNUSED_PARAMETER2(NotUsed, NotUsed2); return WRC_Continue; } #if SQLITE_DEBUG /* ** Always assert. This xSelectCallback2 implementation proves that the ** xSelectCallback2 is never invoked. */ void sqlite3SelectWalkAssert2(Walker *NotUsed, Select *NotUsed2){ UNUSED_PARAMETER2(NotUsed, NotUsed2); assert( 0 ); } #endif /* ** This routine "expands" a SELECT statement and all of its subqueries. ** For additional information on what it means to "expand" a SELECT ** statement, see the comment on the selectExpand worker callback above. ** ** Expanding a SELECT statement is the first step in processing a ** SELECT statement. The SELECT statement must be expanded before ** name resolution is performed. ** ** If anything goes wrong, an error message is written into pParse. ** The calling function can detect the problem by looking at pParse->nErr ** and/or pParse->db->mallocFailed. */ static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){ Walker w; w.xExprCallback = sqlite3ExprWalkNoop; w.pParse = pParse; if( OK_IF_ALWAYS_TRUE(pParse->hasCompound) ){ w.xSelectCallback = convertCompoundSelectToSubquery; w.xSelectCallback2 = 0; sqlite3WalkSelect(&w, pSelect); } w.xSelectCallback = selectExpander; w.xSelectCallback2 = selectPopWith; w.eCode = 0; sqlite3WalkSelect(&w, pSelect); } #ifndef SQLITE_OMIT_SUBQUERY /* ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo() ** interface. ** ** For each FROM-clause subquery, add Column.zType and Column.zColl ** information to the Table structure that represents the result set ** of that subquery. ** ** The Table structure that represents the result set was constructed ** by selectExpander() but the type and collation information was omitted ** at that point because identifiers had not yet been resolved. This ** routine is called after identifier resolution. */ static void selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){ Parse *pParse; int i; SrcList *pTabList; struct SrcList_item *pFrom; assert( p->selFlags & SF_Resolved ); if( p->selFlags & SF_HasTypeInfo ) return; p->selFlags |= SF_HasTypeInfo; pParse = pWalker->pParse; pTabList = p->pSrc; for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){ Table *pTab = pFrom->pTab; assert( pTab!=0 ); if( (pTab->tabFlags & TF_Ephemeral)!=0 ){ /* A sub-query in the FROM clause of a SELECT */ Select *pSel = pFrom->pSelect; if( pSel ){ while( pSel->pPrior ) pSel = pSel->pPrior; sqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSel, SQLITE_AFF_NONE); } } } } #endif /* ** This routine adds datatype and collating sequence information to ** the Table structures of all FROM-clause subqueries in a ** SELECT statement. ** ** Use this routine after name resolution. */ static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){ #ifndef SQLITE_OMIT_SUBQUERY Walker w; w.xSelectCallback = sqlite3SelectWalkNoop; w.xSelectCallback2 = selectAddSubqueryTypeInfo; w.xExprCallback = sqlite3ExprWalkNoop; w.pParse = pParse; sqlite3WalkSelect(&w, pSelect); #endif } /* ** This routine sets up a SELECT statement for processing. The ** following is accomplished: ** ** * VDBE Cursor numbers are assigned to all FROM-clause terms. ** * Ephemeral Table objects are created for all FROM-clause subqueries. ** * ON and USING clauses are shifted into WHERE statements ** * Wildcards "*" and "TABLE.*" in result sets are expanded. ** * Identifiers in expression are matched to tables. ** ** This routine acts recursively on all subqueries within the SELECT. */ void sqlite3SelectPrep( Parse *pParse, /* The parser context */ Select *p, /* The SELECT statement being coded. */ NameContext *pOuterNC /* Name context for container */ ){ assert( p!=0 || pParse->db->mallocFailed ); if( pParse->db->mallocFailed ) return; if( p->selFlags & SF_HasTypeInfo ) return; sqlite3SelectExpand(pParse, p); if( pParse->nErr || pParse->db->mallocFailed ) return; sqlite3ResolveSelectNames(pParse, p, pOuterNC); if( pParse->nErr || pParse->db->mallocFailed ) return; sqlite3SelectAddTypeInfo(pParse, p); } /* ** Reset the aggregate accumulator. ** ** The aggregate accumulator is a set of memory cells that hold ** intermediate results while calculating an aggregate. This ** routine generates code that stores NULLs in all of those memory ** cells. */ static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){ Vdbe *v = pParse->pVdbe; int i; struct AggInfo_func *pFunc; int nReg = pAggInfo->nFunc + pAggInfo->nColumn; if( nReg==0 ) return; #ifdef SQLITE_DEBUG /* Verify that all AggInfo registers are within the range specified by ** AggInfo.mnReg..AggInfo.mxReg */ assert( nReg==pAggInfo->mxReg-pAggInfo->mnReg+1 ); for(i=0; i<pAggInfo->nColumn; i++){ assert( pAggInfo->aCol[i].iMem>=pAggInfo->mnReg && pAggInfo->aCol[i].iMem<=pAggInfo->mxReg ); } for(i=0; i<pAggInfo->nFunc; i++){ assert( pAggInfo->aFunc[i].iMem>=pAggInfo->mnReg && pAggInfo->aFunc[i].iMem<=pAggInfo->mxReg ); } #endif sqlite3VdbeAddOp3(v, OP_Null, 0, pAggInfo->mnReg, pAggInfo->mxReg); for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){ if( pFunc->iDistinct>=0 ){ Expr *pE = pFunc->pExpr; assert( !ExprHasProperty(pE, EP_xIsSelect) ); if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){ sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one " "argument"); pFunc->iDistinct = -1; }else{ KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pE->x.pList,0,0); sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0, (char*)pKeyInfo, P4_KEYINFO); } } } } /* ** Invoke the OP_AggFinalize opcode for every aggregate function ** in the AggInfo structure. */ static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){ Vdbe *v = pParse->pVdbe; int i; struct AggInfo_func *pF; for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){ ExprList *pList = pF->pExpr->x.pList; assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) ); sqlite3VdbeAddOp2(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0); sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF); } } /* ** Update the accumulator memory cells for an aggregate based on ** the current cursor position. ** ** If regAcc is non-zero and there are no min() or max() aggregates ** in pAggInfo, then only populate the pAggInfo->nAccumulator accumulator ** registers if register regAcc contains 0. The caller will take care ** of setting and clearing regAcc. */ static void updateAccumulator(Parse *pParse, int regAcc, AggInfo *pAggInfo){ Vdbe *v = pParse->pVdbe; int i; int regHit = 0; int addrHitTest = 0; struct AggInfo_func *pF; struct AggInfo_col *pC; pAggInfo->directMode = 1; for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){ int nArg; int addrNext = 0; int regAgg; ExprList *pList = pF->pExpr->x.pList; assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) ); assert( !IsWindowFunc(pF->pExpr) ); if( ExprHasProperty(pF->pExpr, EP_WinFunc) ){ Expr *pFilter = pF->pExpr->y.pWin->pFilter; if( pAggInfo->nAccumulator && (pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL) ){ if( regHit==0 ) regHit = ++pParse->nMem; /* If this is the first row of the group (regAcc==0), clear the ** "magnet" register regHit so that the accumulator registers ** are populated if the FILTER clause jumps over the the ** invocation of min() or max() altogether. Or, if this is not ** the first row (regAcc==1), set the magnet register so that the ** accumulators are not populated unless the min()/max() is invoked and ** indicates that they should be. */ sqlite3VdbeAddOp2(v, OP_Copy, regAcc, regHit); } addrNext = sqlite3VdbeMakeLabel(pParse); sqlite3ExprIfFalse(pParse, pFilter, addrNext, SQLITE_JUMPIFNULL); } if( pList ){ nArg = pList->nExpr; regAgg = sqlite3GetTempRange(pParse, nArg); sqlite3ExprCodeExprList(pParse, pList, regAgg, 0, SQLITE_ECEL_DUP); }else{ nArg = 0; regAgg = 0; } if( pF->iDistinct>=0 ){ if( addrNext==0 ){ addrNext = sqlite3VdbeMakeLabel(pParse); } testcase( nArg==0 ); /* Error condition */ testcase( nArg>1 ); /* Also an error */ codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg); } if( pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){ CollSeq *pColl = 0; struct ExprList_item *pItem; int j; assert( pList!=0 ); /* pList!=0 if pF->pFunc has NEEDCOLL */ for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){ pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr); } if( !pColl ){ pColl = pParse->db->pDfltColl; } if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem; sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ); } sqlite3VdbeAddOp3(v, OP_AggStep, 0, regAgg, pF->iMem); sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF); sqlite3VdbeChangeP5(v, (u8)nArg); sqlite3ReleaseTempRange(pParse, regAgg, nArg); if( addrNext ){ sqlite3VdbeResolveLabel(v, addrNext); } } if( regHit==0 && pAggInfo->nAccumulator ){ regHit = regAcc; } if( regHit ){ addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit); VdbeCoverage(v); } for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){ sqlite3ExprCode(pParse, pC->pExpr, pC->iMem); } pAggInfo->directMode = 0; if( addrHitTest ){ sqlite3VdbeJumpHere(v, addrHitTest); } } /* ** Add a single OP_Explain instruction to the VDBE to explain a simple ** count(*) query ("SELECT count(*) FROM pTab"). */ #ifndef SQLITE_OMIT_EXPLAIN static void explainSimpleCount( Parse *pParse, /* Parse context */ Table *pTab, /* Table being queried */ Index *pIdx /* Index used to optimize scan, or NULL */ ){ if( pParse->explain==2 ){ int bCover = (pIdx!=0 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pIdx))); sqlite3VdbeExplain(pParse, 0, "SCAN TABLE %s%s%s", pTab->zName, bCover ? " USING COVERING INDEX " : "", bCover ? pIdx->zName : "" ); } } #else # define explainSimpleCount(a,b,c) #endif /* ** sqlite3WalkExpr() callback used by havingToWhere(). ** ** If the node passed to the callback is a TK_AND node, return ** WRC_Continue to tell sqlite3WalkExpr() to iterate through child nodes. ** ** Otherwise, return WRC_Prune. In this case, also check if the ** sub-expression matches the criteria for being moved to the WHERE ** clause. If so, add it to the WHERE clause and replace the sub-expression ** within the HAVING expression with a constant "1". */ static int havingToWhereExprCb(Walker *pWalker, Expr *pExpr){ if( pExpr->op!=TK_AND ){ Select *pS = pWalker->u.pSelect; if( sqlite3ExprIsConstantOrGroupBy(pWalker->pParse, pExpr, pS->pGroupBy) ){ sqlite3 *db = pWalker->pParse->db; Expr *pNew = sqlite3Expr(db, TK_INTEGER, "1"); if( pNew ){ Expr *pWhere = pS->pWhere; SWAP(Expr, *pNew, *pExpr); pNew = sqlite3ExprAnd(pWalker->pParse, pWhere, pNew); pS->pWhere = pNew; pWalker->eCode = 1; } } return WRC_Prune; } return WRC_Continue; } /* ** Transfer eligible terms from the HAVING clause of a query, which is ** processed after grouping, to the WHERE clause, which is processed before ** grouping. For example, the query: ** ** SELECT * FROM <tables> WHERE a=? GROUP BY b HAVING b=? AND c=? ** ** can be rewritten as: ** ** SELECT * FROM <tables> WHERE a=? AND b=? GROUP BY b HAVING c=? ** ** A term of the HAVING expression is eligible for transfer if it consists ** entirely of constants and expressions that are also GROUP BY terms that ** use the "BINARY" collation sequence. */ static void havingToWhere(Parse *pParse, Select *p){ Walker sWalker; memset(&sWalker, 0, sizeof(sWalker)); sWalker.pParse = pParse; sWalker.xExprCallback = havingToWhereExprCb; sWalker.u.pSelect = p; sqlite3WalkExpr(&sWalker, p->pHaving); #if SELECTTRACE_ENABLED if( sWalker.eCode && (sqlite3SelectTrace & 0x100)!=0 ){ SELECTTRACE(0x100,pParse,p,("Move HAVING terms into WHERE:\n")); sqlite3TreeViewSelect(0, p, 0); } #endif } /* ** Check to see if the pThis entry of pTabList is a self-join of a prior view. ** If it is, then return the SrcList_item for the prior view. If it is not, ** then return 0. */ static struct SrcList_item *isSelfJoinView( SrcList *pTabList, /* Search for self-joins in this FROM clause */ struct SrcList_item *pThis /* Search for prior reference to this subquery */ ){ struct SrcList_item *pItem; for(pItem = pTabList->a; pItem<pThis; pItem++){ Select *pS1; if( pItem->pSelect==0 ) continue; if( pItem->fg.viaCoroutine ) continue; if( pItem->zName==0 ) continue; assert( pItem->pTab!=0 ); assert( pThis->pTab!=0 ); if( pItem->pTab->pSchema!=pThis->pTab->pSchema ) continue; if( sqlite3_stricmp(pItem->zName, pThis->zName)!=0 ) continue; pS1 = pItem->pSelect; if( pItem->pTab->pSchema==0 && pThis->pSelect->selId!=pS1->selId ){ /* The query flattener left two different CTE tables with identical ** names in the same FROM clause. */ continue; } if( sqlite3ExprCompare(0, pThis->pSelect->pWhere, pS1->pWhere, -1) || sqlite3ExprCompare(0, pThis->pSelect->pHaving, pS1->pHaving, -1) ){ /* The view was modified by some other optimization such as ** pushDownWhereTerms() */ continue; } return pItem; } return 0; } #ifdef SQLITE_COUNTOFVIEW_OPTIMIZATION /* ** Attempt to transform a query of the form ** ** SELECT count(*) FROM (SELECT x FROM t1 UNION ALL SELECT y FROM t2) ** ** Into this: ** ** SELECT (SELECT count(*) FROM t1)+(SELECT count(*) FROM t2) ** ** The transformation only works if all of the following are true: ** ** * The subquery is a UNION ALL of two or more terms ** * The subquery does not have a LIMIT clause ** * There is no WHERE or GROUP BY or HAVING clauses on the subqueries ** * The outer query is a simple count(*) with no WHERE clause or other ** extraneous syntax. ** ** Return TRUE if the optimization is undertaken. */ static int countOfViewOptimization(Parse *pParse, Select *p){ Select *pSub, *pPrior; Expr *pExpr; Expr *pCount; sqlite3 *db; if( (p->selFlags & SF_Aggregate)==0 ) return 0; /* This is an aggregate */ if( p->pEList->nExpr!=1 ) return 0; /* Single result column */ if( p->pWhere ) return 0; if( p->pGroupBy ) return 0; pExpr = p->pEList->a[0].pExpr; if( pExpr->op!=TK_AGG_FUNCTION ) return 0; /* Result is an aggregate */ if( sqlite3_stricmp(pExpr->u.zToken,"count") ) return 0; /* Is count() */ if( pExpr->x.pList!=0 ) return 0; /* Must be count(*) */ if( p->pSrc->nSrc!=1 ) return 0; /* One table in FROM */ pSub = p->pSrc->a[0].pSelect; if( pSub==0 ) return 0; /* The FROM is a subquery */ if( pSub->pPrior==0 ) return 0; /* Must be a compound ry */ do{ if( pSub->op!=TK_ALL && pSub->pPrior ) return 0; /* Must be UNION ALL */ if( pSub->pWhere ) return 0; /* No WHERE clause */ if( pSub->pLimit ) return 0; /* No LIMIT clause */ if( pSub->selFlags & SF_Aggregate ) return 0; /* Not an aggregate */ pSub = pSub->pPrior; /* Repeat over compound */ }while( pSub ); /* If we reach this point then it is OK to perform the transformation */ db = pParse->db; pCount = pExpr; pExpr = 0; pSub = p->pSrc->a[0].pSelect; p->pSrc->a[0].pSelect = 0; sqlite3SrcListDelete(db, p->pSrc); p->pSrc = sqlite3DbMallocZero(pParse->db, sizeof(*p->pSrc)); while( pSub ){ Expr *pTerm; pPrior = pSub->pPrior; pSub->pPrior = 0; pSub->pNext = 0; pSub->selFlags |= SF_Aggregate; pSub->selFlags &= ~SF_Compound; pSub->nSelectRow = 0; sqlite3ExprListDelete(db, pSub->pEList); pTerm = pPrior ? sqlite3ExprDup(db, pCount, 0) : pCount; pSub->pEList = sqlite3ExprListAppend(pParse, 0, pTerm); pTerm = sqlite3PExpr(pParse, TK_SELECT, 0, 0); sqlite3PExprAddSelect(pParse, pTerm, pSub); if( pExpr==0 ){ pExpr = pTerm; }else{ pExpr = sqlite3PExpr(pParse, TK_PLUS, pTerm, pExpr); } pSub = pPrior; } p->pEList->a[0].pExpr = pExpr; p->selFlags &= ~SF_Aggregate; #if SELECTTRACE_ENABLED if( sqlite3SelectTrace & 0x400 ){ SELECTTRACE(0x400,pParse,p,("After count-of-view optimization:\n")); sqlite3TreeViewSelect(0, p, 0); } #endif return 1; } #endif /* SQLITE_COUNTOFVIEW_OPTIMIZATION */ /* ** Generate code for the SELECT statement given in the p argument. ** ** The results are returned according to the SelectDest structure. ** See comments in sqliteInt.h for further information. ** ** This routine returns the number of errors. If any errors are ** encountered, then an appropriate error message is left in ** pParse->zErrMsg. ** ** This routine does NOT free the Select structure passed in. The ** calling function needs to do that. */ int sqlite3Select( Parse *pParse, /* The parser context */ Select *p, /* The SELECT statement being coded. */ SelectDest *pDest /* What to do with the query results */ ){ int i, j; /* Loop counters */ WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */ Vdbe *v; /* The virtual machine under construction */ int isAgg; /* True for select lists like "count(*)" */ ExprList *pEList = 0; /* List of columns to extract. */ SrcList *pTabList; /* List of tables to select from */ Expr *pWhere; /* The WHERE clause. May be NULL */ ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */ Expr *pHaving; /* The HAVING clause. May be NULL */ int rc = 1; /* Value to return from this function */ DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */ SortCtx sSort; /* Info on how to code the ORDER BY clause */ AggInfo sAggInfo; /* Information used by aggregate queries */ int iEnd; /* Address of the end of the query */ sqlite3 *db; /* The database connection */ ExprList *pMinMaxOrderBy = 0; /* Added ORDER BY for min/max queries */ u8 minMaxFlag; /* Flag for min/max queries */ db = pParse->db; v = sqlite3GetVdbe(pParse); if( p==0 || db->mallocFailed || pParse->nErr ){ return 1; } if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1; memset(&sAggInfo, 0, sizeof(sAggInfo)); #if SELECTTRACE_ENABLED SELECTTRACE(1,pParse,p, ("begin processing:\n", pParse->addrExplain)); if( sqlite3SelectTrace & 0x100 ){ sqlite3TreeViewSelect(0, p, 0); } #endif assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistFifo ); assert( p->pOrderBy==0 || pDest->eDest!=SRT_Fifo ); assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistQueue ); assert( p->pOrderBy==0 || pDest->eDest!=SRT_Queue ); if( IgnorableOrderby(pDest) ){ assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union || pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard || pDest->eDest==SRT_Queue || pDest->eDest==SRT_DistFifo || pDest->eDest==SRT_DistQueue || pDest->eDest==SRT_Fifo); /* If ORDER BY makes no difference in the output then neither does ** DISTINCT so it can be removed too. */ sqlite3ExprListDelete(db, p->pOrderBy); p->pOrderBy = 0; p->selFlags &= ~SF_Distinct; } sqlite3SelectPrep(pParse, p, 0); if( pParse->nErr || db->mallocFailed ){ goto select_end; } assert( p->pEList!=0 ); #if SELECTTRACE_ENABLED if( sqlite3SelectTrace & 0x104 ){ SELECTTRACE(0x104,pParse,p, ("after name resolution:\n")); sqlite3TreeViewSelect(0, p, 0); } #endif if( pDest->eDest==SRT_Output ){ generateColumnNames(pParse, p); } #ifndef SQLITE_OMIT_WINDOWFUNC if( sqlite3WindowRewrite(pParse, p) ){ goto select_end; } #if SELECTTRACE_ENABLED if( p->pWin && (sqlite3SelectTrace & 0x108)!=0 ){ SELECTTRACE(0x104,pParse,p, ("after window rewrite:\n")); sqlite3TreeViewSelect(0, p, 0); } #endif #endif /* SQLITE_OMIT_WINDOWFUNC */ pTabList = p->pSrc; isAgg = (p->selFlags & SF_Aggregate)!=0; memset(&sSort, 0, sizeof(sSort)); sSort.pOrderBy = p->pOrderBy; /* Try to various optimizations (flattening subqueries, and strength ** reduction of join operators) in the FROM clause up into the main query */ #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) for(i=0; !p->pPrior && i<pTabList->nSrc; i++){ struct SrcList_item *pItem = &pTabList->a[i]; Select *pSub = pItem->pSelect; Table *pTab = pItem->pTab; /* Convert LEFT JOIN into JOIN if there are terms of the right table ** of the LEFT JOIN used in the WHERE clause. */ if( (pItem->fg.jointype & JT_LEFT)!=0 && sqlite3ExprImpliesNonNullRow(p->pWhere, pItem->iCursor) && OptimizationEnabled(db, SQLITE_SimplifyJoin) ){ SELECTTRACE(0x100,pParse,p, ("LEFT-JOIN simplifies to JOIN on term %d\n",i)); pItem->fg.jointype &= ~(JT_LEFT|JT_OUTER); unsetJoinExpr(p->pWhere, pItem->iCursor); } /* No futher action if this term of the FROM clause is no a subquery */ if( pSub==0 ) continue; /* Catch mismatch in the declared columns of a view and the number of ** columns in the SELECT on the RHS */ if( pTab->nCol!=pSub->pEList->nExpr ){ sqlite3ErrorMsg(pParse, "expected %d columns for '%s' but got %d", pTab->nCol, pTab->zName, pSub->pEList->nExpr); goto select_end; } /* Do not try to flatten an aggregate subquery. ** ** Flattening an aggregate subquery is only possible if the outer query ** is not a join. But if the outer query is not a join, then the subquery ** will be implemented as a co-routine and there is no advantage to ** flattening in that case. */ if( (pSub->selFlags & SF_Aggregate)!=0 ) continue; assert( pSub->pGroupBy==0 ); /* If the outer query contains a "complex" result set (that is, ** if the result set of the outer query uses functions or subqueries) ** and if the subquery contains an ORDER BY clause and if ** it will be implemented as a co-routine, then do not flatten. This ** restriction allows SQL constructs like this: ** ** SELECT expensive_function(x) ** FROM (SELECT x FROM tab ORDER BY y LIMIT 10); ** ** The expensive_function() is only computed on the 10 rows that ** are output, rather than every row of the table. ** ** The requirement that the outer query have a complex result set ** means that flattening does occur on simpler SQL constraints without ** the expensive_function() like: ** ** SELECT x FROM (SELECT x FROM tab ORDER BY y LIMIT 10); */ if( pSub->pOrderBy!=0 && i==0 && (p->selFlags & SF_ComplexResult)!=0 && (pTabList->nSrc==1 || (pTabList->a[1].fg.jointype&(JT_LEFT|JT_CROSS))!=0) ){ continue; } if( flattenSubquery(pParse, p, i, isAgg) ){ if( pParse->nErr ) goto select_end; /* This subquery can be absorbed into its parent. */ i = -1; } pTabList = p->pSrc; if( db->mallocFailed ) goto select_end; if( !IgnorableOrderby(pDest) ){ sSort.pOrderBy = p->pOrderBy; } } #endif #ifndef SQLITE_OMIT_COMPOUND_SELECT /* Handle compound SELECT statements using the separate multiSelect() ** procedure. */ if( p->pPrior ){ rc = multiSelect(pParse, p, pDest); #if SELECTTRACE_ENABLED SELECTTRACE(0x1,pParse,p,("end compound-select processing\n")); if( (sqlite3SelectTrace & 0x2000)!=0 && ExplainQueryPlanParent(pParse)==0 ){ sqlite3TreeViewSelect(0, p, 0); } #endif if( p->pNext==0 ) ExplainQueryPlanPop(pParse); return rc; } #endif /* Do the WHERE-clause constant propagation optimization if this is ** a join. No need to speed time on this operation for non-join queries ** as the equivalent optimization will be handled by query planner in ** sqlite3WhereBegin(). */ if( pTabList->nSrc>1 && OptimizationEnabled(db, SQLITE_PropagateConst) && propagateConstants(pParse, p) ){ #if SELECTTRACE_ENABLED if( sqlite3SelectTrace & 0x100 ){ SELECTTRACE(0x100,pParse,p,("After constant propagation:\n")); sqlite3TreeViewSelect(0, p, 0); } #endif }else{ SELECTTRACE(0x100,pParse,p,("Constant propagation not helpful\n")); } #ifdef SQLITE_COUNTOFVIEW_OPTIMIZATION if( OptimizationEnabled(db, SQLITE_QueryFlattener|SQLITE_CountOfView) && countOfViewOptimization(pParse, p) ){ if( db->mallocFailed ) goto select_end; pEList = p->pEList; pTabList = p->pSrc; } #endif /* For each term in the FROM clause, do two things: ** (1) Authorized unreferenced tables ** (2) Generate code for all sub-queries */ for(i=0; i<pTabList->nSrc; i++){ struct SrcList_item *pItem = &pTabList->a[i]; SelectDest dest; Select *pSub; #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) const char *zSavedAuthContext; #endif /* Issue SQLITE_READ authorizations with a fake column name for any ** tables that are referenced but from which no values are extracted. ** Examples of where these kinds of null SQLITE_READ authorizations ** would occur: ** ** SELECT count(*) FROM t1; -- SQLITE_READ t1."" ** SELECT t1.* FROM t1, t2; -- SQLITE_READ t2."" ** ** The fake column name is an empty string. It is possible for a table to ** have a column named by the empty string, in which case there is no way to ** distinguish between an unreferenced table and an actual reference to the ** "" column. The original design was for the fake column name to be a NULL, ** which would be unambiguous. But legacy authorization callbacks might ** assume the column name is non-NULL and segfault. The use of an empty ** string for the fake column name seems safer. */ if( pItem->colUsed==0 && pItem->zName!=0 ){ sqlite3AuthCheck(pParse, SQLITE_READ, pItem->zName, "", pItem->zDatabase); } #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) /* Generate code for all sub-queries in the FROM clause */ pSub = pItem->pSelect; if( pSub==0 ) continue; /* The code for a subquery should only be generated once, though it is ** technically harmless for it to be generated multiple times. The ** following assert() will detect if something changes to cause ** the same subquery to be coded multiple times, as a signal to the ** developers to try to optimize the situation. ** ** Update 2019-07-24: ** See ticket https://sqlite.org/src/tktview/c52b09c7f38903b1311cec40. ** The dbsqlfuzz fuzzer found a case where the same subquery gets ** coded twice. So this assert() now becomes a testcase(). It should ** be very rare, though. */ testcase( pItem->addrFillSub!=0 ); /* Increment Parse.nHeight by the height of the largest expression ** tree referred to by this, the parent select. The child select ** may contain expression trees of at most ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit ** more conservative than necessary, but much easier than enforcing ** an exact limit. */ pParse->nHeight += sqlite3SelectExprHeight(p); /* Make copies of constant WHERE-clause terms in the outer query down ** inside the subquery. This can help the subquery to run more efficiently. */ if( OptimizationEnabled(db, SQLITE_PushDown) && pushDownWhereTerms(pParse, pSub, p->pWhere, pItem->iCursor, (pItem->fg.jointype & JT_OUTER)!=0) ){ #if SELECTTRACE_ENABLED if( sqlite3SelectTrace & 0x100 ){ SELECTTRACE(0x100,pParse,p, ("After WHERE-clause push-down into subquery %d:\n", pSub->selId)); sqlite3TreeViewSelect(0, p, 0); } #endif }else{ SELECTTRACE(0x100,pParse,p,("Push-down not possible\n")); } zSavedAuthContext = pParse->zAuthContext; pParse->zAuthContext = pItem->zName; /* Generate code to implement the subquery ** ** The subquery is implemented as a co-routine if the subquery is ** guaranteed to be the outer loop (so that it does not need to be ** computed more than once) ** ** TODO: Are there other reasons beside (1) to use a co-routine ** implementation? */ if( i==0 && (pTabList->nSrc==1 || (pTabList->a[1].fg.jointype&(JT_LEFT|JT_CROSS))!=0) /* (1) */ ){ /* Implement a co-routine that will return a single row of the result ** set on each invocation. */ int addrTop = sqlite3VdbeCurrentAddr(v)+1; pItem->regReturn = ++pParse->nMem; sqlite3VdbeAddOp3(v, OP_InitCoroutine, pItem->regReturn, 0, addrTop); VdbeComment((v, "%s", pItem->pTab->zName)); pItem->addrFillSub = addrTop; sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn); ExplainQueryPlan((pParse, 1, "CO-ROUTINE %u", pSub->selId)); sqlite3Select(pParse, pSub, &dest); pItem->pTab->nRowLogEst = pSub->nSelectRow; pItem->fg.viaCoroutine = 1; pItem->regResult = dest.iSdst; sqlite3VdbeEndCoroutine(v, pItem->regReturn); sqlite3VdbeJumpHere(v, addrTop-1); sqlite3ClearTempRegCache(pParse); }else{ /* Generate a subroutine that will fill an ephemeral table with ** the content of this subquery. pItem->addrFillSub will point ** to the address of the generated subroutine. pItem->regReturn ** is a register allocated to hold the subroutine return address */ int topAddr; int onceAddr = 0; int retAddr; struct SrcList_item *pPrior; testcase( pItem->addrFillSub==0 ); /* Ticket c52b09c7f38903b1311 */ pItem->regReturn = ++pParse->nMem; topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn); pItem->addrFillSub = topAddr+1; if( pItem->fg.isCorrelated==0 ){ /* If the subquery is not correlated and if we are not inside of ** a trigger, then we only need to compute the value of the subquery ** once. */ onceAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v); VdbeComment((v, "materialize \"%s\"", pItem->pTab->zName)); }else{ VdbeNoopComment((v, "materialize \"%s\"", pItem->pTab->zName)); } pPrior = isSelfJoinView(pTabList, pItem); if( pPrior ){ sqlite3VdbeAddOp2(v, OP_OpenDup, pItem->iCursor, pPrior->iCursor); assert( pPrior->pSelect!=0 ); pSub->nSelectRow = pPrior->pSelect->nSelectRow; }else{ sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor); ExplainQueryPlan((pParse, 1, "MATERIALIZE %u", pSub->selId)); sqlite3Select(pParse, pSub, &dest); } pItem->pTab->nRowLogEst = pSub->nSelectRow; if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr); retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn); VdbeComment((v, "end %s", pItem->pTab->zName)); sqlite3VdbeChangeP1(v, topAddr, retAddr); sqlite3ClearTempRegCache(pParse); } if( db->mallocFailed ) goto select_end; pParse->nHeight -= sqlite3SelectExprHeight(p); pParse->zAuthContext = zSavedAuthContext; #endif } /* Various elements of the SELECT copied into local variables for ** convenience */ pEList = p->pEList; pWhere = p->pWhere; pGroupBy = p->pGroupBy; pHaving = p->pHaving; sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0; #if SELECTTRACE_ENABLED if( sqlite3SelectTrace & 0x400 ){ SELECTTRACE(0x400,pParse,p,("After all FROM-clause analysis:\n")); sqlite3TreeViewSelect(0, p, 0); } #endif /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and ** if the select-list is the same as the ORDER BY list, then this query ** can be rewritten as a GROUP BY. In other words, this: ** ** SELECT DISTINCT xyz FROM ... ORDER BY xyz ** ** is transformed to: ** ** SELECT xyz FROM ... GROUP BY xyz ORDER BY xyz ** ** The second form is preferred as a single index (or temp-table) may be ** used for both the ORDER BY and DISTINCT processing. As originally ** written the query must use a temp-table for at least one of the ORDER ** BY and DISTINCT, and an index or separate temp-table for the other. */ if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct && sqlite3ExprListCompare(sSort.pOrderBy, pEList, -1)==0 && p->pWin==0 ){ p->selFlags &= ~SF_Distinct; pGroupBy = p->pGroupBy = sqlite3ExprListDup(db, pEList, 0); /* Notice that even thought SF_Distinct has been cleared from p->selFlags, ** the sDistinct.isTnct is still set. Hence, isTnct represents the ** original setting of the SF_Distinct flag, not the current setting */ assert( sDistinct.isTnct ); #if SELECTTRACE_ENABLED if( sqlite3SelectTrace & 0x400 ){ SELECTTRACE(0x400,pParse,p,("Transform DISTINCT into GROUP BY:\n")); sqlite3TreeViewSelect(0, p, 0); } #endif } /* If there is an ORDER BY clause, then create an ephemeral index to ** do the sorting. But this sorting ephemeral index might end up ** being unused if the data can be extracted in pre-sorted order. ** If that is the case, then the OP_OpenEphemeral instruction will be ** changed to an OP_Noop once we figure out that the sorting index is ** not needed. The sSort.addrSortIndex variable is used to facilitate ** that change. */ if( sSort.pOrderBy ){ KeyInfo *pKeyInfo; pKeyInfo = sqlite3KeyInfoFromExprList( pParse, sSort.pOrderBy, 0, pEList->nExpr); sSort.iECursor = pParse->nTab++; sSort.addrSortIndex = sqlite3VdbeAddOp4(v, OP_OpenEphemeral, sSort.iECursor, sSort.pOrderBy->nExpr+1+pEList->nExpr, 0, (char*)pKeyInfo, P4_KEYINFO ); }else{ sSort.addrSortIndex = -1; } /* If the output is destined for a temporary table, open that table. */ if( pDest->eDest==SRT_EphemTab ){ sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr); } /* Set the limiter. */ iEnd = sqlite3VdbeMakeLabel(pParse); if( (p->selFlags & SF_FixedLimit)==0 ){ p->nSelectRow = 320; /* 4 billion rows */ } computeLimitRegisters(pParse, p, iEnd); if( p->iLimit==0 && sSort.addrSortIndex>=0 ){ sqlite3VdbeChangeOpcode(v, sSort.addrSortIndex, OP_SorterOpen); sSort.sortFlags |= SORTFLAG_UseSorter; } /* Open an ephemeral index to use for the distinct set. */ if( p->selFlags & SF_Distinct ){ sDistinct.tabTnct = pParse->nTab++; sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral, sDistinct.tabTnct, 0, 0, (char*)sqlite3KeyInfoFromExprList(pParse, p->pEList,0,0), P4_KEYINFO); sqlite3VdbeChangeP5(v, BTREE_UNORDERED); sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED; }else{ sDistinct.eTnctType = WHERE_DISTINCT_NOOP; } if( !isAgg && pGroupBy==0 ){ /* No aggregate functions and no GROUP BY clause */ u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0) | (p->selFlags & SF_FixedLimit); #ifndef SQLITE_OMIT_WINDOWFUNC Window *pWin = p->pWin; /* Master window object (or NULL) */ if( pWin ){ sqlite3WindowCodeInit(pParse, pWin); } #endif assert( WHERE_USE_LIMIT==SF_FixedLimit ); /* Begin the database scan. */ SELECTTRACE(1,pParse,p,("WhereBegin\n")); pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, sSort.pOrderBy, p->pEList, wctrlFlags, p->nSelectRow); if( pWInfo==0 ) goto select_end; if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){ p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo); } if( sDistinct.isTnct && sqlite3WhereIsDistinct(pWInfo) ){ sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo); } if( sSort.pOrderBy ){ sSort.nOBSat = sqlite3WhereIsOrdered(pWInfo); sSort.labelOBLopt = sqlite3WhereOrderByLimitOptLabel(pWInfo); if( sSort.nOBSat==sSort.pOrderBy->nExpr ){ sSort.pOrderBy = 0; } } /* If sorting index that was created by a prior OP_OpenEphemeral ** instruction ended up not being needed, then change the OP_OpenEphemeral ** into an OP_Noop. */ if( sSort.addrSortIndex>=0 && sSort.pOrderBy==0 ){ sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex); } assert( p->pEList==pEList ); #ifndef SQLITE_OMIT_WINDOWFUNC if( pWin ){ int addrGosub = sqlite3VdbeMakeLabel(pParse); int iCont = sqlite3VdbeMakeLabel(pParse); int iBreak = sqlite3VdbeMakeLabel(pParse); int regGosub = ++pParse->nMem; sqlite3WindowCodeStep(pParse, p, pWInfo, regGosub, addrGosub); sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak); sqlite3VdbeResolveLabel(v, addrGosub); VdbeNoopComment((v, "inner-loop subroutine")); sSort.labelOBLopt = 0; selectInnerLoop(pParse, p, -1, &sSort, &sDistinct, pDest, iCont, iBreak); sqlite3VdbeResolveLabel(v, iCont); sqlite3VdbeAddOp1(v, OP_Return, regGosub); VdbeComment((v, "end inner-loop subroutine")); sqlite3VdbeResolveLabel(v, iBreak); }else #endif /* SQLITE_OMIT_WINDOWFUNC */ { /* Use the standard inner loop. */ selectInnerLoop(pParse, p, -1, &sSort, &sDistinct, pDest, sqlite3WhereContinueLabel(pWInfo), sqlite3WhereBreakLabel(pWInfo)); /* End the database scan loop. */ sqlite3WhereEnd(pWInfo); } }else{ /* This case when there exist aggregate functions or a GROUP BY clause ** or both */ NameContext sNC; /* Name context for processing aggregate information */ int iAMem; /* First Mem address for storing current GROUP BY */ int iBMem; /* First Mem address for previous GROUP BY */ int iUseFlag; /* Mem address holding flag indicating that at least ** one row of the input to the aggregator has been ** processed */ int iAbortFlag; /* Mem address which causes query abort if positive */ int groupBySort; /* Rows come from source in GROUP BY order */ int addrEnd; /* End of processing for this SELECT */ int sortPTab = 0; /* Pseudotable used to decode sorting results */ int sortOut = 0; /* Output register from the sorter */ int orderByGrp = 0; /* True if the GROUP BY and ORDER BY are the same */ /* Remove any and all aliases between the result set and the ** GROUP BY clause. */ if( pGroupBy ){ int k; /* Loop counter */ struct ExprList_item *pItem; /* For looping over expression in a list */ for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){ pItem->u.x.iAlias = 0; } for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){ pItem->u.x.iAlias = 0; } assert( 66==sqlite3LogEst(100) ); if( p->nSelectRow>66 ) p->nSelectRow = 66; /* If there is both a GROUP BY and an ORDER BY clause and they are ** identical, then it may be possible to disable the ORDER BY clause ** on the grounds that the GROUP BY will cause elements to come out ** in the correct order. It also may not - the GROUP BY might use a ** database index that causes rows to be grouped together as required ** but not actually sorted. Either way, record the fact that the ** ORDER BY and GROUP BY clauses are the same by setting the orderByGrp ** variable. */ if( sSort.pOrderBy && pGroupBy->nExpr==sSort.pOrderBy->nExpr ){ int ii; /* The GROUP BY processing doesn't care whether rows are delivered in ** ASC or DESC order - only that each group is returned contiguously. ** So set the ASC/DESC flags in the GROUP BY to match those in the ** ORDER BY to maximize the chances of rows being delivered in an ** order that makes the ORDER BY redundant. */ for(ii=0; ii<pGroupBy->nExpr; ii++){ u8 sortFlags = sSort.pOrderBy->a[ii].sortFlags & KEYINFO_ORDER_DESC; pGroupBy->a[ii].sortFlags = sortFlags; } if( sqlite3ExprListCompare(pGroupBy, sSort.pOrderBy, -1)==0 ){ orderByGrp = 1; } } }else{ assert( 0==sqlite3LogEst(1) ); p->nSelectRow = 0; } /* Create a label to jump to when we want to abort the query */ addrEnd = sqlite3VdbeMakeLabel(pParse); /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the ** SELECT statement. */ memset(&sNC, 0, sizeof(sNC)); sNC.pParse = pParse; sNC.pSrcList = pTabList; sNC.uNC.pAggInfo = &sAggInfo; VVA_ONLY( sNC.ncFlags = NC_UAggInfo; ) sAggInfo.mnReg = pParse->nMem+1; sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr : 0; sAggInfo.pGroupBy = pGroupBy; sqlite3ExprAnalyzeAggList(&sNC, pEList); sqlite3ExprAnalyzeAggList(&sNC, sSort.pOrderBy); if( pHaving ){ if( pGroupBy ){ assert( pWhere==p->pWhere ); assert( pHaving==p->pHaving ); assert( pGroupBy==p->pGroupBy ); havingToWhere(pParse, p); pWhere = p->pWhere; } sqlite3ExprAnalyzeAggregates(&sNC, pHaving); } sAggInfo.nAccumulator = sAggInfo.nColumn; if( p->pGroupBy==0 && p->pHaving==0 && sAggInfo.nFunc==1 ){ minMaxFlag = minMaxQuery(db, sAggInfo.aFunc[0].pExpr, &pMinMaxOrderBy); }else{ minMaxFlag = WHERE_ORDERBY_NORMAL; } for(i=0; i<sAggInfo.nFunc; i++){ Expr *pExpr = sAggInfo.aFunc[i].pExpr; assert( !ExprHasProperty(pExpr, EP_xIsSelect) ); sNC.ncFlags |= NC_InAggFunc; sqlite3ExprAnalyzeAggList(&sNC, pExpr->x.pList); #ifndef SQLITE_OMIT_WINDOWFUNC assert( !IsWindowFunc(pExpr) ); if( ExprHasProperty(pExpr, EP_WinFunc) ){ sqlite3ExprAnalyzeAggregates(&sNC, pExpr->y.pWin->pFilter); } #endif sNC.ncFlags &= ~NC_InAggFunc; } sAggInfo.mxReg = pParse->nMem; if( db->mallocFailed ) goto select_end; #if SELECTTRACE_ENABLED if( sqlite3SelectTrace & 0x400 ){ int ii; SELECTTRACE(0x400,pParse,p,("After aggregate analysis:\n")); sqlite3TreeViewSelect(0, p, 0); for(ii=0; ii<sAggInfo.nColumn; ii++){ sqlite3DebugPrintf("agg-column[%d] iMem=%d\n", ii, sAggInfo.aCol[ii].iMem); sqlite3TreeViewExpr(0, sAggInfo.aCol[ii].pExpr, 0); } for(ii=0; ii<sAggInfo.nFunc; ii++){ sqlite3DebugPrintf("agg-func[%d]: iMem=%d\n", ii, sAggInfo.aFunc[ii].iMem); sqlite3TreeViewExpr(0, sAggInfo.aFunc[ii].pExpr, 0); } } #endif /* Processing for aggregates with GROUP BY is very different and ** much more complex than aggregates without a GROUP BY. */ if( pGroupBy ){ KeyInfo *pKeyInfo; /* Keying information for the group by clause */ int addr1; /* A-vs-B comparision jump */ int addrOutputRow; /* Start of subroutine that outputs a result row */ int regOutputRow; /* Return address register for output subroutine */ int addrSetAbort; /* Set the abort flag and return */ int addrTopOfLoop; /* Top of the input loop */ int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */ int addrReset; /* Subroutine for resetting the accumulator */ int regReset; /* Return address register for reset subroutine */ /* If there is a GROUP BY clause we might need a sorting index to ** implement it. Allocate that sorting index now. If it turns out ** that we do not need it after all, the OP_SorterOpen instruction ** will be converted into a Noop. */ sAggInfo.sortingIdx = pParse->nTab++; pKeyInfo = sqlite3KeyInfoFromExprList(pParse,pGroupBy,0,sAggInfo.nColumn); addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen, sAggInfo.sortingIdx, sAggInfo.nSortingColumn, 0, (char*)pKeyInfo, P4_KEYINFO); /* Initialize memory locations used by GROUP BY aggregate processing */ iUseFlag = ++pParse->nMem; iAbortFlag = ++pParse->nMem; regOutputRow = ++pParse->nMem; addrOutputRow = sqlite3VdbeMakeLabel(pParse); regReset = ++pParse->nMem; addrReset = sqlite3VdbeMakeLabel(pParse); iAMem = pParse->nMem + 1; pParse->nMem += pGroupBy->nExpr; iBMem = pParse->nMem + 1; pParse->nMem += pGroupBy->nExpr; sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag); VdbeComment((v, "clear abort flag")); sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1); /* Begin a loop that will extract all source rows in GROUP BY order. ** This might involve two separate loops with an OP_Sort in between, or ** it might be a single loop that uses an index to extract information ** in the right order to begin with. */ sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset); SELECTTRACE(1,pParse,p,("WhereBegin\n")); pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0, WHERE_GROUPBY | (orderByGrp ? WHERE_SORTBYGROUP : 0), 0 ); if( pWInfo==0 ) goto select_end; if( sqlite3WhereIsOrdered(pWInfo)==pGroupBy->nExpr ){ /* The optimizer is able to deliver rows in group by order so ** we do not have to sort. The OP_OpenEphemeral table will be ** cancelled later because we still need to use the pKeyInfo */ groupBySort = 0; }else{ /* Rows are coming out in undetermined order. We have to push ** each row into a sorting index, terminate the first loop, ** then loop over the sorting index in order to get the output ** in sorted order */ int regBase; int regRecord; int nCol; int nGroupBy; explainTempTable(pParse, (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ? "DISTINCT" : "GROUP BY"); groupBySort = 1; nGroupBy = pGroupBy->nExpr; nCol = nGroupBy; j = nGroupBy; for(i=0; i<sAggInfo.nColumn; i++){ if( sAggInfo.aCol[i].iSorterColumn>=j ){ nCol++; j++; } } regBase = sqlite3GetTempRange(pParse, nCol); sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0, 0); j = nGroupBy; for(i=0; i<sAggInfo.nColumn; i++){ struct AggInfo_col *pCol = &sAggInfo.aCol[i]; if( pCol->iSorterColumn>=j ){ int r1 = j + regBase; sqlite3ExprCodeGetColumnOfTable(v, pCol->pTab, pCol->iTable, pCol->iColumn, r1); j++; } } regRecord = sqlite3GetTempReg(pParse); sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord); sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord); sqlite3ReleaseTempReg(pParse, regRecord); sqlite3ReleaseTempRange(pParse, regBase, nCol); sqlite3WhereEnd(pWInfo); sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++; sortOut = sqlite3GetTempReg(pParse); sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol); sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd); VdbeComment((v, "GROUP BY sort")); VdbeCoverage(v); sAggInfo.useSortingIdx = 1; } /* If the index or temporary table used by the GROUP BY sort ** will naturally deliver rows in the order required by the ORDER BY ** clause, cancel the ephemeral table open coded earlier. ** ** This is an optimization - the correct answer should result regardless. ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER to ** disable this optimization for testing purposes. */ if( orderByGrp && OptimizationEnabled(db, SQLITE_GroupByOrder) && (groupBySort || sqlite3WhereIsSorted(pWInfo)) ){ sSort.pOrderBy = 0; sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex); } /* Evaluate the current GROUP BY terms and store in b0, b1, b2... ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth) ** Then compare the current GROUP BY terms against the GROUP BY terms ** from the previous row currently stored in a0, a1, a2... */ addrTopOfLoop = sqlite3VdbeCurrentAddr(v); if( groupBySort ){ sqlite3VdbeAddOp3(v, OP_SorterData, sAggInfo.sortingIdx, sortOut, sortPTab); } for(j=0; j<pGroupBy->nExpr; j++){ if( groupBySort ){ sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j); }else{ sAggInfo.directMode = 1; sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j); } } sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr, (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO); addr1 = sqlite3VdbeCurrentAddr(v); sqlite3VdbeAddOp3(v, OP_Jump, addr1+1, 0, addr1+1); VdbeCoverage(v); /* Generate code that runs whenever the GROUP BY changes. ** Changes in the GROUP BY are detected by the previous code ** block. If there were no changes, this block is skipped. ** ** This code copies current group by terms in b0,b1,b2,... ** over to a0,a1,a2. It then calls the output subroutine ** and resets the aggregate accumulator registers in preparation ** for the next GROUP BY batch. */ sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr); sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow); VdbeComment((v, "output one row")); sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); VdbeCoverage(v); VdbeComment((v, "check abort flag")); sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset); VdbeComment((v, "reset accumulator")); /* Update the aggregate accumulators based on the content of ** the current row */ sqlite3VdbeJumpHere(v, addr1); updateAccumulator(pParse, iUseFlag, &sAggInfo); sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag); VdbeComment((v, "indicate data in accumulator")); /* End of the loop */ if( groupBySort ){ sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop); VdbeCoverage(v); }else{ sqlite3WhereEnd(pWInfo); sqlite3VdbeChangeToNoop(v, addrSortingIdx); } /* Output the final row of result */ sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow); VdbeComment((v, "output final row")); /* Jump over the subroutines */ sqlite3VdbeGoto(v, addrEnd); /* Generate a subroutine that outputs a single row of the result ** set. This subroutine first looks at the iUseFlag. If iUseFlag ** is less than or equal to zero, the subroutine is a no-op. If ** the processing calls for the query to abort, this subroutine ** increments the iAbortFlag memory location before returning in ** order to signal the caller to abort. */ addrSetAbort = sqlite3VdbeCurrentAddr(v); sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag); VdbeComment((v, "set abort flag")); sqlite3VdbeAddOp1(v, OP_Return, regOutputRow); sqlite3VdbeResolveLabel(v, addrOutputRow); addrOutputRow = sqlite3VdbeCurrentAddr(v); sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2); VdbeCoverage(v); VdbeComment((v, "Groupby result generator entry point")); sqlite3VdbeAddOp1(v, OP_Return, regOutputRow); finalizeAggFunctions(pParse, &sAggInfo); sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL); selectInnerLoop(pParse, p, -1, &sSort, &sDistinct, pDest, addrOutputRow+1, addrSetAbort); sqlite3VdbeAddOp1(v, OP_Return, regOutputRow); VdbeComment((v, "end groupby result generator")); /* Generate a subroutine that will reset the group-by accumulator */ sqlite3VdbeResolveLabel(v, addrReset); resetAccumulator(pParse, &sAggInfo); sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag); VdbeComment((v, "indicate accumulator empty")); sqlite3VdbeAddOp1(v, OP_Return, regReset); } /* endif pGroupBy. Begin aggregate queries without GROUP BY: */ else { #ifndef SQLITE_OMIT_BTREECOUNT Table *pTab; if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){ /* If isSimpleCount() returns a pointer to a Table structure, then ** the SQL statement is of the form: ** ** SELECT count(*) FROM <tbl> ** ** where the Table structure returned represents table <tbl>. ** ** This statement is so common that it is optimized specially. The ** OP_Count instruction is executed either on the intkey table that ** contains the data for table <tbl> or on one of its indexes. It ** is better to execute the op on an index, as indexes are almost ** always spread across less pages than their corresponding tables. */ const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); const int iCsr = pParse->nTab++; /* Cursor to scan b-tree */ Index *pIdx; /* Iterator variable */ KeyInfo *pKeyInfo = 0; /* Keyinfo for scanned index */ Index *pBest = 0; /* Best index found so far */ int iRoot = pTab->tnum; /* Root page of scanned b-tree */ sqlite3CodeVerifySchema(pParse, iDb); sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName); /* Search for the index that has the lowest scan cost. ** ** (2011-04-15) Do not do a full scan of an unordered index. ** ** (2013-10-03) Do not count the entries in a partial index. ** ** In practice the KeyInfo structure will not be used. It is only ** passed to keep OP_OpenRead happy. */ if( !HasRowid(pTab) ) pBest = sqlite3PrimaryKeyIndex(pTab); for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ if( pIdx->bUnordered==0 && pIdx->szIdxRow<pTab->szTabRow && pIdx->pPartIdxWhere==0 && (!pBest || pIdx->szIdxRow<pBest->szIdxRow) ){ pBest = pIdx; } } if( pBest ){ iRoot = pBest->tnum; pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pBest); } /* Open a read-only cursor, execute the OP_Count, close the cursor. */ sqlite3VdbeAddOp4Int(v, OP_OpenRead, iCsr, iRoot, iDb, 1); if( pKeyInfo ){ sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO); } sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem); sqlite3VdbeAddOp1(v, OP_Close, iCsr); explainSimpleCount(pParse, pTab, pBest); }else #endif /* SQLITE_OMIT_BTREECOUNT */ { int regAcc = 0; /* "populate accumulators" flag */ /* If there are accumulator registers but no min() or max() functions ** without FILTER clauses, allocate register regAcc. Register regAcc ** will contain 0 the first time the inner loop runs, and 1 thereafter. ** The code generated by updateAccumulator() uses this to ensure ** that the accumulator registers are (a) updated only once if ** there are no min() or max functions or (b) always updated for the ** first row visited by the aggregate, so that they are updated at ** least once even if the FILTER clause means the min() or max() ** function visits zero rows. */ if( sAggInfo.nAccumulator ){ for(i=0; i<sAggInfo.nFunc; i++){ if( ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_WinFunc) ) continue; if( sAggInfo.aFunc[i].pFunc->funcFlags&SQLITE_FUNC_NEEDCOLL ) break; } if( i==sAggInfo.nFunc ){ regAcc = ++pParse->nMem; sqlite3VdbeAddOp2(v, OP_Integer, 0, regAcc); } } /* This case runs if the aggregate has no GROUP BY clause. The ** processing is much simpler since there is only a single row ** of output. */ assert( p->pGroupBy==0 ); resetAccumulator(pParse, &sAggInfo); /* If this query is a candidate for the min/max optimization, then ** minMaxFlag will have been previously set to either ** WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX and pMinMaxOrderBy will ** be an appropriate ORDER BY expression for the optimization. */ assert( minMaxFlag==WHERE_ORDERBY_NORMAL || pMinMaxOrderBy!=0 ); assert( pMinMaxOrderBy==0 || pMinMaxOrderBy->nExpr==1 ); SELECTTRACE(1,pParse,p,("WhereBegin\n")); pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMaxOrderBy, 0, minMaxFlag, 0); if( pWInfo==0 ){ goto select_end; } updateAccumulator(pParse, regAcc, &sAggInfo); if( regAcc ) sqlite3VdbeAddOp2(v, OP_Integer, 1, regAcc); if( sqlite3WhereIsOrdered(pWInfo)>0 ){ sqlite3VdbeGoto(v, sqlite3WhereBreakLabel(pWInfo)); VdbeComment((v, "%s() by index", (minMaxFlag==WHERE_ORDERBY_MIN?"min":"max"))); } sqlite3WhereEnd(pWInfo); finalizeAggFunctions(pParse, &sAggInfo); } sSort.pOrderBy = 0; sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL); selectInnerLoop(pParse, p, -1, 0, 0, pDest, addrEnd, addrEnd); } sqlite3VdbeResolveLabel(v, addrEnd); } /* endif aggregate query */ if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){ explainTempTable(pParse, "DISTINCT"); } /* If there is an ORDER BY clause, then we need to sort the results ** and send them to the callback one by one. */ if( sSort.pOrderBy ){ explainTempTable(pParse, sSort.nOBSat>0 ? "RIGHT PART OF ORDER BY":"ORDER BY"); assert( p->pEList==pEList ); generateSortTail(pParse, p, &sSort, pEList->nExpr, pDest); } /* Jump here to skip this query */ sqlite3VdbeResolveLabel(v, iEnd); /* The SELECT has been coded. If there is an error in the Parse structure, ** set the return code to 1. Otherwise 0. */ rc = (pParse->nErr>0); /* Control jumps to here if an error is encountered above, or upon ** successful coding of the SELECT. */ select_end: sqlite3ExprListDelete(db, pMinMaxOrderBy); sqlite3DbFree(db, sAggInfo.aCol); sqlite3DbFree(db, sAggInfo.aFunc); #if SELECTTRACE_ENABLED SELECTTRACE(0x1,pParse,p,("end processing\n")); if( (sqlite3SelectTrace & 0x2000)!=0 && ExplainQueryPlanParent(pParse)==0 ){ sqlite3TreeViewSelect(0, p, 0); } #endif ExplainQueryPlanPop(pParse); return rc; }
./CrossVul/dataset_final_sorted/CWE-20/c/good_1276_2
crossvul-cpp_data_good_5562_0
/* * SUCS NET3: * * Generic datagram handling routines. These are generic for all * protocols. Possibly a generic IP version on top of these would * make sense. Not tonight however 8-). * This is used because UDP, RAW, PACKET, DDP, IPX, AX.25 and * NetROM layer all have identical poll code and mostly * identical recvmsg() code. So we share it here. The poll was * shared before but buried in udp.c so I moved it. * * Authors: Alan Cox <alan@lxorguk.ukuu.org.uk>. (datagram_poll() from old * udp.c code) * * Fixes: * Alan Cox : NULL return from skb_peek_copy() * understood * Alan Cox : Rewrote skb_read_datagram to avoid the * skb_peek_copy stuff. * Alan Cox : Added support for SOCK_SEQPACKET. * IPX can no longer use the SO_TYPE hack * but AX.25 now works right, and SPX is * feasible. * Alan Cox : Fixed write poll of non IP protocol * crash. * Florian La Roche: Changed for my new skbuff handling. * Darryl Miles : Fixed non-blocking SOCK_SEQPACKET. * Linus Torvalds : BSD semantic fixes. * Alan Cox : Datagram iovec handling * Darryl Miles : Fixed non-blocking SOCK_STREAM. * Alan Cox : POSIXisms * Pete Wyckoff : Unconnected accept() fix. * */ #include <linux/module.h> #include <linux/types.h> #include <linux/kernel.h> #include <asm/uaccess.h> #include <linux/mm.h> #include <linux/interrupt.h> #include <linux/errno.h> #include <linux/sched.h> #include <linux/inet.h> #include <linux/netdevice.h> #include <linux/rtnetlink.h> #include <linux/poll.h> #include <linux/highmem.h> #include <linux/spinlock.h> #include <linux/slab.h> #include <net/protocol.h> #include <linux/skbuff.h> #include <net/checksum.h> #include <net/sock.h> #include <net/tcp_states.h> #include <trace/events/skb.h> /* * Is a socket 'connection oriented' ? */ static inline int connection_based(struct sock *sk) { return sk->sk_type == SOCK_SEQPACKET || sk->sk_type == SOCK_STREAM; } static int receiver_wake_function(wait_queue_t *wait, unsigned int mode, int sync, void *key) { unsigned long bits = (unsigned long)key; /* * Avoid a wakeup if event not interesting for us */ if (bits && !(bits & (POLLIN | POLLERR))) return 0; return autoremove_wake_function(wait, mode, sync, key); } /* * Wait for a packet.. */ static int wait_for_packet(struct sock *sk, int *err, long *timeo_p) { int error; DEFINE_WAIT_FUNC(wait, receiver_wake_function); prepare_to_wait_exclusive(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE); /* Socket errors? */ error = sock_error(sk); if (error) goto out_err; if (!skb_queue_empty(&sk->sk_receive_queue)) goto out; /* Socket shut down? */ if (sk->sk_shutdown & RCV_SHUTDOWN) goto out_noerr; /* Sequenced packets can come disconnected. * If so we report the problem */ error = -ENOTCONN; if (connection_based(sk) && !(sk->sk_state == TCP_ESTABLISHED || sk->sk_state == TCP_LISTEN)) goto out_err; /* handle signals */ if (signal_pending(current)) goto interrupted; error = 0; *timeo_p = schedule_timeout(*timeo_p); out: finish_wait(sk_sleep(sk), &wait); return error; interrupted: error = sock_intr_errno(*timeo_p); out_err: *err = error; goto out; out_noerr: *err = 0; error = 1; goto out; } /** * __skb_recv_datagram - Receive a datagram skbuff * @sk: socket * @flags: MSG_ flags * @off: an offset in bytes to peek skb from. Returns an offset * within an skb where data actually starts * @peeked: returns non-zero if this packet has been seen before * @err: error code returned * * Get a datagram skbuff, understands the peeking, nonblocking wakeups * and possible races. This replaces identical code in packet, raw and * udp, as well as the IPX AX.25 and Appletalk. It also finally fixes * the long standing peek and read race for datagram sockets. If you * alter this routine remember it must be re-entrant. * * This function will lock the socket if a skb is returned, so the caller * needs to unlock the socket in that case (usually by calling * skb_free_datagram) * * * It does not lock socket since today. This function is * * free of race conditions. This measure should/can improve * * significantly datagram socket latencies at high loads, * * when data copying to user space takes lots of time. * * (BTW I've just killed the last cli() in IP/IPv6/core/netlink/packet * * 8) Great win.) * * --ANK (980729) * * The order of the tests when we find no data waiting are specified * quite explicitly by POSIX 1003.1g, don't change them without having * the standard around please. */ struct sk_buff *__skb_recv_datagram(struct sock *sk, unsigned int flags, int *peeked, int *off, int *err) { struct sk_buff *skb; long timeo; /* * Caller is allowed not to check sk->sk_err before skb_recv_datagram() */ int error = sock_error(sk); if (error) goto no_packet; timeo = sock_rcvtimeo(sk, flags & MSG_DONTWAIT); do { /* Again only user level code calls this function, so nothing * interrupt level will suddenly eat the receive_queue. * * Look at current nfs client by the way... * However, this function was correct in any case. 8) */ unsigned long cpu_flags; struct sk_buff_head *queue = &sk->sk_receive_queue; spin_lock_irqsave(&queue->lock, cpu_flags); skb_queue_walk(queue, skb) { *peeked = skb->peeked; if (flags & MSG_PEEK) { if (*off >= skb->len && skb->len) { *off -= skb->len; continue; } skb->peeked = 1; atomic_inc(&skb->users); } else __skb_unlink(skb, queue); spin_unlock_irqrestore(&queue->lock, cpu_flags); return skb; } spin_unlock_irqrestore(&queue->lock, cpu_flags); /* User doesn't want to wait */ error = -EAGAIN; if (!timeo) goto no_packet; } while (!wait_for_packet(sk, err, &timeo)); return NULL; no_packet: *err = error; return NULL; } EXPORT_SYMBOL(__skb_recv_datagram); struct sk_buff *skb_recv_datagram(struct sock *sk, unsigned int flags, int noblock, int *err) { int peeked, off = 0; return __skb_recv_datagram(sk, flags | (noblock ? MSG_DONTWAIT : 0), &peeked, &off, err); } EXPORT_SYMBOL(skb_recv_datagram); void skb_free_datagram(struct sock *sk, struct sk_buff *skb) { consume_skb(skb); sk_mem_reclaim_partial(sk); } EXPORT_SYMBOL(skb_free_datagram); void skb_free_datagram_locked(struct sock *sk, struct sk_buff *skb) { bool slow; if (likely(atomic_read(&skb->users) == 1)) smp_rmb(); else if (likely(!atomic_dec_and_test(&skb->users))) return; slow = lock_sock_fast(sk); skb_orphan(skb); sk_mem_reclaim_partial(sk); unlock_sock_fast(sk, slow); /* skb is now orphaned, can be freed outside of locked section */ __kfree_skb(skb); } EXPORT_SYMBOL(skb_free_datagram_locked); /** * skb_kill_datagram - Free a datagram skbuff forcibly * @sk: socket * @skb: datagram skbuff * @flags: MSG_ flags * * This function frees a datagram skbuff that was received by * skb_recv_datagram. The flags argument must match the one * used for skb_recv_datagram. * * If the MSG_PEEK flag is set, and the packet is still on the * receive queue of the socket, it will be taken off the queue * before it is freed. * * This function currently only disables BH when acquiring the * sk_receive_queue lock. Therefore it must not be used in a * context where that lock is acquired in an IRQ context. * * It returns 0 if the packet was removed by us. */ int skb_kill_datagram(struct sock *sk, struct sk_buff *skb, unsigned int flags) { int err = 0; if (flags & MSG_PEEK) { err = -ENOENT; spin_lock_bh(&sk->sk_receive_queue.lock); if (skb == skb_peek(&sk->sk_receive_queue)) { __skb_unlink(skb, &sk->sk_receive_queue); atomic_dec(&skb->users); err = 0; } spin_unlock_bh(&sk->sk_receive_queue.lock); } kfree_skb(skb); atomic_inc(&sk->sk_drops); sk_mem_reclaim_partial(sk); return err; } EXPORT_SYMBOL(skb_kill_datagram); /** * skb_copy_datagram_iovec - Copy a datagram to an iovec. * @skb: buffer to copy * @offset: offset in the buffer to start copying from * @to: io vector to copy to * @len: amount of data to copy from buffer to iovec * * Note: the iovec is modified during the copy. */ int skb_copy_datagram_iovec(const struct sk_buff *skb, int offset, struct iovec *to, int len) { int start = skb_headlen(skb); int i, copy = start - offset; struct sk_buff *frag_iter; trace_skb_copy_datagram_iovec(skb, len); /* Copy header. */ if (copy > 0) { if (copy > len) copy = len; if (memcpy_toiovec(to, skb->data + offset, copy)) goto fault; if ((len -= copy) == 0) return 0; offset += copy; } /* Copy paged appendix. Hmm... why does this look so complicated? */ for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) { int end; const skb_frag_t *frag = &skb_shinfo(skb)->frags[i]; WARN_ON(start > offset + len); end = start + skb_frag_size(frag); if ((copy = end - offset) > 0) { int err; u8 *vaddr; struct page *page = skb_frag_page(frag); if (copy > len) copy = len; vaddr = kmap(page); err = memcpy_toiovec(to, vaddr + frag->page_offset + offset - start, copy); kunmap(page); if (err) goto fault; if (!(len -= copy)) return 0; offset += copy; } start = end; } skb_walk_frags(skb, frag_iter) { int end; WARN_ON(start > offset + len); end = start + frag_iter->len; if ((copy = end - offset) > 0) { if (copy > len) copy = len; if (skb_copy_datagram_iovec(frag_iter, offset - start, to, copy)) goto fault; if ((len -= copy) == 0) return 0; offset += copy; } start = end; } if (!len) return 0; fault: return -EFAULT; } EXPORT_SYMBOL(skb_copy_datagram_iovec); /** * skb_copy_datagram_const_iovec - Copy a datagram to an iovec. * @skb: buffer to copy * @offset: offset in the buffer to start copying from * @to: io vector to copy to * @to_offset: offset in the io vector to start copying to * @len: amount of data to copy from buffer to iovec * * Returns 0 or -EFAULT. * Note: the iovec is not modified during the copy. */ int skb_copy_datagram_const_iovec(const struct sk_buff *skb, int offset, const struct iovec *to, int to_offset, int len) { int start = skb_headlen(skb); int i, copy = start - offset; struct sk_buff *frag_iter; /* Copy header. */ if (copy > 0) { if (copy > len) copy = len; if (memcpy_toiovecend(to, skb->data + offset, to_offset, copy)) goto fault; if ((len -= copy) == 0) return 0; offset += copy; to_offset += copy; } /* Copy paged appendix. Hmm... why does this look so complicated? */ for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) { int end; const skb_frag_t *frag = &skb_shinfo(skb)->frags[i]; WARN_ON(start > offset + len); end = start + skb_frag_size(frag); if ((copy = end - offset) > 0) { int err; u8 *vaddr; struct page *page = skb_frag_page(frag); if (copy > len) copy = len; vaddr = kmap(page); err = memcpy_toiovecend(to, vaddr + frag->page_offset + offset - start, to_offset, copy); kunmap(page); if (err) goto fault; if (!(len -= copy)) return 0; offset += copy; to_offset += copy; } start = end; } skb_walk_frags(skb, frag_iter) { int end; WARN_ON(start > offset + len); end = start + frag_iter->len; if ((copy = end - offset) > 0) { if (copy > len) copy = len; if (skb_copy_datagram_const_iovec(frag_iter, offset - start, to, to_offset, copy)) goto fault; if ((len -= copy) == 0) return 0; offset += copy; to_offset += copy; } start = end; } if (!len) return 0; fault: return -EFAULT; } EXPORT_SYMBOL(skb_copy_datagram_const_iovec); /** * skb_copy_datagram_from_iovec - Copy a datagram from an iovec. * @skb: buffer to copy * @offset: offset in the buffer to start copying to * @from: io vector to copy to * @from_offset: offset in the io vector to start copying from * @len: amount of data to copy to buffer from iovec * * Returns 0 or -EFAULT. * Note: the iovec is not modified during the copy. */ int skb_copy_datagram_from_iovec(struct sk_buff *skb, int offset, const struct iovec *from, int from_offset, int len) { int start = skb_headlen(skb); int i, copy = start - offset; struct sk_buff *frag_iter; /* Copy header. */ if (copy > 0) { if (copy > len) copy = len; if (memcpy_fromiovecend(skb->data + offset, from, from_offset, copy)) goto fault; if ((len -= copy) == 0) return 0; offset += copy; from_offset += copy; } /* Copy paged appendix. Hmm... why does this look so complicated? */ for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) { int end; const skb_frag_t *frag = &skb_shinfo(skb)->frags[i]; WARN_ON(start > offset + len); end = start + skb_frag_size(frag); if ((copy = end - offset) > 0) { int err; u8 *vaddr; struct page *page = skb_frag_page(frag); if (copy > len) copy = len; vaddr = kmap(page); err = memcpy_fromiovecend(vaddr + frag->page_offset + offset - start, from, from_offset, copy); kunmap(page); if (err) goto fault; if (!(len -= copy)) return 0; offset += copy; from_offset += copy; } start = end; } skb_walk_frags(skb, frag_iter) { int end; WARN_ON(start > offset + len); end = start + frag_iter->len; if ((copy = end - offset) > 0) { if (copy > len) copy = len; if (skb_copy_datagram_from_iovec(frag_iter, offset - start, from, from_offset, copy)) goto fault; if ((len -= copy) == 0) return 0; offset += copy; from_offset += copy; } start = end; } if (!len) return 0; fault: return -EFAULT; } EXPORT_SYMBOL(skb_copy_datagram_from_iovec); static int skb_copy_and_csum_datagram(const struct sk_buff *skb, int offset, u8 __user *to, int len, __wsum *csump) { int start = skb_headlen(skb); int i, copy = start - offset; struct sk_buff *frag_iter; int pos = 0; /* Copy header. */ if (copy > 0) { int err = 0; if (copy > len) copy = len; *csump = csum_and_copy_to_user(skb->data + offset, to, copy, *csump, &err); if (err) goto fault; if ((len -= copy) == 0) return 0; offset += copy; to += copy; pos = copy; } for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) { int end; const skb_frag_t *frag = &skb_shinfo(skb)->frags[i]; WARN_ON(start > offset + len); end = start + skb_frag_size(frag); if ((copy = end - offset) > 0) { __wsum csum2; int err = 0; u8 *vaddr; struct page *page = skb_frag_page(frag); if (copy > len) copy = len; vaddr = kmap(page); csum2 = csum_and_copy_to_user(vaddr + frag->page_offset + offset - start, to, copy, 0, &err); kunmap(page); if (err) goto fault; *csump = csum_block_add(*csump, csum2, pos); if (!(len -= copy)) return 0; offset += copy; to += copy; pos += copy; } start = end; } skb_walk_frags(skb, frag_iter) { int end; WARN_ON(start > offset + len); end = start + frag_iter->len; if ((copy = end - offset) > 0) { __wsum csum2 = 0; if (copy > len) copy = len; if (skb_copy_and_csum_datagram(frag_iter, offset - start, to, copy, &csum2)) goto fault; *csump = csum_block_add(*csump, csum2, pos); if ((len -= copy) == 0) return 0; offset += copy; to += copy; pos += copy; } start = end; } if (!len) return 0; fault: return -EFAULT; } __sum16 __skb_checksum_complete_head(struct sk_buff *skb, int len) { __sum16 sum; sum = csum_fold(skb_checksum(skb, 0, len, skb->csum)); if (likely(!sum)) { if (unlikely(skb->ip_summed == CHECKSUM_COMPLETE)) netdev_rx_csum_fault(skb->dev); skb->ip_summed = CHECKSUM_UNNECESSARY; } return sum; } EXPORT_SYMBOL(__skb_checksum_complete_head); __sum16 __skb_checksum_complete(struct sk_buff *skb) { return __skb_checksum_complete_head(skb, skb->len); } EXPORT_SYMBOL(__skb_checksum_complete); /** * skb_copy_and_csum_datagram_iovec - Copy and checkum skb to user iovec. * @skb: skbuff * @hlen: hardware length * @iov: io vector * * Caller _must_ check that skb will fit to this iovec. * * Returns: 0 - success. * -EINVAL - checksum failure. * -EFAULT - fault during copy. Beware, in this case iovec * can be modified! */ int skb_copy_and_csum_datagram_iovec(struct sk_buff *skb, int hlen, struct iovec *iov) { __wsum csum; int chunk = skb->len - hlen; if (!chunk) return 0; /* Skip filled elements. * Pretty silly, look at memcpy_toiovec, though 8) */ while (!iov->iov_len) iov++; if (iov->iov_len < chunk) { if (__skb_checksum_complete(skb)) goto csum_error; if (skb_copy_datagram_iovec(skb, hlen, iov, chunk)) goto fault; } else { csum = csum_partial(skb->data, hlen, skb->csum); if (skb_copy_and_csum_datagram(skb, hlen, iov->iov_base, chunk, &csum)) goto fault; if (csum_fold(csum)) goto csum_error; if (unlikely(skb->ip_summed == CHECKSUM_COMPLETE)) netdev_rx_csum_fault(skb->dev); iov->iov_len -= chunk; iov->iov_base += chunk; } return 0; csum_error: return -EINVAL; fault: return -EFAULT; } EXPORT_SYMBOL(skb_copy_and_csum_datagram_iovec); /** * datagram_poll - generic datagram poll * @file: file struct * @sock: socket * @wait: poll table * * Datagram poll: Again totally generic. This also handles * sequenced packet sockets providing the socket receive queue * is only ever holding data ready to receive. * * Note: when you _don't_ use this routine for this protocol, * and you use a different write policy from sock_writeable() * then please supply your own write_space callback. */ unsigned int datagram_poll(struct file *file, struct socket *sock, poll_table *wait) { struct sock *sk = sock->sk; unsigned int mask; sock_poll_wait(file, sk_sleep(sk), wait); mask = 0; /* exceptional events? */ if (sk->sk_err || !skb_queue_empty(&sk->sk_error_queue)) mask |= POLLERR; if (sk->sk_shutdown & RCV_SHUTDOWN) mask |= POLLRDHUP | POLLIN | POLLRDNORM; if (sk->sk_shutdown == SHUTDOWN_MASK) mask |= POLLHUP; /* readable? */ if (!skb_queue_empty(&sk->sk_receive_queue)) mask |= POLLIN | POLLRDNORM; /* Connection-based need to check for termination and startup */ if (connection_based(sk)) { if (sk->sk_state == TCP_CLOSE) mask |= POLLHUP; /* connection hasn't started yet? */ if (sk->sk_state == TCP_SYN_SENT) return mask; } /* writable? */ if (sock_writeable(sk)) mask |= POLLOUT | POLLWRNORM | POLLWRBAND; else set_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags); return mask; } EXPORT_SYMBOL(datagram_poll);
./CrossVul/dataset_final_sorted/CWE-20/c/good_5562_0
crossvul-cpp_data_bad_2884_0
/* BNEP implementation for Linux Bluetooth stack (BlueZ). Copyright (C) 2001-2002 Inventel Systemes Written 2001-2002 by Clément Moreau <clement.moreau@inventel.fr> David Libault <david.libault@inventel.fr> Copyright (C) 2002 Maxim Krasnyansky <maxk@qualcomm.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) AND AUTHOR(S) BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ALL LIABILITY, INCLUDING LIABILITY FOR INFRINGEMENT OF ANY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS, RELATING TO USE OF THIS SOFTWARE IS DISCLAIMED. */ #include <linux/module.h> #include <linux/kthread.h> #include <linux/file.h> #include <linux/etherdevice.h> #include <asm/unaligned.h> #include <net/bluetooth/bluetooth.h> #include <net/bluetooth/l2cap.h> #include <net/bluetooth/hci_core.h> #include "bnep.h" #define VERSION "1.3" static bool compress_src = true; static bool compress_dst = true; static LIST_HEAD(bnep_session_list); static DECLARE_RWSEM(bnep_session_sem); static struct bnep_session *__bnep_get_session(u8 *dst) { struct bnep_session *s; BT_DBG(""); list_for_each_entry(s, &bnep_session_list, list) if (ether_addr_equal(dst, s->eh.h_source)) return s; return NULL; } static void __bnep_link_session(struct bnep_session *s) { list_add(&s->list, &bnep_session_list); } static void __bnep_unlink_session(struct bnep_session *s) { list_del(&s->list); } static int bnep_send(struct bnep_session *s, void *data, size_t len) { struct socket *sock = s->sock; struct kvec iv = { data, len }; return kernel_sendmsg(sock, &s->msg, &iv, 1, len); } static int bnep_send_rsp(struct bnep_session *s, u8 ctrl, u16 resp) { struct bnep_control_rsp rsp; rsp.type = BNEP_CONTROL; rsp.ctrl = ctrl; rsp.resp = htons(resp); return bnep_send(s, &rsp, sizeof(rsp)); } #ifdef CONFIG_BT_BNEP_PROTO_FILTER static inline void bnep_set_default_proto_filter(struct bnep_session *s) { /* (IPv4, ARP) */ s->proto_filter[0].start = ETH_P_IP; s->proto_filter[0].end = ETH_P_ARP; /* (RARP, AppleTalk) */ s->proto_filter[1].start = ETH_P_RARP; s->proto_filter[1].end = ETH_P_AARP; /* (IPX, IPv6) */ s->proto_filter[2].start = ETH_P_IPX; s->proto_filter[2].end = ETH_P_IPV6; } #endif static int bnep_ctrl_set_netfilter(struct bnep_session *s, __be16 *data, int len) { int n; if (len < 2) return -EILSEQ; n = get_unaligned_be16(data); data++; len -= 2; if (len < n) return -EILSEQ; BT_DBG("filter len %d", n); #ifdef CONFIG_BT_BNEP_PROTO_FILTER n /= 4; if (n <= BNEP_MAX_PROTO_FILTERS) { struct bnep_proto_filter *f = s->proto_filter; int i; for (i = 0; i < n; i++) { f[i].start = get_unaligned_be16(data++); f[i].end = get_unaligned_be16(data++); BT_DBG("proto filter start %d end %d", f[i].start, f[i].end); } if (i < BNEP_MAX_PROTO_FILTERS) memset(f + i, 0, sizeof(*f)); if (n == 0) bnep_set_default_proto_filter(s); bnep_send_rsp(s, BNEP_FILTER_NET_TYPE_RSP, BNEP_SUCCESS); } else { bnep_send_rsp(s, BNEP_FILTER_NET_TYPE_RSP, BNEP_FILTER_LIMIT_REACHED); } #else bnep_send_rsp(s, BNEP_FILTER_NET_TYPE_RSP, BNEP_FILTER_UNSUPPORTED_REQ); #endif return 0; } static int bnep_ctrl_set_mcfilter(struct bnep_session *s, u8 *data, int len) { int n; if (len < 2) return -EILSEQ; n = get_unaligned_be16(data); data += 2; len -= 2; if (len < n) return -EILSEQ; BT_DBG("filter len %d", n); #ifdef CONFIG_BT_BNEP_MC_FILTER n /= (ETH_ALEN * 2); if (n > 0) { int i; s->mc_filter = 0; /* Always send broadcast */ set_bit(bnep_mc_hash(s->dev->broadcast), (ulong *) &s->mc_filter); /* Add address ranges to the multicast hash */ for (; n > 0; n--) { u8 a1[6], *a2; memcpy(a1, data, ETH_ALEN); data += ETH_ALEN; a2 = data; data += ETH_ALEN; BT_DBG("mc filter %pMR -> %pMR", a1, a2); /* Iterate from a1 to a2 */ set_bit(bnep_mc_hash(a1), (ulong *) &s->mc_filter); while (memcmp(a1, a2, 6) < 0 && s->mc_filter != ~0LL) { /* Increment a1 */ i = 5; while (i >= 0 && ++a1[i--] == 0) ; set_bit(bnep_mc_hash(a1), (ulong *) &s->mc_filter); } } } BT_DBG("mc filter hash 0x%llx", s->mc_filter); bnep_send_rsp(s, BNEP_FILTER_MULTI_ADDR_RSP, BNEP_SUCCESS); #else bnep_send_rsp(s, BNEP_FILTER_MULTI_ADDR_RSP, BNEP_FILTER_UNSUPPORTED_REQ); #endif return 0; } static int bnep_rx_control(struct bnep_session *s, void *data, int len) { u8 cmd = *(u8 *)data; int err = 0; data++; len--; switch (cmd) { case BNEP_CMD_NOT_UNDERSTOOD: case BNEP_SETUP_CONN_RSP: case BNEP_FILTER_NET_TYPE_RSP: case BNEP_FILTER_MULTI_ADDR_RSP: /* Ignore these for now */ break; case BNEP_FILTER_NET_TYPE_SET: err = bnep_ctrl_set_netfilter(s, data, len); break; case BNEP_FILTER_MULTI_ADDR_SET: err = bnep_ctrl_set_mcfilter(s, data, len); break; case BNEP_SETUP_CONN_REQ: err = bnep_send_rsp(s, BNEP_SETUP_CONN_RSP, BNEP_CONN_NOT_ALLOWED); break; default: { u8 pkt[3]; pkt[0] = BNEP_CONTROL; pkt[1] = BNEP_CMD_NOT_UNDERSTOOD; pkt[2] = cmd; bnep_send(s, pkt, sizeof(pkt)); } break; } return err; } static int bnep_rx_extension(struct bnep_session *s, struct sk_buff *skb) { struct bnep_ext_hdr *h; int err = 0; do { h = (void *) skb->data; if (!skb_pull(skb, sizeof(*h))) { err = -EILSEQ; break; } BT_DBG("type 0x%x len %d", h->type, h->len); switch (h->type & BNEP_TYPE_MASK) { case BNEP_EXT_CONTROL: bnep_rx_control(s, skb->data, skb->len); break; default: /* Unknown extension, skip it. */ break; } if (!skb_pull(skb, h->len)) { err = -EILSEQ; break; } } while (!err && (h->type & BNEP_EXT_HEADER)); return err; } static u8 __bnep_rx_hlen[] = { ETH_HLEN, /* BNEP_GENERAL */ 0, /* BNEP_CONTROL */ 2, /* BNEP_COMPRESSED */ ETH_ALEN + 2, /* BNEP_COMPRESSED_SRC_ONLY */ ETH_ALEN + 2 /* BNEP_COMPRESSED_DST_ONLY */ }; static int bnep_rx_frame(struct bnep_session *s, struct sk_buff *skb) { struct net_device *dev = s->dev; struct sk_buff *nskb; u8 type; dev->stats.rx_bytes += skb->len; type = *(u8 *) skb->data; skb_pull(skb, 1); if ((type & BNEP_TYPE_MASK) >= sizeof(__bnep_rx_hlen)) goto badframe; if ((type & BNEP_TYPE_MASK) == BNEP_CONTROL) { bnep_rx_control(s, skb->data, skb->len); kfree_skb(skb); return 0; } skb_reset_mac_header(skb); /* Verify and pull out header */ if (!skb_pull(skb, __bnep_rx_hlen[type & BNEP_TYPE_MASK])) goto badframe; s->eh.h_proto = get_unaligned((__be16 *) (skb->data - 2)); if (type & BNEP_EXT_HEADER) { if (bnep_rx_extension(s, skb) < 0) goto badframe; } /* Strip 802.1p header */ if (ntohs(s->eh.h_proto) == ETH_P_8021Q) { if (!skb_pull(skb, 4)) goto badframe; s->eh.h_proto = get_unaligned((__be16 *) (skb->data - 2)); } /* We have to alloc new skb and copy data here :(. Because original skb * may not be modified and because of the alignment requirements. */ nskb = alloc_skb(2 + ETH_HLEN + skb->len, GFP_KERNEL); if (!nskb) { dev->stats.rx_dropped++; kfree_skb(skb); return -ENOMEM; } skb_reserve(nskb, 2); /* Decompress header and construct ether frame */ switch (type & BNEP_TYPE_MASK) { case BNEP_COMPRESSED: memcpy(__skb_put(nskb, ETH_HLEN), &s->eh, ETH_HLEN); break; case BNEP_COMPRESSED_SRC_ONLY: memcpy(__skb_put(nskb, ETH_ALEN), s->eh.h_dest, ETH_ALEN); memcpy(__skb_put(nskb, ETH_ALEN), skb_mac_header(skb), ETH_ALEN); put_unaligned(s->eh.h_proto, (__be16 *) __skb_put(nskb, 2)); break; case BNEP_COMPRESSED_DST_ONLY: memcpy(__skb_put(nskb, ETH_ALEN), skb_mac_header(skb), ETH_ALEN); memcpy(__skb_put(nskb, ETH_ALEN + 2), s->eh.h_source, ETH_ALEN + 2); break; case BNEP_GENERAL: memcpy(__skb_put(nskb, ETH_ALEN * 2), skb_mac_header(skb), ETH_ALEN * 2); put_unaligned(s->eh.h_proto, (__be16 *) __skb_put(nskb, 2)); break; } skb_copy_from_linear_data(skb, __skb_put(nskb, skb->len), skb->len); kfree_skb(skb); dev->stats.rx_packets++; nskb->ip_summed = CHECKSUM_NONE; nskb->protocol = eth_type_trans(nskb, dev); netif_rx_ni(nskb); return 0; badframe: dev->stats.rx_errors++; kfree_skb(skb); return 0; } static u8 __bnep_tx_types[] = { BNEP_GENERAL, BNEP_COMPRESSED_SRC_ONLY, BNEP_COMPRESSED_DST_ONLY, BNEP_COMPRESSED }; static int bnep_tx_frame(struct bnep_session *s, struct sk_buff *skb) { struct ethhdr *eh = (void *) skb->data; struct socket *sock = s->sock; struct kvec iv[3]; int len = 0, il = 0; u8 type = 0; BT_DBG("skb %p dev %p type %d", skb, skb->dev, skb->pkt_type); if (!skb->dev) { /* Control frame sent by us */ goto send; } iv[il++] = (struct kvec) { &type, 1 }; len++; if (compress_src && ether_addr_equal(eh->h_dest, s->eh.h_source)) type |= 0x01; if (compress_dst && ether_addr_equal(eh->h_source, s->eh.h_dest)) type |= 0x02; if (type) skb_pull(skb, ETH_ALEN * 2); type = __bnep_tx_types[type]; switch (type) { case BNEP_COMPRESSED_SRC_ONLY: iv[il++] = (struct kvec) { eh->h_source, ETH_ALEN }; len += ETH_ALEN; break; case BNEP_COMPRESSED_DST_ONLY: iv[il++] = (struct kvec) { eh->h_dest, ETH_ALEN }; len += ETH_ALEN; break; } send: iv[il++] = (struct kvec) { skb->data, skb->len }; len += skb->len; /* FIXME: linearize skb */ { len = kernel_sendmsg(sock, &s->msg, iv, il, len); } kfree_skb(skb); if (len > 0) { s->dev->stats.tx_bytes += len; s->dev->stats.tx_packets++; return 0; } return len; } static int bnep_session(void *arg) { struct bnep_session *s = arg; struct net_device *dev = s->dev; struct sock *sk = s->sock->sk; struct sk_buff *skb; wait_queue_t wait; BT_DBG(""); set_user_nice(current, -15); init_waitqueue_entry(&wait, current); add_wait_queue(sk_sleep(sk), &wait); while (1) { set_current_state(TASK_INTERRUPTIBLE); if (atomic_read(&s->terminate)) break; /* RX */ while ((skb = skb_dequeue(&sk->sk_receive_queue))) { skb_orphan(skb); if (!skb_linearize(skb)) bnep_rx_frame(s, skb); else kfree_skb(skb); } if (sk->sk_state != BT_CONNECTED) break; /* TX */ while ((skb = skb_dequeue(&sk->sk_write_queue))) if (bnep_tx_frame(s, skb)) break; netif_wake_queue(dev); schedule(); } __set_current_state(TASK_RUNNING); remove_wait_queue(sk_sleep(sk), &wait); /* Cleanup session */ down_write(&bnep_session_sem); /* Delete network device */ unregister_netdev(dev); /* Wakeup user-space polling for socket errors */ s->sock->sk->sk_err = EUNATCH; wake_up_interruptible(sk_sleep(s->sock->sk)); /* Release the socket */ fput(s->sock->file); __bnep_unlink_session(s); up_write(&bnep_session_sem); free_netdev(dev); module_put_and_exit(0); return 0; } static struct device *bnep_get_device(struct bnep_session *session) { struct hci_conn *conn; conn = l2cap_pi(session->sock->sk)->chan->conn->hcon; if (!conn) return NULL; return &conn->dev; } static struct device_type bnep_type = { .name = "bluetooth", }; int bnep_add_connection(struct bnep_connadd_req *req, struct socket *sock) { struct net_device *dev; struct bnep_session *s, *ss; u8 dst[ETH_ALEN], src[ETH_ALEN]; int err; BT_DBG(""); baswap((void *) dst, &l2cap_pi(sock->sk)->chan->dst); baswap((void *) src, &l2cap_pi(sock->sk)->chan->src); /* session struct allocated as private part of net_device */ dev = alloc_netdev(sizeof(struct bnep_session), (*req->device) ? req->device : "bnep%d", NET_NAME_UNKNOWN, bnep_net_setup); if (!dev) return -ENOMEM; down_write(&bnep_session_sem); ss = __bnep_get_session(dst); if (ss && ss->state == BT_CONNECTED) { err = -EEXIST; goto failed; } s = netdev_priv(dev); /* This is rx header therefore addresses are swapped. * ie. eh.h_dest is our local address. */ memcpy(s->eh.h_dest, &src, ETH_ALEN); memcpy(s->eh.h_source, &dst, ETH_ALEN); memcpy(dev->dev_addr, s->eh.h_dest, ETH_ALEN); s->dev = dev; s->sock = sock; s->role = req->role; s->state = BT_CONNECTED; s->msg.msg_flags = MSG_NOSIGNAL; #ifdef CONFIG_BT_BNEP_MC_FILTER /* Set default mc filter */ set_bit(bnep_mc_hash(dev->broadcast), (ulong *) &s->mc_filter); #endif #ifdef CONFIG_BT_BNEP_PROTO_FILTER /* Set default protocol filter */ bnep_set_default_proto_filter(s); #endif SET_NETDEV_DEV(dev, bnep_get_device(s)); SET_NETDEV_DEVTYPE(dev, &bnep_type); err = register_netdev(dev); if (err) goto failed; __bnep_link_session(s); __module_get(THIS_MODULE); s->task = kthread_run(bnep_session, s, "kbnepd %s", dev->name); if (IS_ERR(s->task)) { /* Session thread start failed, gotta cleanup. */ module_put(THIS_MODULE); unregister_netdev(dev); __bnep_unlink_session(s); err = PTR_ERR(s->task); goto failed; } up_write(&bnep_session_sem); strcpy(req->device, dev->name); return 0; failed: up_write(&bnep_session_sem); free_netdev(dev); return err; } int bnep_del_connection(struct bnep_conndel_req *req) { struct bnep_session *s; int err = 0; BT_DBG(""); down_read(&bnep_session_sem); s = __bnep_get_session(req->dst); if (s) { atomic_inc(&s->terminate); wake_up_process(s->task); } else err = -ENOENT; up_read(&bnep_session_sem); return err; } static void __bnep_copy_ci(struct bnep_conninfo *ci, struct bnep_session *s) { memset(ci, 0, sizeof(*ci)); memcpy(ci->dst, s->eh.h_source, ETH_ALEN); strcpy(ci->device, s->dev->name); ci->flags = s->flags; ci->state = s->state; ci->role = s->role; } int bnep_get_connlist(struct bnep_connlist_req *req) { struct bnep_session *s; int err = 0, n = 0; down_read(&bnep_session_sem); list_for_each_entry(s, &bnep_session_list, list) { struct bnep_conninfo ci; __bnep_copy_ci(&ci, s); if (copy_to_user(req->ci, &ci, sizeof(ci))) { err = -EFAULT; break; } if (++n >= req->cnum) break; req->ci++; } req->cnum = n; up_read(&bnep_session_sem); return err; } int bnep_get_conninfo(struct bnep_conninfo *ci) { struct bnep_session *s; int err = 0; down_read(&bnep_session_sem); s = __bnep_get_session(ci->dst); if (s) __bnep_copy_ci(ci, s); else err = -ENOENT; up_read(&bnep_session_sem); return err; } static int __init bnep_init(void) { char flt[50] = ""; #ifdef CONFIG_BT_BNEP_PROTO_FILTER strcat(flt, "protocol "); #endif #ifdef CONFIG_BT_BNEP_MC_FILTER strcat(flt, "multicast"); #endif BT_INFO("BNEP (Ethernet Emulation) ver %s", VERSION); if (flt[0]) BT_INFO("BNEP filters: %s", flt); bnep_sock_init(); return 0; } static void __exit bnep_exit(void) { bnep_sock_cleanup(); } module_init(bnep_init); module_exit(bnep_exit); module_param(compress_src, bool, 0644); MODULE_PARM_DESC(compress_src, "Compress sources headers"); module_param(compress_dst, bool, 0644); MODULE_PARM_DESC(compress_dst, "Compress destination headers"); MODULE_AUTHOR("Marcel Holtmann <marcel@holtmann.org>"); MODULE_DESCRIPTION("Bluetooth BNEP ver " VERSION); MODULE_VERSION(VERSION); MODULE_LICENSE("GPL"); MODULE_ALIAS("bt-proto-4");
./CrossVul/dataset_final_sorted/CWE-20/c/bad_2884_0
crossvul-cpp_data_bad_5107_0
/* packet-umts_fp.c * Routines for UMTS FP disassembly * * Martin Mathieson * * Wireshark - Network traffic analyzer * By Gerald Combs <gerald@wireshark.org> * Copyright 1998 Gerald Combs * * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "config.h" #include <epan/packet.h> #include <epan/expert.h> #include <epan/prefs.h> #include <epan/uat.h> #include <epan/conversation.h> #include <epan/addr_resolv.h> #include <epan/proto_data.h> #include <wsutil/crc7.h> /* For FP data header and control frame CRC. */ #include <wsutil/crc16-plain.h> /* For FP Payload CRC. */ #include <wsutil/crc11.h> /* For FP EDCH header CRC. */ #include "packet-umts_fp.h" #include "packet-nbap.h" #include "packet-rrc.h" /* The Frame Protocol (FP) is described in: * 3GPP TS 25.427 (for dedicated channels) * 3GPP TS 25.435 (for common/shared channels) * * TODO: * - IUR interface-specific formats * - do CRC verification before further parsing * - Set the logical channel properly for non multiplexed, channels * for channels that doesn't have the C/T flag! This should be based * on the RRC message RadioBearerSetup. */ void proto_register_fp(void); void proto_reg_handoff_fp(void); #define UMTS_FP_IPV4 1 #define UMTS_FP_IPV6 2 /* Initialize the protocol and registered fields. */ int proto_fp = -1; extern int proto_umts_mac; extern int proto_rlc; static int hf_fp_release = -1; static int hf_fp_release_version = -1; static int hf_fp_release_year = -1; static int hf_fp_release_month = -1; static int hf_fp_channel_type = -1; static int hf_fp_division = -1; static int hf_fp_direction = -1; static int hf_fp_ddi_config = -1; static int hf_fp_ddi_config_ddi = -1; static int hf_fp_ddi_config_macd_pdu_size = -1; static int hf_fp_header_crc = -1; static int hf_fp_ft = -1; static int hf_fp_cfn = -1; static int hf_fp_pch_cfn = -1; static int hf_fp_pch_toa = -1; static int hf_fp_cfn_control = -1; static int hf_fp_toa = -1; static int hf_fp_tfi = -1; static int hf_fp_usch_tfi = -1; static int hf_fp_cpch_tfi = -1; static int hf_fp_propagation_delay = -1; static int hf_fp_tb = -1; static int hf_fp_chan_zero_tbs = -1; static int hf_fp_received_sync_ul_timing_deviation = -1; static int hf_fp_pch_pi = -1; static int hf_fp_pch_tfi = -1; static int hf_fp_fach_tfi = -1; static int hf_fp_transmit_power_level = -1; static int hf_fp_paging_indication_bitmap = -1; static int hf_fp_pdsch_set_id = -1; static int hf_fp_rx_timing_deviation = -1; static int hf_fp_dch_e_rucch_flag = -1; static int hf_fp_dch_control_frame_type = -1; static int hf_fp_dch_rx_timing_deviation = -1; static int hf_fp_quality_estimate = -1; static int hf_fp_payload_crc = -1; static int hf_fp_edch_header_crc = -1; static int hf_fp_edch_fsn = -1; static int hf_fp_edch_subframe = -1; static int hf_fp_edch_number_of_subframes = -1; static int hf_fp_edch_harq_retransmissions = -1; static int hf_fp_edch_subframe_number = -1; static int hf_fp_edch_number_of_mac_es_pdus = -1; static int hf_fp_edch_ddi = -1; static int hf_fp_edch_subframe_header = -1; static int hf_fp_edch_number_of_mac_d_pdus = -1; static int hf_fp_edch_pdu_padding = -1; static int hf_fp_edch_tsn = -1; static int hf_fp_edch_mac_es_pdu = -1; static int hf_fp_edch_user_buffer_size = -1; static int hf_fp_edch_no_macid_sdus = -1; static int hf_fp_edch_number_of_mac_is_pdus = -1; static int hf_fp_edch_mac_is_pdu = -1; static int hf_fp_edch_e_rnti = -1; static int hf_fp_edch_macis_descriptors = -1; static int hf_fp_edch_macis_lchid = -1; static int hf_fp_edch_macis_length = -1; static int hf_fp_edch_macis_flag = -1; static int hf_fp_frame_seq_nr = -1; static int hf_fp_hsdsch_pdu_block_header = -1; /* static int hf_fp_hsdsch_pdu_block = -1; */ static int hf_fp_flush = -1; static int hf_fp_fsn_drt_reset = -1; static int hf_fp_drt_indicator = -1; static int hf_fp_fach_indicator = -1; static int hf_fp_total_pdu_blocks = -1; static int hf_fp_drt = -1; static int hf_fp_hrnti = -1; static int hf_fp_rach_measurement_result = -1; static int hf_fp_lchid = -1; static int hf_fp_pdu_length_in_block = -1; static int hf_fp_pdus_in_block = -1; static int hf_fp_cmch_pi = -1; static int hf_fp_user_buffer_size = -1; static int hf_fp_hsdsch_credits = -1; static int hf_fp_hsdsch_max_macd_pdu_len = -1; static int hf_fp_hsdsch_max_macdc_pdu_len = -1; static int hf_fp_hsdsch_interval = -1; static int hf_fp_hsdsch_calculated_rate = -1; static int hf_fp_hsdsch_unlimited_rate = -1; static int hf_fp_hsdsch_repetition_period = -1; static int hf_fp_hsdsch_data_padding = -1; static int hf_fp_hsdsch_new_ie_flags = -1; static int hf_fp_hsdsch_new_ie_flag[8] = {-1, -1, -1, -1, -1, -1, -1, -1}; static int hf_fp_hsdsch_drt = -1; static int hf_fp_hsdsch_entity = -1; static int hf_fp_hsdsch_physical_layer_category = -1; static int hf_fp_timing_advance = -1; static int hf_fp_num_of_pdu = -1; static int hf_fp_mac_d_pdu_len = -1; static int hf_fp_mac_d_pdu = -1; static int hf_fp_data = -1; static int hf_fp_crcis = -1; static int hf_fp_crci[8] = {-1, -1, -1, -1, -1, -1, -1, -1}; static int hf_fp_common_control_frame_type = -1; static int hf_fp_t1 = -1; static int hf_fp_t2 = -1; static int hf_fp_t3 = -1; static int hf_fp_ul_sir_target = -1; static int hf_fp_pusch_set_id = -1; static int hf_fp_activation_cfn = -1; static int hf_fp_duration = -1; static int hf_fp_power_offset = -1; static int hf_fp_code_number = -1; static int hf_fp_spreading_factor = -1; static int hf_fp_mc_info = -1; static int hf_fp_rach_new_ie_flags = -1; static int hf_fp_rach_new_ie_flag_unused[7] = {-1, -1, -1, -1, -1, -1, -1 }; static int hf_fp_rach_ext_propagation_delay_present = -1; static int hf_fp_rach_cell_portion_id_present = -1; static int hf_fp_rach_angle_of_arrival_present = -1; static int hf_fp_rach_ext_rx_sync_ul_timing_deviation_present = -1; static int hf_fp_rach_ext_rx_timing_deviation_present = -1; static int hf_fp_cell_portion_id = -1; static int hf_fp_ext_propagation_delay = -1; static int hf_fp_angle_of_arrival = -1; static int hf_fp_ext_received_sync_ul_timing_deviation = -1; static int hf_fp_radio_interface_parameter_update_flag[5] = {-1, -1, -1, -1, -1}; static int hf_fp_dpc_mode = -1; static int hf_fp_tpc_po = -1; static int hf_fp_multiple_rl_set_indicator = -1; static int hf_fp_max_ue_tx_pow = -1; static int hf_fp_congestion_status = -1; static int hf_fp_e_rucch_present = -1; static int hf_fp_extended_bits_present = -1; static int hf_fp_extended_bits = -1; static int hf_fp_spare_extension = -1; static int hf_fp_ul_setup_frame = -1; static int hf_fp_dl_setup_frame = -1; /* Subtrees. */ static int ett_fp = -1; static int ett_fp_release = -1; static int ett_fp_data = -1; static int ett_fp_crcis = -1; static int ett_fp_ddi_config = -1; static int ett_fp_edch_subframe_header = -1; static int ett_fp_edch_subframe = -1; static int ett_fp_edch_maces = -1; static int ett_fp_edch_macis_descriptors = -1; static int ett_fp_hsdsch_new_ie_flags = -1; static int ett_fp_rach_new_ie_flags = -1; static int ett_fp_hsdsch_pdu_block_header = -1; static expert_field ei_fp_hsdsch_common_experimental_support = EI_INIT; static expert_field ei_fp_hsdsch_common_t3_not_implemented = EI_INIT; static expert_field ei_fp_channel_type_unknown = EI_INIT; static expert_field ei_fp_ddi_not_defined = EI_INIT; static expert_field ei_fp_stop_hsdpa_transmission = EI_INIT; static expert_field ei_fp_hsdsch_entity_not_specified = EI_INIT; static expert_field ei_fp_expecting_tdd = EI_INIT; static expert_field ei_fp_bad_payload_checksum = EI_INIT; static expert_field ei_fp_e_rnti_t2_edch_frames = EI_INIT; static expert_field ei_fp_crci_no_subdissector = EI_INIT; static expert_field ei_fp_timing_adjustmentment_reported = EI_INIT; static expert_field ei_fp_mac_is_sdus_miscount = EI_INIT; static expert_field ei_fp_maybe_srb = EI_INIT; static expert_field ei_fp_transport_channel_type_unknown = EI_INIT; static expert_field ei_fp_unable_to_locate_ddi_entry = EI_INIT; static expert_field ei_fp_e_rnti_first_entry = EI_INIT; static expert_field ei_fp_bad_header_checksum = EI_INIT; static expert_field ei_fp_crci_error_bit_set_for_tb = EI_INIT; static expert_field ei_fp_spare_extension = EI_INIT; static expert_field ei_fp_no_per_frame_info = EI_INIT; static dissector_handle_t rlc_bcch_handle; static dissector_handle_t mac_fdd_dch_handle; static dissector_handle_t mac_fdd_rach_handle; static dissector_handle_t mac_fdd_fach_handle; static dissector_handle_t mac_fdd_pch_handle; static dissector_handle_t mac_fdd_edch_handle; static dissector_handle_t mac_fdd_edch_type2_handle; static dissector_handle_t mac_fdd_hsdsch_handle; static dissector_handle_t fp_handle; static proto_tree *top_level_tree = NULL; /* Variables used for preferences */ static gboolean preferences_call_mac_dissectors = TRUE; static gboolean preferences_show_release_info = TRUE; static gboolean preferences_payload_checksum = TRUE; static gboolean preferences_header_checksum = TRUE; #define UMTS_FP_USE_UAT 1 #ifdef UMTS_FP_USE_UAT /* UAT entry structure. */ typedef struct { guint8 protocol; gchar *srcIP; guint16 src_port; gchar *dstIP; guint16 dst_port; guint8 interface_type; guint8 division; guint8 rlc_mode; guint8 channel_type; } uat_umts_fp_ep_and_ch_record_t; static uat_umts_fp_ep_and_ch_record_t *uat_umts_fp_ep_and_ch_records = NULL; static uat_t *umts_fp_uat = NULL; static guint num_umts_fp_ep_and_ch_items = 0; #endif /* UMTS_FP_USE_UAT */ /* E-DCH (T1) channel header information */ struct edch_t1_subframe_info { guint8 subframe_number; guint8 number_of_mac_es_pdus; guint8 ddi[64]; guint16 number_of_mac_d_pdus[64]; }; /* E-DCH (T2) channel header information */ struct edch_t2_subframe_info { guint8 subframe_number; guint8 number_of_mac_is_pdus; guint8 number_of_mac_is_sdus[16]; guint8 mac_is_lchid[16][16]; guint16 mac_is_length[16][16]; }; static const value_string channel_type_vals[] = { { CHANNEL_RACH_FDD, "RACH_FDD" }, { CHANNEL_RACH_TDD, "RACH_TDD" }, { CHANNEL_FACH_FDD, "FACH_FDD" }, { CHANNEL_FACH_TDD, "FACH_TDD" }, { CHANNEL_DSCH_FDD, "DSCH_FDD" }, { CHANNEL_DSCH_TDD, "DSCH_TDD" }, { CHANNEL_USCH_TDD_384, "USCH_TDD_384" }, { CHANNEL_USCH_TDD_128, "USCH_TDD_128" }, { CHANNEL_PCH, "PCH" }, { CHANNEL_CPCH, "CPCH" }, { CHANNEL_BCH, "BCH" }, { CHANNEL_DCH, "DCH" }, { CHANNEL_HSDSCH, "HSDSCH" }, { CHANNEL_IUR_CPCHF, "IUR CPCHF" }, { CHANNEL_IUR_FACH, "IUR FACH" }, { CHANNEL_IUR_DSCH, "IUR DSCH" }, { CHANNEL_EDCH, "EDCH" }, { CHANNEL_RACH_TDD_128, "RACH_TDD_128" }, { CHANNEL_HSDSCH_COMMON, "HSDSCH-COMMON" }, { CHANNEL_HSDSCH_COMMON_T3, "HSDSCH-COMMON-T3" }, { CHANNEL_EDCH_COMMON, "EDCH-COMMON"}, { 0, NULL } }; static const value_string division_vals[] = { { Division_FDD, "FDD"}, { Division_TDD_384, "TDD-384"}, { Division_TDD_128, "TDD-128"}, { Division_TDD_768, "TDD-768"}, { 0, NULL } }; static const value_string data_control_vals[] = { { 0, "Data" }, { 1, "Control" }, { 0, NULL } }; static const value_string direction_vals[] = { { 0, "Downlink" }, { 1, "Uplink" }, { 0, NULL } }; static const value_string crci_vals[] = { { 0, "Correct" }, { 1, "Not correct" }, { 0, NULL } }; static const value_string paging_indication_vals[] = { { 0, "no PI-bitmap in payload" }, { 1, "PI-bitmap in payload" }, { 0, NULL } }; static const value_string spreading_factor_vals[] = { { 0, "4"}, { 1, "8"}, { 2, "16"}, { 3, "32"}, { 4, "64"}, { 5, "128"}, { 6, "256"}, { 0, NULL } }; static const value_string congestion_status_vals[] = { { 0, "No TNL congestion"}, { 1, "Reserved for future use"}, { 2, "TNL congestion - detected by delay build-up"}, { 3, "TNL congestion - detected by frame loss"}, { 0, NULL } }; static const value_string e_rucch_flag_vals[] = { { 0, "Conventional E-RUCCH reception" }, { 1, "TA Request reception" }, { 0, NULL } }; static const value_string hsdshc_mac_entity_vals[] = { { entity_not_specified, "Unspecified (assume MAC-hs)" }, { hs, "MAC-hs" }, { ehs, "MAC-ehs" }, { 0, NULL } }; /* TODO: add and use */ #if 0 static const value_string segmentation_status_vals[] = { { 0, "" }, { 1, "" }, { 2, "" }, { 3, "" }, { 0, NULL } }; #endif static const value_string lchid_vals[] = { { 0, "Logical Channel 1" }, { 1, "Logical Channel 2" }, { 2, "Logical Channel 3" }, { 3, "Logical Channel 4" }, { 4, "Logical Channel 5" }, { 5, "Logical Channel 6" }, { 6, "Logical Channel 7" }, { 7, "Logical Channel 8" }, { 8, "Logical Channel 9" }, { 9, "Logical Channel 10" }, { 10, "Logical Channel 11" }, { 11, "Logical Channel 12" }, { 12, "Logical Channel 13" }, { 13, "Logical Channel 14" }, { 14, "CCCH (SRB0)" }, { 15, "E-RNTI being included (FDD only)" }, { 0, NULL } }; /* Dedicated control types */ #define DCH_OUTER_LOOP_POWER_CONTROL 1 #define DCH_TIMING_ADJUSTMENT 2 #define DCH_DL_SYNCHRONISATION 3 #define DCH_UL_SYNCHRONISATION 4 #define DCH_DL_NODE_SYNCHRONISATION 6 #define DCH_UL_NODE_SYNCHRONISATION 7 #define DCH_RX_TIMING_DEVIATION 8 #define DCH_RADIO_INTERFACE_PARAMETER_UPDATE 9 #define DCH_TIMING_ADVANCE 10 #define DCH_TNL_CONGESTION_INDICATION 11 static const value_string dch_control_frame_type_vals[] = { { DCH_OUTER_LOOP_POWER_CONTROL, "OUTER LOOP POWER CONTROL" }, { DCH_TIMING_ADJUSTMENT, "TIMING ADJUSTMENT" }, { DCH_DL_SYNCHRONISATION, "DL SYNCHRONISATION" }, { DCH_UL_SYNCHRONISATION, "UL SYNCHRONISATION" }, { 5, "Reserved Value" }, { DCH_DL_NODE_SYNCHRONISATION, "DL NODE SYNCHRONISATION" }, { DCH_UL_NODE_SYNCHRONISATION, "UL NODE SYNCHRONISATION" }, { DCH_RX_TIMING_DEVIATION, "RX TIMING DEVIATION" }, { DCH_RADIO_INTERFACE_PARAMETER_UPDATE, "RADIO INTERFACE PARAMETER UPDATE" }, { DCH_TIMING_ADVANCE, "TIMING ADVANCE" }, { DCH_TNL_CONGESTION_INDICATION, "TNL CONGESTION INDICATION" }, { 0, NULL } }; /* Common channel control types */ #define COMMON_OUTER_LOOP_POWER_CONTROL 1 #define COMMON_TIMING_ADJUSTMENT 2 #define COMMON_DL_SYNCHRONISATION 3 #define COMMON_UL_SYNCHRONISATION 4 #define COMMON_DL_NODE_SYNCHRONISATION 6 #define COMMON_UL_NODE_SYNCHRONISATION 7 #define COMMON_DYNAMIC_PUSCH_ASSIGNMENT 8 #define COMMON_TIMING_ADVANCE 9 #define COMMON_HS_DSCH_Capacity_Request 10 #define COMMON_HS_DSCH_Capacity_Allocation 11 #define COMMON_HS_DSCH_Capacity_Allocation_Type_2 12 static const value_string common_control_frame_type_vals[] = { { COMMON_OUTER_LOOP_POWER_CONTROL, "OUTER LOOP POWER CONTROL" }, { COMMON_TIMING_ADJUSTMENT, "TIMING ADJUSTMENT" }, { COMMON_DL_SYNCHRONISATION, "DL SYNCHRONISATION" }, { COMMON_UL_SYNCHRONISATION, "UL SYNCHRONISATION" }, { 5, "Reserved Value" }, { COMMON_DL_NODE_SYNCHRONISATION, "DL NODE SYNCHRONISATION" }, { COMMON_UL_NODE_SYNCHRONISATION, "UL NODE SYNCHRONISATION" }, { COMMON_DYNAMIC_PUSCH_ASSIGNMENT, "DYNAMIC PUSCH ASSIGNMENT" }, { COMMON_TIMING_ADVANCE, "TIMING ADVANCE" }, { COMMON_HS_DSCH_Capacity_Request, "HS-DSCH Capacity Request" }, { COMMON_HS_DSCH_Capacity_Allocation, "HS-DSCH Capacity Allocation" }, { COMMON_HS_DSCH_Capacity_Allocation_Type_2, "HS-DSCH Capacity Allocation Type 2" }, { 0, NULL } }; /* 0 to 7*/ static const guint8 hsdsch_macdflow_id_rlc_map[] = { RLC_UM, /*0 SRB */ RLC_AM, /*1 Interactive PS*/ RLC_AM, /*2 Interatcive PS*/ RLC_UNKNOWN_MODE, /*3 ???*/ RLC_AM, /*4 Streaming PS*/ RLC_UNKNOWN_MODE, RLC_UNKNOWN_MODE, RLC_UNKNOWN_MODE }; /* Mapping hsdsch MACd-FlowId to MAC_CONTENT, basically flowid = 1 (0) => SRB*/ /* 1 to 8*/ static const guint8 hsdsch_macdflow_id_mac_content_map[] = { MAC_CONTENT_DCCH, /*1 SRB */ MAC_CONTENT_PS_DTCH, /*2 Interactive PS*/ MAC_CONTENT_PS_DTCH, /*3 Interatcive PS*/ RLC_UNKNOWN_MODE, /*4 ???*/ MAC_CONTENT_PS_DTCH, /*5 Streaming PS*/ RLC_UNKNOWN_MODE, RLC_UNKNOWN_MODE, RLC_UNKNOWN_MODE }; /* Make fake logical channel id's based on MACdFlow-ID's, * XXXX Bug 12121 expanded the number of entries to 8(+2), * not at all sure what the proper value should be 0xfF? */ static const guint8 fake_lchid_macd_flow[] = {1,9,14,11,0,12,0,0}; /* Dissect message parts */ static int dissect_tb_data(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, int offset, struct fp_info *p_fp_info, dissector_handle_t *data_handle, void *data); static int dissect_macd_pdu_data(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, int offset, guint16 length, guint16 number_of_pdus, struct fp_info *p_fp_info, void *data); static int dissect_macd_pdu_data_type_2(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, int offset, guint16 length, guint16 number_of_pdus, struct fp_info * fpi, void *data); static int dissect_crci_bits(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, fp_info *p_fp_info, int offset); static void dissect_spare_extension_and_crc(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint8 dch_crc_present, int offset, guint header_length); /* Dissect common control messages */ static int dissect_common_outer_loop_power_control(packet_info *pinfo, proto_tree *tree, tvbuff_t *tvb, int offset, struct fp_info *p_fp_info); static int dissect_common_timing_adjustment(packet_info *pinfo, proto_tree *tree, tvbuff_t *tvb, int offset, struct fp_info *p_fp_info); static int dissect_common_dl_node_synchronisation(packet_info *pinfo, proto_tree *tree, tvbuff_t *tvb, int offset); static int dissect_common_ul_node_synchronisation(packet_info *pinfo, proto_tree *tree, tvbuff_t *tvb, int offset); static int dissect_common_dl_synchronisation(packet_info *pinfo, proto_tree *tree, tvbuff_t *tvb, int offset, struct fp_info *p_fp_info); static int dissect_common_ul_synchronisation(packet_info *pinfo, proto_tree *tree, tvbuff_t *tvb, int offset, struct fp_info *p_fp_info); static int dissect_common_timing_advance(packet_info *pinfo, proto_tree *tree, tvbuff_t *tvb, int offset); static int dissect_hsdpa_capacity_request(packet_info *pinfo, proto_tree *tree, tvbuff_t *tvb, int offset); static int dissect_hsdpa_capacity_allocation(packet_info *pinfo, proto_tree *tree, tvbuff_t *tvb, int offset, struct fp_info *p_fp_info); static int dissect_hsdpa_capacity_allocation_type_2(packet_info *pinfo, proto_tree *tree, tvbuff_t *tvb, int offset); static void dissect_common_control(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, int offset, struct fp_info *p_fp_info); static int dissect_common_dynamic_pusch_assignment(packet_info *pinfo, proto_tree *tree, tvbuff_t *tvb, int offset); /* Dissect common channel types */ static void dissect_rach_channel_info(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, int offset, struct fp_info *p_fp_info, void *data); static void dissect_fach_channel_info(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, int offset, struct fp_info *p_fp_info, void *data); static void dissect_dsch_channel_info(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, int offset, struct fp_info *p_fp_info); static void dissect_usch_channel_info(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, int offset, struct fp_info *p_fp_info); static void dissect_pch_channel_info(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, int offset, struct fp_info *p_fp_info, void *data); static void dissect_cpch_channel_info(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, int offset, struct fp_info *p_fp_info); static void dissect_bch_channel_info(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, int offset, struct fp_info *p_fp_info); static void dissect_iur_dsch_channel_info(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, int offset, struct fp_info *p_fp_info); static void dissect_hsdsch_channel_info(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, int offset, struct fp_info *p_fp_info, void *data); static void dissect_hsdsch_type_2_channel_info(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, int offset, struct fp_info *p_fp_info, void *data); static void dissect_hsdsch_common_channel_info(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, int offset, struct fp_info *p_fp_info, void *data); /* Dissect DCH control messages */ static int dissect_dch_timing_adjustment(proto_tree *tree, packet_info *pinfo, tvbuff_t *tvb, int offset); static int dissect_dch_rx_timing_deviation(packet_info *pinfo, proto_tree *tree, tvbuff_t *tvb, int offset, struct fp_info *p_fp_info); static int dissect_dch_dl_synchronisation(proto_tree *tree, packet_info *pinfo, tvbuff_t *tvb, int offset); static int dissect_dch_ul_synchronisation(proto_tree *tree, packet_info *pinfo, tvbuff_t *tvb, int offset); static int dissect_dch_outer_loop_power_control(proto_tree *tree, packet_info *pinfo, tvbuff_t *tvb, int offset); static int dissect_dch_dl_node_synchronisation(proto_tree *tree, packet_info *pinfo, tvbuff_t *tvb, int offset); static int dissect_dch_ul_node_synchronisation(proto_tree *tree, packet_info *pinfo, tvbuff_t *tvb, int offset); static int dissect_dch_radio_interface_parameter_update(proto_tree *tree, packet_info *pinfo, tvbuff_t *tvb, int offset); static int dissect_dch_timing_advance(proto_tree *tree, packet_info *pinfo, tvbuff_t *tvb, int offset, struct fp_info *p_fp_info); static int dissect_dch_tnl_congestion_indication(proto_tree *tree, packet_info *pinfo, tvbuff_t *tvb, int offset); static void dissect_dch_control_frame(proto_tree *tree, packet_info *pinfo, tvbuff_t *tvb, int offset, struct fp_info *p_fp_info); /* Dissect a DCH channel */ static void dissect_dch_channel_info(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, int offset, struct fp_info *p_fp_info, void *data); /* Dissect dedicated channels */ static void dissect_e_dch_channel_info(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, int offset, struct fp_info *p_fp_info, gboolean is_common, rlc_info *rlcinf, void *data); static void dissect_e_dch_t2_or_common_channel_info(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, int offset, struct fp_info *p_fp_info, int number_of_subframes, gboolean is_common, guint16 header_crc, proto_item * header_crc_pi, void *data); /* Main dissection function */ static int dissect_fp(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void* data); /* * CRNC sends data downlink on uplink parameters. */ void set_umts_fp_conv_data(conversation_t *conversation, umts_fp_conversation_info_t *umts_fp_conversation_info) { if (conversation == NULL) { return; } conversation_add_proto_data(conversation, proto_fp, umts_fp_conversation_info); } static int get_tb_count(struct fp_info *p_fp_info) { int chan, tb_count = 0; for (chan = 0; chan < p_fp_info->num_chans; chan++) { tb_count += p_fp_info->chan_num_tbs[chan]; } return tb_count; } static gboolean verify_control_frame_crc(tvbuff_t * tvb, packet_info * pinfo, proto_item * pi, guint16 frame_crc) { guint8 crc = 0; guint8 * data = NULL; /* Get data. */ data = (guint8 *)tvb_memdup(wmem_packet_scope(), tvb, 0, tvb_reported_length(tvb)); /* Include only FT flag bit in CRC calculation. */ data[0] = data[0] & 1; /* Calculate crc7 sum. */ crc = crc7update(0, data, tvb_reported_length(tvb)); crc = crc7finalize(crc); /* finalize crc */ if (frame_crc == crc) { proto_item_append_text(pi, " [correct]"); return TRUE; } else { proto_item_append_text(pi, " [incorrect, should be 0x%x]", crc); expert_add_info(pinfo, pi, &ei_fp_bad_header_checksum); return FALSE; } } static gboolean verify_header_crc(tvbuff_t * tvb, packet_info * pinfo, proto_item * pi, guint16 header_crc, guint header_length) { guint8 crc = 0; guint8 * data = NULL; /* Get data of header with first byte removed. */ data = (guint8 *)tvb_memdup(wmem_packet_scope(), tvb, 1, header_length-1); /* Calculate crc7 sum. */ crc = crc7update(0, data, header_length-1); crc = crc7finalize(crc); /* finalize crc */ if (header_crc == crc) { proto_item_append_text(pi, " [correct]"); return TRUE; } else { proto_item_append_text(pi, " [incorrect, should be 0x%x]", crc); expert_add_info(pinfo, pi, &ei_fp_bad_header_checksum); return FALSE; } } static gboolean verify_header_crc_edch(tvbuff_t * tvb, packet_info * pinfo, proto_item * pi, guint16 header_crc, guint header_length) { guint16 crc = 0; guint8 * data = NULL; /* First create new subset of header with first byte removed. */ tvbuff_t * headtvb = tvb_new_subset_length(tvb, 1, header_length-1); /* Get data of header with first byte removed. */ data = (guint8 *)tvb_memdup(wmem_packet_scope(), headtvb, 0, header_length-1); /* Remove first 4 bits of the remaining data which are Header CRC cont. */ data[0] = data[0] & 0x0f; crc = crc11_307_noreflect_noxor(data, header_length-1); if (header_crc == crc) { proto_item_append_text(pi, " [correct]"); return TRUE; } else { proto_item_append_text(pi, " [incorrect, should be 0x%x]", crc); expert_add_info(pinfo, pi, &ei_fp_bad_header_checksum); return FALSE; } } /* Dissect the TBs of a UL data frame*/ static int dissect_tb_data(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, int offset, struct fp_info *p_fp_info, dissector_handle_t *data_handle, void *data) { int chan, num_tbs = 0; int bit_offset = 0; int crci_bit_offset = (offset+1)<<3; /* Current offset + Quality estimate of 1 byte at the end*/ guint data_bits = 0; guint8 crci_bit = 0; proto_item *tree_ti = NULL; proto_tree *data_tree = NULL; gboolean dissected = FALSE; if (tree) { /* Add data subtree */ tree_ti = proto_tree_add_item(tree, hf_fp_data, tvb, offset, -1, ENC_NA); proto_item_set_text(tree_ti, "TB data for %u chans", p_fp_info->num_chans); data_tree = proto_item_add_subtree(tree_ti, ett_fp_data); } /* Calculate offset to CRCI bits */ if (p_fp_info->is_uplink) { for (chan=0; chan < p_fp_info->num_chans; chan++) { int n; for (n=0; n < p_fp_info->chan_num_tbs[chan]; n++) { /* Advance bit offset */ crci_bit_offset += p_fp_info->chan_tf_size[chan]; /* Pad out to next byte */ if (crci_bit_offset % 8) { crci_bit_offset += (8 - (crci_bit_offset % 8)); } } } } /* Now for the TB data */ for (chan=0; chan < p_fp_info->num_chans; chan++) { int n; p_fp_info->cur_chan = chan; /*Set current channel?*/ /* Clearly show channels with no TBs */ if (p_fp_info->chan_num_tbs[chan] == 0) { proto_item *no_tb_ti = proto_tree_add_uint(data_tree, hf_fp_chan_zero_tbs, tvb, offset+(bit_offset/8), 0, chan+1); proto_item_append_text(no_tb_ti, " (of size %d)", p_fp_info->chan_tf_size[chan]); PROTO_ITEM_SET_GENERATED(no_tb_ti); } /* Show TBs from non-empty channels */ pinfo->fd->subnum = chan; /* set subframe number to current TB */ for (n=0; n < p_fp_info->chan_num_tbs[chan]; n++) { proto_item *ti; p_fp_info->cur_tb = chan; /*Set current transport block?*/ if (data_tree) { ti = proto_tree_add_item(data_tree, hf_fp_tb, tvb, offset + (bit_offset/8), ((bit_offset % 8) + p_fp_info->chan_tf_size[chan] + 7) / 8, ENC_NA); proto_item_set_text(ti, "TB (chan %u, tb %u, %u bits)", chan+1, n+1, p_fp_info->chan_tf_size[chan]); } if (preferences_call_mac_dissectors /*&& !rlc_is_ciphered(pinfo)*/ && data_handle && (p_fp_info->chan_tf_size[chan] > 0)) { tvbuff_t *next_tvb; proto_item *item; /* If this is DL we should not care about crci bits (since they don't exists)*/ if (p_fp_info->is_uplink) { if ( p_fp_info->channel == CHANNEL_RACH_FDD) { /*In RACH we don't have any QE field, hence go back 8 bits.*/ crci_bit = tvb_get_bits8(tvb, crci_bit_offset+n-8, 1); item = proto_tree_add_item(data_tree, hf_fp_crci[n%8], tvb, (crci_bit_offset+n-8)/8, 1, ENC_BIG_ENDIAN); PROTO_ITEM_SET_GENERATED(item); } else { crci_bit = tvb_get_bits8(tvb, crci_bit_offset+n, 1); item = proto_tree_add_item(data_tree, hf_fp_crci[n%8], tvb, (crci_bit_offset+n)/8, 1, ENC_BIG_ENDIAN); PROTO_ITEM_SET_GENERATED(item); } } if (crci_bit == 0 || !p_fp_info->is_uplink) { next_tvb = tvb_new_subset(tvb, offset + bit_offset/8, ((bit_offset % 8) + p_fp_info->chan_tf_size[chan] + 7) / 8, -1); /****************/ /* TODO: maybe this decision can be based only on info available in fp_info */ call_dissector_with_data(*data_handle, next_tvb, pinfo, top_level_tree, data); dissected = TRUE; } else { proto_tree_add_expert(tree, pinfo, &ei_fp_crci_no_subdissector, tvb, offset + bit_offset/8, ((bit_offset % 8) + p_fp_info->chan_tf_size[chan] + 7) / 8); } } num_tbs++; /* Advance bit offset */ bit_offset += p_fp_info->chan_tf_size[chan]; data_bits += p_fp_info->chan_tf_size[chan]; /* Pad out to next byte */ if (bit_offset % 8) { bit_offset += (8 - (bit_offset % 8)); } } } if (dissected == FALSE) { col_append_fstr(pinfo->cinfo, COL_INFO, "(%u bits in %u tbs)", data_bits, num_tbs); } /* Data tree should cover entire length */ if (data_tree) { proto_item_set_len(tree_ti, bit_offset/8); proto_item_append_text(tree_ti, " (%u bits in %u tbs)", data_bits, num_tbs); } /* Move offset past TBs (we know it's already padded out to next byte) */ offset += (bit_offset / 8); return offset; } /* Dissect the MAC-d PDUs of an HS-DSCH (type 1) frame. Length is in bits, and payload is offset by 4 bits of padding */ static int dissect_macd_pdu_data(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, int offset, guint16 length, guint16 number_of_pdus, struct fp_info *p_fp_info, void *data) { int pdu; int bit_offset = 0; proto_item *pdus_ti = NULL; proto_tree *data_tree = NULL; gboolean dissected = FALSE; /* Add data subtree */ if (tree) { pdus_ti = proto_tree_add_item(tree, hf_fp_data, tvb, offset, -1, ENC_NA); proto_item_set_text(pdus_ti, "%u MAC-d PDUs of %u bits", number_of_pdus, length); data_tree = proto_item_add_subtree(pdus_ti, ett_fp_data); } /* Now for the PDUs */ for (pdu=0; pdu < number_of_pdus; pdu++) { proto_item *pdu_ti; if (data_tree) { /* Show 4 bits padding at start of PDU */ proto_tree_add_item(data_tree, hf_fp_hsdsch_data_padding, tvb, offset+(bit_offset/8), 1, ENC_BIG_ENDIAN); } bit_offset += 4; /* Data bytes! */ if (data_tree) { pinfo->fd->subnum = pdu; /* set subframe number to current TB */ p_fp_info->cur_tb = pdu; /*Set TB (PDU) index correctly*/ pdu_ti = proto_tree_add_item(data_tree, hf_fp_mac_d_pdu, tvb, offset + (bit_offset/8), ((bit_offset % 8) + length + 7) / 8, ENC_NA); proto_item_set_text(pdu_ti, "MAC-d PDU (PDU %u)", pdu+1); } if (preferences_call_mac_dissectors /*&& !rlc_is_ciphered(pinfo)*/) { tvbuff_t *next_tvb; next_tvb = tvb_new_subset(tvb, offset + bit_offset/8, ((bit_offset % 8) + length + 7)/8, -1); call_dissector_with_data(mac_fdd_hsdsch_handle, next_tvb, pinfo, top_level_tree, data); dissected = TRUE; } /* Advance bit offset */ bit_offset += length; /* Pad out to next byte */ if (bit_offset % 8) { bit_offset += (8 - (bit_offset % 8)); } } /* Data tree should cover entire length */ proto_item_set_len(pdus_ti, bit_offset/8); /* Move offset past PDUs (we know it's already padded out to next byte) */ offset += (bit_offset / 8); /* Show summary in info column */ if (dissected == FALSE) { col_append_fstr(pinfo->cinfo, COL_INFO, " %u PDUs of %u bits", number_of_pdus, length); } return offset; } /* Dissect the MAC-d PDUs of an HS-DSCH (type 2) frame. Length is in bytes, and payload is byte-aligned (no padding) */ static int dissect_macd_pdu_data_type_2(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, int offset, guint16 length, guint16 number_of_pdus, struct fp_info *fpi, void *data) { int pdu; proto_item *pdus_ti = NULL; proto_tree *data_tree = NULL; int first_offset = offset; gboolean dissected = FALSE; /* Add data subtree */ if (tree) { pdus_ti = proto_tree_add_item(tree, hf_fp_data, tvb, offset, -1, ENC_NA); proto_item_set_text(pdus_ti, "%u MAC-d PDUs of %u bytes", number_of_pdus, length); data_tree = proto_item_add_subtree(pdus_ti, ett_fp_data); } /* Now for the PDUs */ for (pdu=0; pdu < number_of_pdus; pdu++) { proto_item *pdu_ti; /* Data bytes! */ if (data_tree) { pdu_ti = proto_tree_add_item(data_tree, hf_fp_mac_d_pdu, tvb, offset, length, ENC_NA); proto_item_set_text(pdu_ti, "MAC-d PDU (PDU %u)", pdu+1); } if (preferences_call_mac_dissectors /*&& !rlc_is_ciphered(pinfo)*/) { tvbuff_t *next_tvb = tvb_new_subset(tvb, offset, length, -1); fpi->cur_tb = pdu; /*Set proper pdu index for MAC and higher layers*/ call_dissector_with_data(mac_fdd_hsdsch_handle, next_tvb, pinfo, top_level_tree, data); dissected = TRUE; } /* Advance offset */ offset += length; } /* Data tree should cover entire length */ proto_item_set_len(pdus_ti, offset-first_offset); /* Show summary in info column */ if (!dissected) { col_append_fstr(pinfo->cinfo, COL_INFO, " %u PDUs of %u bits", number_of_pdus, length*8); } return offset; } /* Dissect CRCI bits (uplink) */ static int dissect_crci_bits(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, fp_info *p_fp_info, int offset) { int n, num_tbs; proto_item *ti = NULL; proto_tree *crcis_tree = NULL; guint errors = 0; num_tbs = get_tb_count(p_fp_info); /* Add CRCIs subtree */ if (tree) { ti = proto_tree_add_item(tree, hf_fp_crcis, tvb, offset, (num_tbs+7)/8, ENC_NA); proto_item_set_text(ti, "CRCI bits for %u tbs", num_tbs); crcis_tree = proto_item_add_subtree(ti, ett_fp_crcis); } /* CRCIs */ for (n=0; n < num_tbs; n++) { int bit = (tvb_get_guint8(tvb, offset+(n/8)) >> (7-(n%8))) & 0x01; proto_tree_add_item(crcis_tree, hf_fp_crci[n%8], tvb, offset+(n/8), 1, ENC_BIG_ENDIAN); if (bit == 1) { errors++; expert_add_info(pinfo, ti, &ei_fp_crci_error_bit_set_for_tb); } } if (tree) { /* Highlight range of bytes covered by indicator bits */ proto_item_set_len(ti, (num_tbs+7) / 8); /* Show error count in root text */ proto_item_append_text(ti, " (%u errors)", errors); } offset += ((num_tbs+7) / 8); return offset; } static void dissect_spare_extension_and_crc(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint8 dch_crc_present, int offset, guint header_length) { int crc_size = 0; int remain = tvb_captured_length_remaining(tvb, offset); /* Payload CRC (optional) */ if ((dch_crc_present == 1) || ((dch_crc_present == 2) && (remain >= 2))) { crc_size = 2; } if (remain > crc_size) { proto_item *ti; ti = proto_tree_add_item(tree, hf_fp_spare_extension, tvb, offset, remain-crc_size, ENC_NA); proto_item_append_text(ti, " (%u octets)", remain-crc_size); expert_add_info_format(pinfo, ti, &ei_fp_spare_extension, "Spare Extension present (%u bytes)", remain-crc_size); offset += remain-crc_size; } if (crc_size) { proto_item * pi = proto_tree_add_item(tree, hf_fp_payload_crc, tvb, offset, crc_size, ENC_BIG_ENDIAN); if (preferences_payload_checksum) { guint16 calc_crc, read_crc; guint8 * data = (guint8 *)tvb_memdup(wmem_packet_scope(), tvb, header_length, offset-header_length); calc_crc = crc16_8005_noreflect_noxor(data, offset-header_length); read_crc = tvb_get_bits16(tvb, offset*8, 16, ENC_BIG_ENDIAN); if (calc_crc == read_crc) { proto_item_append_text(pi, " [correct]"); } else { proto_item_append_text(pi, " [incorrect, should be 0x%x]", calc_crc); expert_add_info(pinfo, pi, &ei_fp_bad_payload_checksum); } } } } /***********************************************************/ /* Common control message types */ static int dissect_common_outer_loop_power_control(packet_info *pinfo, proto_tree *tree, tvbuff_t *tvb, int offset, struct fp_info *p_fp_info _U_) { return dissect_dch_outer_loop_power_control(tree, pinfo, tvb, offset); } static int dissect_common_timing_adjustment(packet_info *pinfo, proto_tree *tree, tvbuff_t *tvb, int offset, struct fp_info *p_fp_info) { if (p_fp_info->channel != CHANNEL_PCH) { guint8 cfn; gint16 toa; /* CFN control */ cfn = tvb_get_guint8(tvb, offset); proto_tree_add_item(tree, hf_fp_cfn_control, tvb, offset, 1, ENC_BIG_ENDIAN); offset++; /* ToA */ toa = tvb_get_ntohs(tvb, offset); proto_tree_add_item(tree, hf_fp_toa, tvb, offset, 2, ENC_BIG_ENDIAN); offset += 2; col_append_fstr(pinfo->cinfo, COL_INFO, " CFN=%u, ToA=%d", cfn, toa); } else { guint16 cfn; gint32 toa; /* PCH CFN is 12 bits */ cfn = (tvb_get_ntohs(tvb, offset) >> 4); proto_tree_add_item(tree, hf_fp_pch_cfn, tvb, offset, 2, ENC_BIG_ENDIAN); offset += 2; /* 4 bits of padding follow... */ /* 20 bits of ToA (followed by 4 padding bits) */ toa = ((int)(tvb_get_ntoh24(tvb, offset) << 8)) / 4096; proto_tree_add_int(tree, hf_fp_pch_toa, tvb, offset, 3, toa); offset += 3; col_append_fstr(pinfo->cinfo, COL_INFO, " CFN=%u, ToA=%d", cfn, toa); } return offset; } static int dissect_common_dl_node_synchronisation(packet_info *pinfo, proto_tree *tree, tvbuff_t *tvb, int offset) { /* T1 (3 bytes) */ guint32 t1 = tvb_get_ntoh24(tvb, offset); proto_tree_add_item(tree, hf_fp_t1, tvb, offset, 3, ENC_BIG_ENDIAN); offset += 3; col_append_fstr(pinfo->cinfo, COL_INFO, " T1=%u", t1); return offset; } static int dissect_common_ul_node_synchronisation(packet_info *pinfo, proto_tree *tree, tvbuff_t *tvb, int offset) { guint32 t1, t2, t3; /* T1 (3 bytes) */ t1 = tvb_get_ntoh24(tvb, offset); proto_tree_add_item(tree, hf_fp_t1, tvb, offset, 3, ENC_BIG_ENDIAN); offset += 3; /* T2 (3 bytes) */ t2 = tvb_get_ntoh24(tvb, offset); proto_tree_add_item(tree, hf_fp_t2, tvb, offset, 3, ENC_BIG_ENDIAN); offset += 3; /* T3 (3 bytes) */ t3 = tvb_get_ntoh24(tvb, offset); proto_tree_add_item(tree, hf_fp_t3, tvb, offset, 3, ENC_BIG_ENDIAN); offset += 3; col_append_fstr(pinfo->cinfo, COL_INFO, " T1=%u T2=%u, T3=%u", t1, t2, t3); return offset; } static int dissect_common_dl_synchronisation(packet_info *pinfo, proto_tree *tree, tvbuff_t *tvb, int offset, struct fp_info *p_fp_info) { guint16 cfn; if (p_fp_info->channel != CHANNEL_PCH) { /* CFN control */ cfn = tvb_get_guint8(tvb, offset); proto_tree_add_item(tree, hf_fp_cfn_control, tvb, offset, 1, ENC_BIG_ENDIAN); offset++; } else { /* PCH CFN is 12 bits */ cfn = (tvb_get_ntohs(tvb, offset) >> 4); proto_tree_add_item(tree, hf_fp_pch_cfn, tvb, offset, 2, ENC_BIG_ENDIAN); /* 4 bits of padding follow... */ offset += 2; } col_append_fstr(pinfo->cinfo, COL_INFO, " CFN=%u", cfn); return offset; } static int dissect_common_ul_synchronisation(packet_info *pinfo, proto_tree *tree, tvbuff_t *tvb, int offset, struct fp_info *p_fp_info) { return dissect_common_timing_adjustment(pinfo, tree, tvb, offset, p_fp_info); } static int dissect_common_timing_advance(packet_info *pinfo, proto_tree *tree, tvbuff_t *tvb, int offset) { guint8 cfn; guint16 timing_advance; /* CFN control */ cfn = tvb_get_guint8(tvb, offset); proto_tree_add_item(tree, hf_fp_cfn_control, tvb, offset, 1, ENC_BIG_ENDIAN); offset++; /* Timing Advance */ timing_advance = (tvb_get_guint8(tvb, offset) & 0x3f) * 4; proto_tree_add_uint(tree, hf_fp_timing_advance, tvb, offset, 1, timing_advance); offset++; col_append_fstr(pinfo->cinfo, COL_INFO, " CFN = %u, TA = %u", cfn, timing_advance); return offset; } static int dissect_hsdpa_capacity_request(packet_info *pinfo, proto_tree *tree, tvbuff_t *tvb, int offset) { guint8 priority; guint16 user_buffer_size; /* CmCH-PI */ priority = (tvb_get_guint8(tvb, offset) & 0x0f); proto_tree_add_item(tree, hf_fp_cmch_pi, tvb, offset, 1, ENC_BIG_ENDIAN); offset++; /* User buffer size */ user_buffer_size = tvb_get_ntohs(tvb, offset); proto_tree_add_item(tree, hf_fp_user_buffer_size, tvb, offset, 2, ENC_BIG_ENDIAN); offset += 2; col_append_fstr(pinfo->cinfo, COL_INFO, " CmCH-PI=%u User-Buffer-Size=%u", priority, user_buffer_size); return offset; } static int dissect_hsdpa_capacity_allocation(packet_info *pinfo, proto_tree *tree, tvbuff_t *tvb, int offset, struct fp_info *p_fp_info) { proto_item *ti; proto_item *rate_ti; guint16 max_pdu_length; guint8 repetition_period; guint8 interval; guint64 credits; /* Congestion status (introduced sometime during R6...) */ if ((p_fp_info->release == 6) || (p_fp_info->release == 7)) { proto_tree_add_bits_item(tree, hf_fp_congestion_status, tvb, offset*8 + 2, 2, ENC_BIG_ENDIAN); } /* CmCH-PI */ proto_tree_add_item(tree, hf_fp_cmch_pi, tvb, offset, 1, ENC_BIG_ENDIAN); offset++; /* Max MAC-d PDU length (13 bits) */ max_pdu_length = tvb_get_ntohs(tvb, offset) >> 3; proto_tree_add_item(tree, hf_fp_hsdsch_max_macd_pdu_len, tvb, offset, 2, ENC_BIG_ENDIAN); offset++; /* HS-DSCH credits (11 bits) */ ti = proto_tree_add_bits_ret_val(tree, hf_fp_hsdsch_credits, tvb, offset*8 + 5, 11, &credits, ENC_BIG_ENDIAN); offset += 2; /* Interesting values */ if (credits == 0) { proto_item_append_text(ti, " (stop transmission)"); expert_add_info(pinfo, ti, &ei_fp_stop_hsdpa_transmission); } if (credits == 2047) { proto_item_append_text(ti, " (unlimited)"); } /* HS-DSCH Interval */ interval = tvb_get_guint8(tvb, offset); ti = proto_tree_add_uint(tree, hf_fp_hsdsch_interval, tvb, offset, 1, interval*10); offset++; if (interval == 0) { proto_item_append_text(ti, " (none of the credits shall be used)"); } /* HS-DSCH Repetition period */ repetition_period = tvb_get_guint8(tvb, offset); ti = proto_tree_add_item(tree, hf_fp_hsdsch_repetition_period, tvb, offset, 1, ENC_BIG_ENDIAN); offset++; if (repetition_period == 0) { proto_item_append_text(ti, " (unlimited repetition period)"); } /* Calculated and show effective rate enabled */ if (credits == 2047) { rate_ti = proto_tree_add_item(tree, hf_fp_hsdsch_unlimited_rate, tvb, 0, 0, ENC_NA); PROTO_ITEM_SET_GENERATED(rate_ti); } else { if (interval != 0) { /* Cast on credits is safe, since we know it won't exceed 10^11 */ rate_ti = proto_tree_add_uint(tree, hf_fp_hsdsch_calculated_rate, tvb, 0, 0, (guint16)credits * max_pdu_length * (1000 / (interval*10))); PROTO_ITEM_SET_GENERATED(rate_ti); } } col_append_fstr(pinfo->cinfo, COL_INFO, " Max-PDU-len=%u Credits=%u Interval=%u Rep-Period=%u", max_pdu_length, (guint16)credits, interval, repetition_period); return offset; } static int dissect_hsdpa_capacity_allocation_type_2(packet_info *pinfo, proto_tree *tree, tvbuff_t *tvb, int offset) { proto_item *ti; proto_item *rate_ti; guint16 max_pdu_length; guint8 repetition_period; guint8 interval; guint16 credits; /* Congestion status */ proto_tree_add_bits_item(tree, hf_fp_congestion_status, tvb, offset*8 + 2, 2, ENC_BIG_ENDIAN); /* CmCH-PI */ proto_tree_add_item(tree, hf_fp_cmch_pi, tvb, offset, 1, ENC_BIG_ENDIAN); offset++; /* 5 spare bits follow here */ /* Max MAC-d/c PDU length (11 bits) */ max_pdu_length = tvb_get_ntohs(tvb, offset) & 0x7ff; proto_tree_add_item(tree, hf_fp_hsdsch_max_macdc_pdu_len, tvb, offset, 2, ENC_BIG_ENDIAN); offset += 2; /* HS-DSCH credits (16 bits) */ credits = (tvb_get_ntohs(tvb, offset)); ti = proto_tree_add_uint(tree, hf_fp_hsdsch_credits, tvb, offset, 2, credits); offset += 2; /* Interesting values */ if (credits == 0) { proto_item_append_text(ti, " (stop transmission)"); expert_add_info(pinfo, ti, &ei_fp_stop_hsdpa_transmission); } if (credits == 65535) { proto_item_append_text(ti, " (unlimited)"); } /* HS-DSCH Interval */ interval = tvb_get_guint8(tvb, offset); ti = proto_tree_add_uint(tree, hf_fp_hsdsch_interval, tvb, offset, 1, interval*10); offset++; if (interval == 0) { proto_item_append_text(ti, " (none of the credits shall be used)"); } /* HS-DSCH Repetition period */ repetition_period = tvb_get_guint8(tvb, offset); ti = proto_tree_add_item(tree, hf_fp_hsdsch_repetition_period, tvb, offset, 1, ENC_BIG_ENDIAN); offset++; if (repetition_period == 0) { proto_item_append_text(ti, " (unlimited repetition period)"); } /* Calculated and show effective rate enabled */ if (credits == 65535) { rate_ti = proto_tree_add_item(tree, hf_fp_hsdsch_unlimited_rate, tvb, 0, 0, ENC_NA); PROTO_ITEM_SET_GENERATED(rate_ti); } else { if (interval != 0) { rate_ti = proto_tree_add_uint(tree, hf_fp_hsdsch_calculated_rate, tvb, 0, 0, credits * max_pdu_length * (1000 / (interval*10))); PROTO_ITEM_SET_GENERATED(rate_ti); } } col_append_fstr(pinfo->cinfo, COL_INFO, " Max-PDU-len=%u Credits=%u Interval=%u Rep-Period=%u", max_pdu_length, credits, interval, repetition_period); return offset; } static int dissect_common_dynamic_pusch_assignment(packet_info *pinfo, proto_tree *tree, tvbuff_t *tvb, int offset) { guint8 pusch_set_id; guint8 activation_cfn; guint8 duration; /* PUSCH Set Id */ pusch_set_id = tvb_get_guint8(tvb, offset); proto_tree_add_item(tree, hf_fp_pusch_set_id, tvb, offset, 1, ENC_BIG_ENDIAN); offset++; /* Activation CFN */ activation_cfn = tvb_get_guint8(tvb, offset); proto_tree_add_item(tree, hf_fp_activation_cfn, tvb, offset, 1, ENC_BIG_ENDIAN); offset++; /* Duration */ duration = tvb_get_guint8(tvb, offset) * 10; proto_tree_add_uint(tree, hf_fp_duration, tvb, offset, 1, duration); offset++; col_append_fstr(pinfo->cinfo, COL_INFO, " PUSCH Set Id=%u Activation CFN=%u Duration=%u", pusch_set_id, activation_cfn, duration); return offset; } /* Dissect the control part of a common channel message */ static void dissect_common_control(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, int offset, struct fp_info *p_fp_info) { /* Common control frame type */ guint8 control_frame_type = tvb_get_guint8(tvb, offset); proto_tree_add_item(tree, hf_fp_common_control_frame_type, tvb, offset, 1, ENC_BIG_ENDIAN); offset++; col_append_str(pinfo->cinfo, COL_INFO, val_to_str_const(control_frame_type, common_control_frame_type_vals, "Unknown")); /* Frame-type specific dissection */ switch (control_frame_type) { case COMMON_OUTER_LOOP_POWER_CONTROL: /*offset =*/ dissect_common_outer_loop_power_control(pinfo, tree, tvb, offset, p_fp_info); break; case COMMON_TIMING_ADJUSTMENT: /*offset =*/ dissect_common_timing_adjustment(pinfo, tree, tvb, offset, p_fp_info); break; case COMMON_DL_SYNCHRONISATION: /*offset =*/ dissect_common_dl_synchronisation(pinfo, tree, tvb, offset, p_fp_info); break; case COMMON_UL_SYNCHRONISATION: /*offset =*/ dissect_common_ul_synchronisation(pinfo, tree, tvb, offset, p_fp_info); break; case COMMON_DL_NODE_SYNCHRONISATION: /*offset =*/ dissect_common_dl_node_synchronisation(pinfo, tree, tvb, offset); break; case COMMON_UL_NODE_SYNCHRONISATION: /*offset =*/ dissect_common_ul_node_synchronisation(pinfo, tree, tvb, offset); break; case COMMON_DYNAMIC_PUSCH_ASSIGNMENT: /*offset =*/ dissect_common_dynamic_pusch_assignment(pinfo, tree, tvb, offset); break; case COMMON_TIMING_ADVANCE: /*offset =*/ dissect_common_timing_advance(pinfo, tree, tvb, offset); break; case COMMON_HS_DSCH_Capacity_Request: /*offset =*/ dissect_hsdpa_capacity_request(pinfo, tree, tvb, offset); break; case COMMON_HS_DSCH_Capacity_Allocation: /*offset =*/ dissect_hsdpa_capacity_allocation(pinfo, tree, tvb, offset, p_fp_info); break; case COMMON_HS_DSCH_Capacity_Allocation_Type_2: /*offset =*/ dissect_hsdpa_capacity_allocation_type_2(pinfo, tree, tvb, offset); break; default: break; } /* There is no Spare Extension nor payload crc in common control!? */ /* dissect_spare_extension_and_crc(tvb, pinfo, tree, 0, offset); */ } /**************************/ /* Dissect a RACH channel */ static void dissect_rach_channel_info(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, int offset, struct fp_info *p_fp_info, void *data) { gboolean is_control_frame; guint16 header_crc = 0; proto_item * header_crc_pi = NULL; guint header_length = 0; /* Header CRC */ header_crc = tvb_get_bits8(tvb, 0, 7); header_crc_pi = proto_tree_add_item(tree, hf_fp_header_crc, tvb, offset, 1, ENC_BIG_ENDIAN); /* Frame Type */ is_control_frame = tvb_get_guint8(tvb, offset) & 0x01; proto_tree_add_item(tree, hf_fp_ft, tvb, offset, 1, ENC_BIG_ENDIAN); offset++; col_append_str(pinfo->cinfo, COL_INFO, is_control_frame ? " [Control] " : " [Data] "); if (is_control_frame) { dissect_common_control(tvb, pinfo, tree, offset, p_fp_info); /* For control frame the header CRC is actually frame CRC covering all * bytes except the first */ if (preferences_header_checksum) { verify_control_frame_crc(tvb, pinfo, header_crc_pi, header_crc); } } else { guint8 cfn; guint32 propagation_delay = 0; proto_item *propagation_delay_ti = NULL; guint32 received_sync_ul_timing_deviation = 0; proto_item *received_sync_ul_timing_deviation_ti = NULL; proto_item *rx_timing_deviation_ti = NULL; guint16 rx_timing_deviation = 0; /* DATA */ /* CFN */ cfn = tvb_get_guint8(tvb, offset); proto_tree_add_item(tree, hf_fp_cfn, tvb, offset, 1, ENC_BIG_ENDIAN); offset++; col_append_fstr(pinfo->cinfo, COL_INFO, "CFN=%03u ", cfn); /* TFI */ proto_tree_add_item(tree, hf_fp_tfi, tvb, offset, 1, ENC_BIG_ENDIAN); offset++; if (p_fp_info->channel == CHANNEL_RACH_FDD) { /* Propagation delay */ propagation_delay = tvb_get_guint8(tvb, offset); propagation_delay_ti = proto_tree_add_uint(tree, hf_fp_propagation_delay, tvb, offset, 1, propagation_delay*3); offset++; } /* Should be TDD 3.84 or 7.68 */ if (p_fp_info->channel == CHANNEL_RACH_TDD) { /* Rx Timing Deviation */ rx_timing_deviation = tvb_get_guint8(tvb, offset); rx_timing_deviation_ti = proto_tree_add_item(tree, hf_fp_rx_timing_deviation, tvb, offset, 1, ENC_BIG_ENDIAN); offset++; } if (p_fp_info->channel == CHANNEL_RACH_TDD_128) { /* Received SYNC UL Timing Deviation */ received_sync_ul_timing_deviation = tvb_get_guint8(tvb, offset); received_sync_ul_timing_deviation_ti = proto_tree_add_item(tree, hf_fp_received_sync_ul_timing_deviation, tvb, offset, 1, ENC_BIG_ENDIAN); offset++; } header_length = offset; /* TB data */ offset = dissect_tb_data(tvb, pinfo, tree, offset, p_fp_info, &mac_fdd_rach_handle, data); /* CRCIs */ offset = dissect_crci_bits(tvb, pinfo, tree, p_fp_info, offset); /* Info introduced in R6 */ /* only check if it looks as if they are present */ if (((p_fp_info->release == 6) || (p_fp_info->release == 7)) && (tvb_reported_length_remaining(tvb, offset) > 2)) { int n; guint8 flags; /* guint8 flag_bytes = 0; */ gboolean cell_portion_id_present = FALSE; gboolean ext_propagation_delay_present = FALSE; gboolean angle_of_arrival_present = FALSE; gboolean ext_rx_sync_ul_timing_deviation_present = FALSE; gboolean ext_rx_timing_deviation_present = FALSE; /* New IE flags (assume mandatory for now) */ do { proto_item *new_ie_flags_ti; proto_tree *new_ie_flags_tree; guint ies_found = 0; /* Add new IE flags subtree */ new_ie_flags_ti = proto_tree_add_string_format(tree, hf_fp_rach_new_ie_flags, tvb, offset, 1, "", "New IE flags"); new_ie_flags_tree = proto_item_add_subtree(new_ie_flags_ti, ett_fp_rach_new_ie_flags); /* Read next byte */ flags = tvb_get_guint8(tvb, offset); /* flag_bytes++ */ /* Dissect individual bits */ for (n=0; n < 8; n++) { switch (n) { case 6: switch (p_fp_info->division) { case Division_FDD: /* Ext propagation delay */ ext_propagation_delay_present = TRUE; proto_tree_add_item(new_ie_flags_tree, hf_fp_rach_ext_propagation_delay_present, tvb, offset, 1, ENC_BIG_ENDIAN); break; case Division_TDD_128: /* Ext Rx Sync UL Timing */ ext_rx_sync_ul_timing_deviation_present = TRUE; proto_tree_add_item(new_ie_flags_tree, hf_fp_rach_ext_rx_sync_ul_timing_deviation_present, tvb, offset, 1, ENC_BIG_ENDIAN); break; default: /* Not defined */ proto_tree_add_item(new_ie_flags_tree, hf_fp_rach_new_ie_flag_unused[6], tvb, offset, 1, ENC_BIG_ENDIAN); break; } break; case 7: switch (p_fp_info->division) { case Division_FDD: /* Cell Portion ID */ cell_portion_id_present = TRUE; proto_tree_add_item(new_ie_flags_tree, hf_fp_rach_cell_portion_id_present, tvb, offset, 1, ENC_BIG_ENDIAN); break; case Division_TDD_128: /* AOA */ angle_of_arrival_present = TRUE; proto_tree_add_item(new_ie_flags_tree, hf_fp_rach_angle_of_arrival_present, tvb, offset, 1, ENC_BIG_ENDIAN); break; case Division_TDD_384: case Division_TDD_768: /* Extended Rx Timing Deviation */ ext_rx_timing_deviation_present = TRUE; proto_tree_add_item(new_ie_flags_tree, hf_fp_rach_ext_rx_timing_deviation_present, tvb, offset, 1, ENC_BIG_ENDIAN); break; } break; default: /* No defined meanings */ /* Visual Studio Code Analyzer wrongly thinks n can be 7 here. It can't */ proto_tree_add_item(new_ie_flags_tree, hf_fp_rach_new_ie_flag_unused[n], tvb, offset, 1, ENC_BIG_ENDIAN); break; } if ((flags >> (7-n)) & 0x01) { ies_found++; } } offset++; proto_item_append_text(new_ie_flags_ti, " (%u IEs found)", ies_found); /* Last bit set will indicate another flags byte follows... */ } while (0); /*((flags & 0x01) && (flag_bytes < 31));*/ /* Cell Portion ID */ if (cell_portion_id_present) { proto_tree_add_item(tree, hf_fp_cell_portion_id, tvb, offset, 1, ENC_BIG_ENDIAN); offset++; } /* Ext Rx Timing Deviation */ if (ext_rx_timing_deviation_present) { guint8 extra_bits; guint bits_to_extend; switch (p_fp_info->division) { case Division_TDD_384: bits_to_extend = 1; break; case Division_TDD_768: bits_to_extend = 2; break; default: /* TODO: report unexpected division type */ bits_to_extend = 1; break; } extra_bits = tvb_get_guint8(tvb, offset) & ((bits_to_extend == 1) ? 0x01 : 0x03); rx_timing_deviation = (extra_bits << 8) | (rx_timing_deviation); proto_item_append_text(rx_timing_deviation_ti, " (extended to 0x%x)", rx_timing_deviation); proto_tree_add_bits_item(tree, hf_fp_extended_bits, tvb, offset*8 + (8-bits_to_extend), bits_to_extend, ENC_BIG_ENDIAN); offset++; } /* Ext propagation delay. */ if (ext_propagation_delay_present) { guint16 extra_bits = tvb_get_ntohs(tvb, offset) & 0x03ff; proto_tree_add_item(tree, hf_fp_ext_propagation_delay, tvb, offset, 2, ENC_BIG_ENDIAN); /* Adding 10 bits to original 8 */ proto_item_append_text(propagation_delay_ti, " (extended to %u)", ((extra_bits << 8) | propagation_delay) * 3); offset += 2; } /* Angle of Arrival (AOA) */ if (angle_of_arrival_present) { proto_tree_add_item(tree, hf_fp_angle_of_arrival, tvb, offset, 2, ENC_BIG_ENDIAN); offset += 2; } /* Ext. Rx Sync UL Timing Deviation */ if (ext_rx_sync_ul_timing_deviation_present) { guint16 extra_bits; /* Ext received Sync UL Timing Deviation */ extra_bits = tvb_get_ntohs(tvb, offset) & 0x1fff; proto_tree_add_item(tree, hf_fp_ext_received_sync_ul_timing_deviation, tvb, offset, 2, ENC_BIG_ENDIAN); /* Adding 13 bits to original 8 */ proto_item_append_text(received_sync_ul_timing_deviation_ti, " (extended to %u)", (extra_bits << 8) | received_sync_ul_timing_deviation); offset += 2; } } if (preferences_header_checksum) { verify_header_crc(tvb, pinfo, header_crc_pi, header_crc, header_length); } /* Spare Extension and Payload CRC */ dissect_spare_extension_and_crc(tvb, pinfo, tree, 1, offset, header_length); } } /**************************/ /* Dissect a FACH channel */ static void dissect_fach_channel_info(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, int offset, struct fp_info *p_fp_info, void *data) { gboolean is_control_frame; guint16 header_crc = 0; proto_item * header_crc_pi = NULL; guint header_length = 0; /* Header CRC */ header_crc = tvb_get_bits8(tvb, 0, 7); header_crc_pi = proto_tree_add_item(tree, hf_fp_header_crc, tvb, offset, 1, ENC_BIG_ENDIAN); /* Frame Type */ is_control_frame = tvb_get_guint8(tvb, offset) & 0x01; proto_tree_add_item(tree, hf_fp_ft, tvb, offset, 1, ENC_BIG_ENDIAN); offset++; col_append_str(pinfo->cinfo, COL_INFO, is_control_frame ? " [Control] " : " [Data] "); if (is_control_frame) { dissect_common_control(tvb, pinfo, tree, offset, p_fp_info); /* For control frame the header CRC is actually frame CRC covering all * bytes except the first */ if (preferences_header_checksum) { verify_control_frame_crc(tvb, pinfo, header_crc_pi, header_crc); } } else { guint8 cfn; /* DATA */ /* CFN */ cfn = tvb_get_guint8(tvb, offset); proto_tree_add_item(tree, hf_fp_cfn, tvb, offset, 1, ENC_BIG_ENDIAN); offset++; col_append_fstr(pinfo->cinfo, COL_INFO, "CFN=%03u ", cfn); /* TFI */ proto_tree_add_item(tree, hf_fp_fach_tfi, tvb, offset, 1, ENC_BIG_ENDIAN); offset++; /* Transmit power level */ proto_tree_add_float(tree, hf_fp_transmit_power_level, tvb, offset, 1, (float)(int)(tvb_get_guint8(tvb, offset)) / 10); offset++; header_length = offset; /* TB data */ offset = dissect_tb_data(tvb, pinfo, tree, offset, p_fp_info, &mac_fdd_fach_handle, data); /* New IE flags (if it looks as though they are present) */ if ((p_fp_info->release == 7) && (tvb_reported_length_remaining(tvb, offset) > 2)) { guint8 flags = tvb_get_guint8(tvb, offset); guint8 aoa_present = flags & 0x01; offset++; if (aoa_present) { proto_tree_add_item(tree, hf_fp_angle_of_arrival, tvb, offset, 2, ENC_BIG_ENDIAN); offset += 2; } } if (preferences_header_checksum) { verify_header_crc(tvb, pinfo, header_crc_pi, header_crc, header_length); } /* Spare Extension and Payload CRC */ dissect_spare_extension_and_crc(tvb, pinfo, tree, 1, offset, header_length); } } /**************************/ /* Dissect a DSCH channel */ static void dissect_dsch_channel_info(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, int offset, struct fp_info *p_fp_info) { gboolean is_control_frame; /* Header CRC */ proto_tree_add_item(tree, hf_fp_header_crc, tvb, offset, 1, ENC_BIG_ENDIAN); /* Frame Type */ is_control_frame = tvb_get_guint8(tvb, offset) & 0x01; proto_tree_add_item(tree, hf_fp_ft, tvb, offset, 1, ENC_BIG_ENDIAN); offset++; col_append_str(pinfo->cinfo, COL_INFO, is_control_frame ? " [Control] " : " [Data] "); if (is_control_frame) { dissect_common_control(tvb, pinfo, tree, offset, p_fp_info); } else { guint8 cfn; guint header_length = 0; /* DATA */ /* CFN */ cfn = tvb_get_guint8(tvb, offset); proto_tree_add_item(tree, hf_fp_cfn, tvb, offset, 1, ENC_BIG_ENDIAN); offset++; col_append_fstr(pinfo->cinfo, COL_INFO, "CFN=%03u ", cfn); /* TFI */ proto_tree_add_item(tree, hf_fp_tfi, tvb, offset, 1, ENC_BIG_ENDIAN); offset++; /* Other fields depend upon release & FDD/TDD settings */ if (((p_fp_info->release == 99) || (p_fp_info->release == 4)) && (p_fp_info->channel == CHANNEL_DSCH_FDD)) { /* Power offset */ proto_tree_add_float(tree, hf_fp_power_offset, tvb, offset, 1, (float)(-32.0) + ((float)(int)(tvb_get_guint8(tvb, offset)) * (float)(0.25))); offset++; /* Code number */ proto_tree_add_item(tree, hf_fp_code_number, tvb, offset, 1, ENC_BIG_ENDIAN); offset++; /* Spreading Factor (3 bits) */ proto_tree_add_item(tree, hf_fp_spreading_factor, tvb, offset, 1, ENC_BIG_ENDIAN); /* MC info (4 bits)*/ proto_tree_add_item(tree, hf_fp_mc_info, tvb, offset, 1, ENC_BIG_ENDIAN); /* Last bit of this byte is spare */ offset++; } else { /* Normal case */ /* PDSCH Set Id */ proto_tree_add_item(tree, hf_fp_pdsch_set_id, tvb, offset, 1, ENC_BIG_ENDIAN); offset++; /* Transmit power level */ proto_tree_add_float(tree, hf_fp_transmit_power_level, tvb, offset, 1, (float)(int)(tvb_get_guint8(tvb, offset)) / 10); offset++; } header_length = offset; /* TB data */ offset = dissect_tb_data(tvb, pinfo, tree, offset, p_fp_info, NULL, NULL); /* Spare Extension and Payload CRC */ dissect_spare_extension_and_crc(tvb, pinfo, tree, 1, offset, header_length); } } /**************************/ /* Dissect a USCH channel */ static void dissect_usch_channel_info(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, int offset, struct fp_info *p_fp_info) { gboolean is_control_frame; /* Header CRC */ proto_tree_add_item(tree, hf_fp_header_crc, tvb, offset, 1, ENC_BIG_ENDIAN); /* Frame Type */ is_control_frame = tvb_get_guint8(tvb, offset) & 0x01; proto_tree_add_item(tree, hf_fp_ft, tvb, offset, 1, ENC_BIG_ENDIAN); offset++; col_append_str(pinfo->cinfo, COL_INFO, is_control_frame ? " [Control] " : " [Data] "); if (is_control_frame) { dissect_common_control(tvb, pinfo, tree, offset, p_fp_info); } else { guint cfn; guint16 rx_timing_deviation; proto_item *rx_timing_deviation_ti; guint header_length = 0; /* DATA */ /* CFN */ cfn = tvb_get_guint8(tvb, offset); proto_tree_add_item(tree, hf_fp_cfn, tvb, offset, 1, ENC_BIG_ENDIAN); offset++; col_append_fstr(pinfo->cinfo, COL_INFO, "CFN=%03u ", cfn); /* TFI */ proto_tree_add_item(tree, hf_fp_usch_tfi, tvb, offset, 1, ENC_BIG_ENDIAN); offset++; /* Rx Timing Deviation */ rx_timing_deviation = tvb_get_guint8(tvb, offset); rx_timing_deviation_ti = proto_tree_add_item(tree, hf_fp_rx_timing_deviation, tvb, offset, 1, ENC_BIG_ENDIAN); offset++; header_length = offset; /* TB data */ offset = dissect_tb_data(tvb, pinfo, tree, offset, p_fp_info, NULL, NULL); /* QE */ proto_tree_add_item(tree, hf_fp_quality_estimate, tvb, offset, 1, ENC_BIG_ENDIAN); offset++; /* CRCIs */ offset = dissect_crci_bits(tvb, pinfo, tree, p_fp_info, offset); /* New IEs */ if ((p_fp_info->release == 7) && (tvb_reported_length_remaining(tvb, offset) > 2)) { guint8 flags = tvb_get_guint8(tvb, offset); guint8 bits_extended = flags & 0x01; offset++; if (bits_extended) { guint8 extra_bits = tvb_get_guint8(tvb, offset) & 0x03; proto_item_append_text(rx_timing_deviation_ti, " (extended to %u)", (rx_timing_deviation << 2) | extra_bits); } offset++; } /* Spare Extension and Payload CRC */ dissect_spare_extension_and_crc(tvb, pinfo, tree, 1, offset, header_length); } } /**************************/ /* Dissect a PCH channel */ static void dissect_pch_channel_info(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, int offset, struct fp_info *p_fp_info, void *data) { gboolean is_control_frame; guint16 pch_cfn; gboolean paging_indication; guint16 header_crc = 0; proto_item * header_crc_pi = NULL; /* Header CRC */ header_crc = tvb_get_bits8(tvb, 0, 7); header_crc_pi = proto_tree_add_item(tree, hf_fp_header_crc, tvb, offset, 1, ENC_BIG_ENDIAN); /* Frame Type */ is_control_frame = tvb_get_guint8(tvb, offset) & 0x01; proto_tree_add_item(tree, hf_fp_ft, tvb, offset, 1, ENC_BIG_ENDIAN); offset++; col_append_str(pinfo->cinfo, COL_INFO, is_control_frame ? " [Control] " : " [Data] "); if (is_control_frame) { dissect_common_control(tvb, pinfo, tree, offset, p_fp_info); /* For control frame the header CRC is actually frame CRC covering all * bytes except the first */ if (preferences_header_checksum) { verify_control_frame_crc(tvb, pinfo, header_crc_pi, header_crc); } } else { guint header_length = 0; /* DATA */ /* 12-bit CFN value */ proto_tree_add_item(tree, hf_fp_pch_cfn, tvb, offset, 2, ENC_BIG_ENDIAN); pch_cfn = (tvb_get_ntohs(tvb, offset) & 0xfff0) >> 4; offset++; col_append_fstr(pinfo->cinfo, COL_INFO, "CFN=%04u ", pch_cfn); /* Paging indication */ proto_tree_add_item(tree, hf_fp_pch_pi, tvb, offset, 1, ENC_BIG_ENDIAN); paging_indication = tvb_get_guint8(tvb, offset) & 0x01; offset++; /* 5-bit TFI */ proto_tree_add_item(tree, hf_fp_pch_tfi, tvb, offset, 1, ENC_BIG_ENDIAN); offset++; header_length = offset; /* Optional paging indications */ if (paging_indication) { proto_item *ti; ti = proto_tree_add_item(tree, hf_fp_paging_indication_bitmap, tvb, offset, (p_fp_info->paging_indications+7) / 8, ENC_NA); proto_item_append_text(ti, " (%u bits)", p_fp_info->paging_indications); offset += ((p_fp_info->paging_indications+7) / 8); } /* TB data */ offset = dissect_tb_data(tvb, pinfo, tree, offset, p_fp_info, &mac_fdd_pch_handle, data); if (preferences_header_checksum) { verify_header_crc(tvb, pinfo, header_crc_pi, header_crc, header_length); } /* Spare Extension and Payload CRC */ dissect_spare_extension_and_crc(tvb, pinfo, tree, 1, offset, header_length); } } /**************************/ /* Dissect a CPCH channel */ static void dissect_cpch_channel_info(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, int offset, struct fp_info *p_fp_info) { gboolean is_control_frame; /* Header CRC */ proto_tree_add_item(tree, hf_fp_header_crc, tvb, offset, 1, ENC_BIG_ENDIAN); /* Frame Type */ is_control_frame = tvb_get_guint8(tvb, offset) & 0x01; proto_tree_add_item(tree, hf_fp_ft, tvb, offset, 1, ENC_BIG_ENDIAN); offset++; col_append_str(pinfo->cinfo, COL_INFO, is_control_frame ? " [Control] " : " [Data] "); if (is_control_frame) { dissect_common_control(tvb, pinfo, tree, offset, p_fp_info); } else { guint cfn; guint header_length = 0; /* DATA */ /* CFN */ cfn = tvb_get_guint8(tvb, offset); proto_tree_add_item(tree, hf_fp_cfn, tvb, offset, 1, ENC_BIG_ENDIAN); offset++; col_append_fstr(pinfo->cinfo, COL_INFO, "CFN=%03u ", cfn); /* TFI */ proto_tree_add_item(tree, hf_fp_cpch_tfi, tvb, offset, 1, ENC_BIG_ENDIAN); offset++; /* Propagation delay */ proto_tree_add_uint(tree, hf_fp_propagation_delay, tvb, offset, 1, tvb_get_guint8(tvb, offset) * 3); offset++; header_length = offset; /* XXX this might be wrong */ /* TB data */ offset = dissect_tb_data(tvb, pinfo, tree, offset, p_fp_info, NULL, NULL); /* CRCIs */ offset = dissect_crci_bits(tvb, pinfo, tree, p_fp_info, offset); /* Spare Extension and Payload CRC */ dissect_spare_extension_and_crc(tvb, pinfo, tree, 1, offset, header_length); } } /**************************/ /* Dissect a BCH channel */ static void dissect_bch_channel_info(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, int offset, struct fp_info *p_fp_info) { gboolean is_control_frame; /* Header CRC */ proto_tree_add_item(tree, hf_fp_header_crc, tvb, offset, 1, ENC_BIG_ENDIAN); /* Frame Type */ is_control_frame = tvb_get_guint8(tvb, offset) & 0x01; proto_tree_add_item(tree, hf_fp_ft, tvb, offset, 1, ENC_BIG_ENDIAN); offset++; col_append_str(pinfo->cinfo, COL_INFO, is_control_frame ? " [Control] " : " [Data] "); if (is_control_frame) { dissect_common_control(tvb, pinfo, tree, offset, p_fp_info); } } /********************************/ /* Dissect an IUR DSCH channel */ static void dissect_iur_dsch_channel_info(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, int offset, struct fp_info *p_fp_info) { gboolean is_control_frame; /* Header CRC */ proto_tree_add_item(tree, hf_fp_header_crc, tvb, offset, 1, ENC_BIG_ENDIAN); /* Frame Type */ is_control_frame = tvb_get_guint8(tvb, offset) & 0x01; proto_tree_add_item(tree, hf_fp_ft, tvb, offset, 1, ENC_BIG_ENDIAN); offset++; col_append_str(pinfo->cinfo, COL_INFO, is_control_frame ? " [Control] " : " [Data] "); if (is_control_frame) { dissect_common_control(tvb, pinfo, tree, offset, p_fp_info); } else { /* TODO: DATA */ } } /************************/ /* DCH control messages */ static int dissect_dch_timing_adjustment(proto_tree *tree, packet_info *pinfo, tvbuff_t *tvb, int offset) { guint8 control_cfn; gint16 toa; proto_item *toa_ti; /* CFN control */ control_cfn = tvb_get_guint8(tvb, offset); proto_tree_add_item(tree, hf_fp_cfn_control, tvb, offset, 1, ENC_BIG_ENDIAN); offset++; /* ToA */ toa = tvb_get_ntohs(tvb, offset); toa_ti = proto_tree_add_item(tree, hf_fp_toa, tvb, offset, 2, ENC_BIG_ENDIAN); offset += 2; expert_add_info_format(pinfo, toa_ti, &ei_fp_timing_adjustmentment_reported, "Timing adjustmentment reported (%f ms)", (float)(toa / 8)); col_append_fstr(pinfo->cinfo, COL_INFO, " CFN = %u, ToA = %d", control_cfn, toa); return offset; } static int dissect_dch_rx_timing_deviation(packet_info *pinfo, proto_tree *tree, tvbuff_t *tvb, int offset, struct fp_info *p_fp_info) { guint16 timing_deviation; gint timing_deviation_chips; proto_item *timing_deviation_ti; /* CFN control */ proto_tree_add_item(tree, hf_fp_cfn_control, tvb, offset, 1, ENC_BIG_ENDIAN); offset++; /* Rx Timing Deviation */ timing_deviation = tvb_get_guint8(tvb, offset); timing_deviation_ti = proto_tree_add_item(tree, hf_fp_dch_rx_timing_deviation, tvb, offset, 1, ENC_BIG_ENDIAN); offset++; /* May be extended in R7, but in this case there are at least 2 bytes remaining */ if ((p_fp_info->release == 7) && (tvb_reported_length_remaining(tvb, offset) >= 2)) { /* New IE flags */ guint64 extended_bits_present; guint64 e_rucch_present; /* Read flags */ proto_tree_add_bits_ret_val(tree, hf_fp_e_rucch_present, tvb, offset*8 + 6, 1, &e_rucch_present, ENC_BIG_ENDIAN); proto_tree_add_bits_ret_val(tree, hf_fp_extended_bits_present, tvb, offset*8 + 7, 1, &extended_bits_present, ENC_BIG_ENDIAN); offset++; /* Optional E-RUCCH */ if (e_rucch_present) { /* Value of bit_offset depends upon division type */ int bit_offset; switch (p_fp_info->division) { case Division_TDD_384: bit_offset = 6; break; case Division_TDD_768: bit_offset = 5; break; default: { proto_tree_add_expert(tree, pinfo, &ei_fp_expecting_tdd, tvb, 0, 0); bit_offset = 6; } } proto_tree_add_item(tree, hf_fp_dch_e_rucch_flag, tvb, offset, 1, ENC_BIG_ENDIAN); proto_tree_add_bits_item(tree, hf_fp_dch_e_rucch_flag, tvb, offset*8 + bit_offset, 1, ENC_BIG_ENDIAN); } /* Timing deviation may be extended by another: - 1 bits (3.84 TDD) OR - 2 bits (7.68 TDD) */ if (extended_bits_present) { guint8 extra_bits; guint bits_to_extend; switch (p_fp_info->division) { case Division_TDD_384: bits_to_extend = 1; break; case Division_TDD_768: bits_to_extend = 2; break; default: /* TODO: report unexpected division type */ bits_to_extend = 1; break; } extra_bits = tvb_get_guint8(tvb, offset) & ((bits_to_extend == 1) ? 0x01 : 0x03); timing_deviation = (extra_bits << 8) | (timing_deviation); proto_item_append_text(timing_deviation_ti, " (extended to 0x%x)", timing_deviation); proto_tree_add_bits_item(tree, hf_fp_extended_bits, tvb, offset*8 + (8-bits_to_extend), bits_to_extend, ENC_BIG_ENDIAN); offset++; } } timing_deviation_chips = (timing_deviation*4) - 1024; proto_item_append_text(timing_deviation_ti, " (%d chips)", timing_deviation_chips); col_append_fstr(pinfo->cinfo, COL_INFO, " deviation = %u (%d chips)", timing_deviation, timing_deviation_chips); return offset; } static int dissect_dch_dl_synchronisation(proto_tree *tree, packet_info *pinfo, tvbuff_t *tvb, int offset) { /* CFN control */ guint cfn = tvb_get_guint8(tvb, offset); proto_tree_add_item(tree, hf_fp_cfn_control, tvb, offset, 1, ENC_BIG_ENDIAN); offset++; col_append_fstr(pinfo->cinfo, COL_INFO, " CFN = %u", cfn); return offset; } static int dissect_dch_ul_synchronisation(proto_tree *tree, packet_info *pinfo, tvbuff_t *tvb, int offset) { guint8 cfn; gint16 toa; /* CFN control */ cfn = tvb_get_guint8(tvb, offset); proto_tree_add_item(tree, hf_fp_cfn_control, tvb, offset, 1, ENC_BIG_ENDIAN); offset++; /* ToA */ toa = tvb_get_ntohs(tvb, offset); proto_tree_add_item(tree, hf_fp_toa, tvb, offset, 2, ENC_BIG_ENDIAN); offset += 2; col_append_fstr(pinfo->cinfo, COL_INFO, " CFN = %u, ToA = %d", cfn, toa); return offset; } static int dissect_dch_outer_loop_power_control(proto_tree *tree, packet_info *pinfo, tvbuff_t *tvb, int offset) { /* UL SIR target */ float target = (float)-8.2 + ((float)0.1 * (float)(int)(tvb_get_guint8(tvb, offset))); proto_tree_add_float(tree, hf_fp_ul_sir_target, tvb, offset, 1, target); offset++; col_append_fstr(pinfo->cinfo, COL_INFO, " UL SIR Target = %f", target); return offset; } static int dissect_dch_dl_node_synchronisation(proto_tree *tree, packet_info *pinfo, tvbuff_t *tvb, int offset) { return dissect_common_dl_node_synchronisation(pinfo, tree, tvb, offset); } static int dissect_dch_ul_node_synchronisation(proto_tree *tree, packet_info *pinfo, tvbuff_t *tvb, int offset) { return dissect_common_ul_node_synchronisation(pinfo, tree, tvb, offset); } static int dissect_dch_radio_interface_parameter_update(proto_tree *tree, packet_info *pinfo _U_, tvbuff_t *tvb, int offset) { int n; guint8 value; /* Show defined flags in these 2 bytes */ for (n=4; n >= 0; n--) { proto_tree_add_item(tree, hf_fp_radio_interface_parameter_update_flag[n], tvb, offset, 2, ENC_BIG_ENDIAN); } offset += 2; /* CFN */ tvb_get_guint8(tvb, offset); proto_tree_add_item(tree, hf_fp_cfn, tvb, offset, 1, ENC_BIG_ENDIAN); offset++; /* DPC mode */ proto_tree_add_item(tree, hf_fp_dpc_mode, tvb, offset, 1, ENC_BIG_ENDIAN); /* TPC PO */ proto_tree_add_item(tree, hf_fp_tpc_po, tvb, offset, 1, ENC_BIG_ENDIAN); offset++; /* Multiple RL sets indicator */ proto_tree_add_item(tree, hf_fp_multiple_rl_set_indicator, tvb, offset, 1, ENC_BIG_ENDIAN); offset += 2; /* MAX_UE_TX_POW */ value = (tvb_get_guint8(tvb, offset) & 0x7f); proto_tree_add_int(tree, hf_fp_max_ue_tx_pow, tvb, offset, 1, -55 + value); offset++; return offset; } static int dissect_dch_timing_advance(proto_tree *tree, packet_info *pinfo, tvbuff_t *tvb, int offset, struct fp_info *p_fp_info) { guint8 cfn; guint16 timing_advance; proto_item *timing_advance_ti; /* CFN control */ cfn = tvb_get_guint8(tvb, offset); proto_tree_add_item(tree, hf_fp_cfn_control, tvb, offset, 1, ENC_BIG_ENDIAN); offset++; /* Timing Advance */ timing_advance = (tvb_get_guint8(tvb, offset) & 0x3f) * 4; timing_advance_ti = proto_tree_add_uint(tree, hf_fp_timing_advance, tvb, offset, 1, timing_advance); offset++; if ((p_fp_info->release == 7) && (tvb_reported_length_remaining(tvb, offset) > 0)) { /* New IE flags */ guint8 flags = tvb_get_guint8(tvb, offset); guint8 extended_bits = flags & 0x01; offset++; if (extended_bits) { guint8 extra_bit = tvb_get_guint8(tvb, offset) & 0x01; proto_item_append_text(timing_advance_ti, " (extended to %u)", (timing_advance << 1) | extra_bit); } offset++; } col_append_fstr(pinfo->cinfo, COL_INFO, " CFN = %u, TA = %u", cfn, timing_advance); return offset; } static int dissect_dch_tnl_congestion_indication(proto_tree *tree, packet_info *pinfo, tvbuff_t *tvb, int offset) { guint64 status; /* Congestion status */ proto_tree_add_bits_ret_val(tree, hf_fp_congestion_status, tvb, offset*8 + 6, 2, &status, ENC_BIG_ENDIAN); offset++; col_append_fstr(pinfo->cinfo, COL_INFO, " status = %s", val_to_str_const((guint16)status, congestion_status_vals, "unknown")); return offset; } /* DCH control frame */ static void dissect_dch_control_frame(proto_tree *tree, packet_info *pinfo, tvbuff_t *tvb, int offset, struct fp_info *p_fp_info) { /* Control frame type */ guint8 control_frame_type = tvb_get_guint8(tvb, offset); proto_tree_add_item(tree, hf_fp_dch_control_frame_type, tvb, offset, 1, ENC_BIG_ENDIAN); offset++; col_append_str(pinfo->cinfo, COL_INFO, val_to_str_const(control_frame_type, dch_control_frame_type_vals, "Unknown")); switch (control_frame_type) { case DCH_TIMING_ADJUSTMENT: /*offset =*/ dissect_dch_timing_adjustment(tree, pinfo, tvb, offset); break; case DCH_RX_TIMING_DEVIATION: /*offset =*/ dissect_dch_rx_timing_deviation(pinfo, tree, tvb, offset, p_fp_info); break; case DCH_DL_SYNCHRONISATION: /*offset =*/ dissect_dch_dl_synchronisation(tree, pinfo, tvb, offset); break; case DCH_UL_SYNCHRONISATION: /*offset =*/ dissect_dch_ul_synchronisation(tree, pinfo, tvb, offset); break; case DCH_OUTER_LOOP_POWER_CONTROL: /*offset =*/ dissect_dch_outer_loop_power_control(tree, pinfo, tvb, offset); break; case DCH_DL_NODE_SYNCHRONISATION: /*offset =*/ dissect_dch_dl_node_synchronisation(tree, pinfo, tvb, offset); break; case DCH_UL_NODE_SYNCHRONISATION: /*offset =*/ dissect_dch_ul_node_synchronisation(tree, pinfo, tvb, offset); break; case DCH_RADIO_INTERFACE_PARAMETER_UPDATE: /*offset =*/ dissect_dch_radio_interface_parameter_update(tree, pinfo, tvb, offset); break; case DCH_TIMING_ADVANCE: /*offset =*/ dissect_dch_timing_advance(tree, pinfo, tvb, offset, p_fp_info); break; case DCH_TNL_CONGESTION_INDICATION: /*offset =*/ dissect_dch_tnl_congestion_indication(tree, pinfo, tvb, offset); break; } /* Spare Extension */ /* dissect_spare_extension_and_crc(tvb, pinfo, tree, 0, offset); */ } /*******************************/ /* Dissect a DCH channel */ static void dissect_dch_channel_info(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, int offset, struct fp_info *p_fp_info, void *data) { gboolean is_control_frame; guint8 cfn; guint header_length = 0; guint16 header_crc = 0; proto_item * header_crc_pi = NULL; /* Header CRC */ header_crc = tvb_get_bits8(tvb, 0, 7); header_crc_pi = proto_tree_add_item(tree, hf_fp_header_crc, tvb, offset, 1, ENC_BIG_ENDIAN); /* Frame Type */ is_control_frame = tvb_get_guint8(tvb, offset) & 0x01; proto_tree_add_item(tree, hf_fp_ft, tvb, offset, 1, ENC_BIG_ENDIAN); offset++; col_append_str(pinfo->cinfo, COL_INFO, is_control_frame ? " [Control] " : ((p_fp_info->is_uplink) ? " [ULData] " : " [DLData] " )); if (is_control_frame) { /* DCH control frame */ dissect_dch_control_frame(tree, pinfo, tvb, offset, p_fp_info); /* For control frame the header CRC is actually frame CRC covering all * bytes except the first */ if (preferences_header_checksum) { verify_control_frame_crc(tvb, pinfo, header_crc_pi, header_crc); } } else { /************************/ /* DCH data here */ int chan; /* CFN */ proto_tree_add_item(tree, hf_fp_cfn, tvb, offset, 1, ENC_BIG_ENDIAN); cfn = tvb_get_guint8(tvb, offset); offset++; col_append_fstr(pinfo->cinfo, COL_INFO, "CFN=%03u ", cfn); /* One TFI for each channel */ for (chan=0; chan < p_fp_info->num_chans; chan++) { proto_tree_add_item(tree, hf_fp_tfi, tvb, offset, 1, ENC_BIG_ENDIAN); offset++; } header_length = offset; /* Dissect TB data */ offset = dissect_tb_data(tvb, pinfo, tree, offset, p_fp_info, &mac_fdd_dch_handle, data); /* QE (uplink only) */ if (p_fp_info->is_uplink) { proto_tree_add_item(tree, hf_fp_quality_estimate, tvb, offset, 1, ENC_BIG_ENDIAN); offset++; } /* CRCI bits (uplink only) */ if (p_fp_info->is_uplink) { offset = dissect_crci_bits(tvb, pinfo, tree, p_fp_info, offset); } if (preferences_header_checksum) { verify_header_crc(tvb, pinfo, header_crc_pi, header_crc, header_length); } /* Spare extension and payload CRC (optional) */ dissect_spare_extension_and_crc(tvb, pinfo, tree, p_fp_info->dch_crc_present, offset, header_length); } } /**********************************/ /* Dissect an E-DCH channel */ static void dissect_e_dch_channel_info(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, int offset, struct fp_info *p_fp_info, gboolean is_common, rlc_info *rlcinf, void *data) { gboolean is_control_frame; guint8 number_of_subframes; guint8 cfn; int n; struct edch_t1_subframe_info subframes[16]; guint16 header_crc = 0; proto_item * header_crc_pi = NULL; guint header_length = 0; if (p_fp_info->edch_type == 1) { col_append_str(pinfo->cinfo, COL_INFO, " (T2)"); } /* Header CRC */ /* the bitmask doesn't properly handle this delicate case, do manually */ header_crc = (tvb_get_bits8(tvb, offset*8, 7) << 4) + tvb_get_bits8(tvb, offset*8+8, 4); /* Frame Type */ is_control_frame = tvb_get_guint8(tvb, offset) & 0x01; col_append_str(pinfo->cinfo, COL_INFO, is_control_frame ? " [Control] " : " [Data] "); if (is_control_frame) { /* DCH control frame */ /* For control frame the header CRC is actually frame CRC covering all * bytes except the first */ header_crc = tvb_get_bits8(tvb, 0, 7); header_crc_pi = proto_tree_add_item(tree, hf_fp_header_crc, tvb, 0, 1, ENC_BIG_ENDIAN); proto_tree_add_item(tree, hf_fp_ft, tvb, 0, 1, ENC_BIG_ENDIAN); offset++; if (preferences_header_checksum) { verify_control_frame_crc(tvb, pinfo, header_crc_pi, header_crc); } dissect_dch_control_frame(tree, pinfo, tvb, offset, p_fp_info); } else { /********************************/ /* E-DCH data here */ guint bit_offset = 0; guint total_pdus = 0; guint total_bits = 0; gboolean dissected = FALSE; header_crc_pi = proto_tree_add_uint_format(tree, hf_fp_edch_header_crc, tvb, offset, 2, header_crc, "%u%u%u%u%u%u%u.%u%u%u%u.... = E-DCH Header CRC: 0x%x", (header_crc >> 10) & 1, (header_crc >> 9) & 1, (header_crc >> 8) & 1, (header_crc >> 7) & 1, (header_crc >> 6) & 1, (header_crc >> 5) & 1, (header_crc >> 4) & 1, (header_crc >> 3) & 1, (header_crc >> 2) & 1, (header_crc >> 1) & 1, (header_crc >> 0) & 1, header_crc); proto_tree_add_item(tree, hf_fp_ft, tvb, offset, 1, ENC_BIG_ENDIAN); offset++; /* FSN */ proto_tree_add_item(tree, hf_fp_edch_fsn, tvb, offset, 1, ENC_BIG_ENDIAN); offset++; /* Number of subframes. This was 3 bits in early releases, is 4 bits offset by 1 in later releases */ if ((p_fp_info->release >= 6) && ((p_fp_info->release_year > 2005) || ((p_fp_info->release_year == 2005) && (p_fp_info->release_month >= 9)))) { /* Use 4 bits plus offset of 1 */ number_of_subframes = (tvb_get_guint8(tvb, offset) & 0x0f) + 1; } else { /* Use 3 bits only */ number_of_subframes = (tvb_get_guint8(tvb, offset) & 0x07); } proto_tree_add_uint(tree, hf_fp_edch_number_of_subframes, tvb, offset, 1, number_of_subframes); offset++; /* CFN */ cfn = tvb_get_guint8(tvb, offset); proto_tree_add_item(tree, hf_fp_cfn, tvb, offset, 1, ENC_BIG_ENDIAN); offset++; /* Remainder of T2 or common data frames differ here... */ if (p_fp_info->edch_type == 1) { dissect_e_dch_t2_or_common_channel_info(tvb, pinfo, tree, offset, p_fp_info, number_of_subframes, is_common, header_crc, header_crc_pi, data); return; } /* EDCH subframe header list */ for (n=0; n < number_of_subframes; n++) { int i; int start_offset = offset; proto_item *subframe_header_ti; proto_tree *subframe_header_tree; /* Add subframe header subtree */ subframe_header_ti = proto_tree_add_string_format(tree, hf_fp_edch_subframe_header, tvb, offset, 0, "", "Subframe"); subframe_header_tree = proto_item_add_subtree(subframe_header_ti, ett_fp_edch_subframe_header); /* Number of HARQ Retransmissions */ proto_tree_add_item(subframe_header_tree, hf_fp_edch_harq_retransmissions, tvb, offset, 1, ENC_BIG_ENDIAN); /* Subframe number */ subframes[n].subframe_number = (tvb_get_guint8(tvb, offset) & 0x07); proto_tree_add_bits_item(subframe_header_tree, hf_fp_edch_subframe_number, tvb, offset*8+5, 1, ENC_BIG_ENDIAN); offset++; /* Number of MAC-es PDUs */ subframes[n].number_of_mac_es_pdus = (tvb_get_guint8(tvb, offset) & 0xf0) >> 4; proto_tree_add_item(subframe_header_tree, hf_fp_edch_number_of_mac_es_pdus, tvb, offset, 1, ENC_BIG_ENDIAN); bit_offset = 4; proto_item_append_text(subframe_header_ti, " %u header (%u MAC-es PDUs)", subframes[n].subframe_number, subframes[n].number_of_mac_es_pdus); /* Details of each MAC-es PDU */ for (i=0; i < subframes[n].number_of_mac_es_pdus; i++) { guint64 ddi; guint64 n_pdus; /*Size of the PDU*/ proto_item *ddi_ti; gint ddi_size = -1; int p; /* DDI (6 bits) */ ddi_ti = proto_tree_add_bits_ret_val(subframe_header_tree, hf_fp_edch_ddi, tvb, offset*8 + bit_offset, 6, &ddi, ENC_BIG_ENDIAN); if (rlcinf) { rlcinf->rbid[i] = (guint8)ddi; } /********************************/ /* Look up data in higher layers*/ /* Look up the size from this DDI value */ for (p=0; p < p_fp_info->no_ddi_entries; p++) { if (ddi == p_fp_info->edch_ddi[p]) { ddi_size = p_fp_info->edch_macd_pdu_size[p]; break; } } if (ddi_size == -1) { expert_add_info_format(pinfo, ddi_ti, &ei_fp_ddi_not_defined, "DDI %u not defined for this UE!", (guint)ddi); return; } else { proto_item_append_text(ddi_ti, " (%d bits)", ddi_size); } subframes[n].ddi[i] = (guint8)ddi; bit_offset += 6; /* Number of MAC-d PDUs (6 bits) */ proto_tree_add_bits_ret_val(subframe_header_tree, hf_fp_edch_number_of_mac_d_pdus, tvb, offset*8 + bit_offset, 6, &n_pdus, ENC_BIG_ENDIAN); subframes[n].number_of_mac_d_pdus[i] = (guint8)n_pdus; bit_offset += 6; } offset += ((bit_offset+7)/8); /* Tree should cover entire subframe header */ proto_item_set_len(subframe_header_ti, offset - start_offset); } header_length = offset; /* EDCH subframes */ for (n=0; n < number_of_subframes; n++) { int i; proto_item *subframe_ti; proto_tree *subframe_tree; guint bits_in_subframe = 0; guint mac_d_pdus_in_subframe = 0; guint lchid=0; /*Logcial channel id*/ umts_mac_info *macinf; bit_offset = 0; macinf = (umts_mac_info *)p_get_proto_data(wmem_file_scope(), pinfo, proto_umts_mac, 0); /* Add subframe subtree */ subframe_ti = proto_tree_add_string_format(tree, hf_fp_edch_subframe, tvb, offset, 0, "", "Subframe %u data", subframes[n].subframe_number); subframe_tree = proto_item_add_subtree(subframe_ti, ett_fp_edch_subframe); for (i=0; i < subframes[n].number_of_mac_es_pdus; i++) { int m; guint16 size = 0; /* guint8 tsn; */ guint send_size; proto_item *ti; int macd_idx; proto_tree *maces_tree = NULL; /** TODO: Merge these two loops? **/ /* Look up mac-d pdu size for this ddi */ for (m=0; m < p_fp_info->no_ddi_entries; m++) { if (subframes[n].ddi[i] == p_fp_info->edch_ddi[m]) { size = p_fp_info->edch_macd_pdu_size[m]; break; } } /* Look up logicalchannel id for this DDI value */ for (m=0; m < p_fp_info->no_ddi_entries; m++) { if (subframes[n].ddi[i] == p_fp_info->edch_ddi[m]) { lchid = p_fp_info->edch_lchId[m]; break; } } if (m == p_fp_info->no_ddi_entries) { /* Not found. Oops */ expert_add_info(pinfo, NULL, &ei_fp_unable_to_locate_ddi_entry); return; } /* Send MAC-dd PDUs together as one MAC-es PDU */ send_size = size * subframes[n].number_of_mac_d_pdus[i]; /* 2 bits spare */ proto_tree_add_item(subframe_tree, hf_fp_edch_pdu_padding, tvb, offset + (bit_offset/8), 1, ENC_BIG_ENDIAN); bit_offset += 2; /* TSN */ /* tsn = (tvb_get_guint8(tvb, offset + (bit_offset/8)) & 0x3f); */ proto_tree_add_item(subframe_tree, hf_fp_edch_tsn, tvb, offset + (bit_offset/8), 1, ENC_BIG_ENDIAN); bit_offset += 6; /* PDU */ if (subframe_tree) { ti = proto_tree_add_item(subframe_tree, hf_fp_edch_mac_es_pdu, tvb, offset + (bit_offset/8), ((bit_offset % 8) + send_size + 7) / 8, ENC_NA); proto_item_append_text(ti, " (%u * %u = %u bits, PDU %d)", size, subframes[n].number_of_mac_d_pdus[i], send_size, n); maces_tree = proto_item_add_subtree(ti, ett_fp_edch_maces); } for (macd_idx = 0; macd_idx < subframes[n].number_of_mac_d_pdus[i]; macd_idx++) { if (preferences_call_mac_dissectors /*&& !rlc_is_ciphered(pinfo)*/) { tvbuff_t *next_tvb; pinfo->fd->subnum = macd_idx; /* set subframe number to current TB */ /* create new TVB and pass further on */ next_tvb = tvb_new_subset(tvb, offset + bit_offset/8, ((bit_offset % 8) + size + 7) / 8, -1); /*This was all previously stored in [0] rather than [macd_idx] and cur_tb wasn't updated!*/ /*Set up information needed for MAC and lower layers*/ macinf->content[macd_idx] = lchId_type_table[lchid]; /*Set the proper Content type for the mac layer.*/ macinf->lchid[macd_idx] = lchid; rlcinf->mode[macd_idx] = lchId_rlc_map[lchid]; /* Set RLC mode by lchid to RLC_MODE map in nbap.h */ /* Set U-RNTI to ComuncationContext signaled from nbap*/ rlcinf->urnti[macd_idx] = p_fp_info->com_context_id; rlcinf->rbid[macd_idx] = lchid; /*subframes[n].ddi[i];*/ /*Save the DDI value for RLC*/ /*g_warning("========Setting RBID:%d for lchid:%d", subframes[n].ddi[i], lchid);*/ /* rlcinf->mode[0] = RLC_AM;*/ rlcinf->li_size[macd_idx] = RLC_LI_7BITS; #if 0 /*If this entry exists, SECRUITY_MODE is completed*/ if ( rrc_ciph_inf && g_tree_lookup(rrc_ciph_inf, GINT_TO_POINTER((gint)p_fp_info->com_context_id)) ) { rlcinf->ciphered[macd_idx] = TRUE; } else { rlcinf->ciphered[macd_idx] = FALSE; } #endif rlcinf->ciphered[macd_idx] = FALSE; rlcinf->deciphered[macd_idx] = FALSE; p_fp_info->cur_tb = macd_idx; /*Set the transport block index (NOTE: This and not subnum is used in MAC dissector!)*/ /* TODO: use maces_tree? */ call_dissector_with_data(mac_fdd_edch_handle, next_tvb, pinfo, top_level_tree, data); dissected = TRUE; } else { /* Just add as a MAC-d PDU */ proto_tree_add_item(maces_tree, hf_fp_mac_d_pdu, tvb, offset + (bit_offset/8), ((bit_offset % 8) + size + 7) / 8, ENC_NA); } bit_offset += size; } bits_in_subframe += send_size; mac_d_pdus_in_subframe += subframes[n].number_of_mac_d_pdus[i]; /* Pad out to next byte */ if (bit_offset % 8) { bit_offset += (8 - (bit_offset % 8)); } } if (tree) { /* Tree should cover entire subframe */ proto_item_set_len(subframe_ti, bit_offset/8); /* Append summary info to subframe label */ proto_item_append_text(subframe_ti, " (%u bits in %u MAC-d PDUs)", bits_in_subframe, mac_d_pdus_in_subframe); } total_pdus += mac_d_pdus_in_subframe; total_bits += bits_in_subframe; offset += (bit_offset/8); } /* Report number of subframes in info column * do this only if no other dissector was called */ if (dissected == FALSE) { col_append_fstr(pinfo->cinfo, COL_INFO, " CFN = %03u (%u bits in %u pdus in %u subframes)", cfn, total_bits, total_pdus, number_of_subframes); } /* Add data summary to info column */ /*col_append_fstr(pinfo->cinfo, COL_INFO, " (%u bytes in %u SDUs in %u MAC-is PDUs in %u subframes)", total_bytes, macis_sdus_found, macis_pdus, number_of_subframes);*/ if (preferences_header_checksum) { verify_header_crc_edch(tvb, pinfo, header_crc_pi, header_crc, header_length); } /* Spare extension and payload CRC (optional) */ dissect_spare_extension_and_crc(tvb, pinfo, tree, p_fp_info->dch_crc_present, offset, header_length); } } /* Dissect the remainder of the T2 or common frame that differs from T1 */ static void dissect_e_dch_t2_or_common_channel_info(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, int offset, struct fp_info *p_fp_info, int number_of_subframes, gboolean is_common, guint16 header_crc, proto_item * header_crc_pi, void *data) { int n; int pdu_no; guint64 total_macis_sdus; guint16 macis_sdus_found = 0; guint16 macis_pdus = 0; gboolean F = TRUE; /* We want to continue loop if get E-RNTI indication... */ gint bit_offset; proto_item *subframe_macis_descriptors_ti = NULL; static struct edch_t2_subframe_info subframes[16]; guint header_length = 0; /* User Buffer size */ proto_tree_add_bits_item(tree, hf_fp_edch_user_buffer_size, tvb, offset*8, 18, ENC_BIG_ENDIAN); offset += 2; /* Spare is in-between... */ /* Total number of MAC-is SDUs */ proto_tree_add_bits_ret_val(tree, hf_fp_edch_no_macid_sdus, tvb, offset*8+4, 12, &total_macis_sdus, ENC_BIG_ENDIAN); offset += 2; if (is_common) { /* E-RNTI */ proto_tree_add_item(tree, hf_fp_edch_e_rnti, tvb, offset, 2, ENC_BIG_ENDIAN); offset += 2; } bit_offset = offset*8; /* EDCH subframe header list */ for (n=0; n < number_of_subframes; n++) { guint64 subframe_number; guint64 no_of_macis_pdus; proto_item *subframe_header_ti; proto_tree *subframe_header_tree; /* Add subframe header subtree */ subframe_header_ti = proto_tree_add_string_format(tree, hf_fp_edch_subframe_header, tvb, offset, 0, "", "Subframe"); subframe_header_tree = proto_item_add_subtree(subframe_header_ti, ett_fp_edch_subframe_header); /* Spare bit */ bit_offset++; if (!is_common) { /* Number of HARQ Retransmissions */ proto_tree_add_item(subframe_header_tree, hf_fp_edch_harq_retransmissions, tvb, bit_offset/8, 1, ENC_BIG_ENDIAN); bit_offset += 4; } /* Subframe number */ proto_tree_add_bits_ret_val(subframe_header_tree, hf_fp_edch_subframe_number, tvb, bit_offset, 3, &subframe_number, ENC_BIG_ENDIAN); subframes[n].subframe_number = (guint8)subframe_number; bit_offset += 3; /* Number of MAC-is PDUs */ proto_tree_add_bits_ret_val(subframe_header_tree, hf_fp_edch_number_of_mac_is_pdus, tvb, bit_offset, 4, &no_of_macis_pdus, ENC_BIG_ENDIAN); bit_offset += 4; subframes[n].number_of_mac_is_pdus = (guint8)no_of_macis_pdus; macis_pdus += subframes[n].number_of_mac_is_pdus; /* Next 4 bits are spare for T2*/ if (!is_common) { bit_offset += 4; } /* Show summary in root */ proto_item_append_text(subframe_header_ti, " (SFN %u, %u MAC-is PDUs)", subframes[n].subframe_number, subframes[n].number_of_mac_is_pdus); proto_item_set_len(subframe_header_ti, is_common ? 1 : 2); } offset = bit_offset / 8; /* MAC-is PDU descriptors for each subframe follow */ for (n=0; n < number_of_subframes; n++) { proto_tree *subframe_macis_descriptors_tree; /* Add subframe header subtree */ subframe_macis_descriptors_ti = proto_tree_add_string_format(tree, hf_fp_edch_macis_descriptors, tvb, offset, 0, "", "MAC-is descriptors (SFN %u)", subframes[n].subframe_number); proto_item_set_len(subframe_macis_descriptors_ti, subframes[n].number_of_mac_is_pdus*2); subframe_macis_descriptors_tree = proto_item_add_subtree(subframe_macis_descriptors_ti, ett_fp_edch_macis_descriptors); /* Find a sequence of descriptors for each MAC-is PDU in this subframe */ for (pdu_no=0; pdu_no < subframes[n].number_of_mac_is_pdus; pdu_no++) { proto_item *f_ti = NULL; subframes[n].number_of_mac_is_sdus[pdu_no] = 0; do { /* Check we haven't gone past the limit */ if (macis_sdus_found++ > total_macis_sdus) { expert_add_info_format(pinfo, f_ti, &ei_fp_mac_is_sdus_miscount, "Found too many (%u) MAC-is SDUs - header said there were %u", macis_sdus_found, (guint16)total_macis_sdus); } /* LCH-ID */ subframes[n].mac_is_lchid[pdu_no][subframes[n].number_of_mac_is_sdus[pdu_no]] = (tvb_get_guint8(tvb, offset) & 0xf0) >> 4; proto_tree_add_item(subframe_macis_descriptors_tree, hf_fp_edch_macis_lchid, tvb, offset, 1, ENC_BIG_ENDIAN); if (subframes[n].mac_is_lchid[pdu_no][subframes[n].number_of_mac_is_sdus[pdu_no]] == 15) { proto_item *ti; /* 4 bits of spare */ offset++; /* E-RNTI */ ti = proto_tree_add_item(tree, hf_fp_edch_e_rnti, tvb, offset, 2, ENC_BIG_ENDIAN); offset += 2; /* This is only allowed if: - it's the common case AND - it's the first descriptor */ if (!is_common) { expert_add_info(pinfo, ti, &ei_fp_e_rnti_t2_edch_frames); } if (subframes[n].number_of_mac_is_sdus[pdu_no] > 0) { expert_add_info(pinfo, ti, &ei_fp_e_rnti_first_entry); } continue; } /* Length */ subframes[n].mac_is_length[pdu_no][subframes[n].number_of_mac_is_sdus[pdu_no]] = (tvb_get_ntohs(tvb, offset) & 0x0ffe) >> 1; proto_tree_add_item(subframe_macis_descriptors_tree, hf_fp_edch_macis_length, tvb, offset, 2, ENC_BIG_ENDIAN); offset++; /* Flag */ F = tvb_get_guint8(tvb, offset) & 0x01; f_ti = proto_tree_add_item(subframe_macis_descriptors_tree, hf_fp_edch_macis_flag, tvb, offset, 1, ENC_BIG_ENDIAN); subframes[n].number_of_mac_is_sdus[pdu_no]++; offset++; } while (F == 0); } } /* Check overall count of MAC-is SDUs */ if (macis_sdus_found != total_macis_sdus) { expert_add_info_format(pinfo, subframe_macis_descriptors_ti, &ei_fp_mac_is_sdus_miscount, "Frame contains %u MAC-is SDUs - header said there would be %u!", macis_sdus_found, (guint16)total_macis_sdus); } header_length = offset; /* Now PDUs */ for (n=0; n < number_of_subframes; n++) { /* MAC-is PDU */ for (pdu_no=0; pdu_no < subframes[n].number_of_mac_is_pdus; pdu_no++) { int i; guint length = 0; umts_mac_is_info * mac_is_info = wmem_new(wmem_file_scope(), umts_mac_is_info); mac_is_info->number_of_mac_is_sdus = subframes[n].number_of_mac_is_sdus[pdu_no]; DISSECTOR_ASSERT(subframes[n].number_of_mac_is_sdus[pdu_no] <= MAX_MAC_FRAMES); for (i = 0; i < subframes[n].number_of_mac_is_sdus[pdu_no]; i++) { mac_is_info->sdulength[i] = subframes[n].mac_is_length[pdu_no][i]; mac_is_info->lchid[i] = subframes[n].mac_is_lchid[pdu_no][i]; length += subframes[n].mac_is_length[pdu_no][i]; } /* Call MAC for this PDU if configured to */ if (preferences_call_mac_dissectors) { p_add_proto_data(wmem_file_scope(), pinfo, proto_umts_mac, 0, mac_is_info); call_dissector_with_data(mac_fdd_edch_type2_handle, tvb_new_subset_remaining(tvb, offset), pinfo, top_level_tree, data); } else { /* Still show data if not decoding as MAC PDU */ proto_tree_add_item(tree, hf_fp_edch_mac_is_pdu, tvb, offset, length, ENC_NA); } /* get_mac_tsn_size in packet-umts_mac.h, gets the global_mac_tsn_size preference in umts_mac.c */ if (get_mac_tsn_size() == MAC_TSN_14BITS) { offset += length + 2; /* Plus 2 bytes for TSN 14 bits and SS 2 bit. */ } else { offset += length + 1; /* Plus 1 byte for TSN 6 bits and SS 2 bit. */ } } } if (preferences_header_checksum) { verify_header_crc_edch(tvb, pinfo, header_crc_pi, header_crc, header_length); } /* Spare extension and payload CRC (optional) */ dissect_spare_extension_and_crc(tvb, pinfo, tree, p_fp_info->dch_crc_present, offset, header_length); } /**********************************************************/ /* Dissect an HSDSCH channel */ /* The data format corresponds to the format */ /* described in R5 and R6, and frame type 1 in Release 7. */ static void dissect_hsdsch_channel_info(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, int offset, struct fp_info *p_fp_info, void *data) { gboolean is_control_frame; guint header_length = 0; guint16 header_crc = 0; proto_item * header_crc_pi = NULL; /* Header CRC */ header_crc = tvb_get_bits8(tvb, 0, 7); header_crc_pi = proto_tree_add_item(tree, hf_fp_header_crc, tvb, offset, 1, ENC_BIG_ENDIAN); /* Frame Type */ is_control_frame = tvb_get_guint8(tvb, offset) & 0x01; proto_tree_add_item(tree, hf_fp_ft, tvb, offset, 1, ENC_BIG_ENDIAN); offset++; col_append_str(pinfo->cinfo, COL_INFO, is_control_frame ? " [Control] " : " [Data] "); if (is_control_frame) { dissect_common_control(tvb, pinfo, tree, offset, p_fp_info); /* For control frame the header CRC is actually frame CRC covering all * bytes except the first */ if (preferences_header_checksum) { verify_control_frame_crc(tvb, pinfo, header_crc_pi, header_crc); } } else { guint8 number_of_pdus; guint16 pdu_length; guint16 user_buffer_size; int i; umts_mac_info *macinf; rlc_info *rlcinf; rlcinf = (rlc_info *)p_get_proto_data(wmem_file_scope(), pinfo, proto_rlc, 0); macinf = (umts_mac_info *)p_get_proto_data(wmem_file_scope(), pinfo, proto_umts_mac, 0); /**************************************/ /* HS-DCH data here (type 1 in R7) */ /* Frame Seq Nr */ if ((p_fp_info->release == 6) || (p_fp_info->release == 7)) { guint8 frame_seq_no = (tvb_get_guint8(tvb, offset) & 0xf0) >> 4; proto_tree_add_item(tree, hf_fp_frame_seq_nr, tvb, offset, 1, ENC_BIG_ENDIAN); col_append_fstr(pinfo->cinfo, COL_INFO, " seqno=%u", frame_seq_no); } /* CmCH-PI */ proto_tree_add_item(tree, hf_fp_cmch_pi, tvb, offset, 1, ENC_BIG_ENDIAN); offset++; /* MAC-d PDU Length (13 bits) */ pdu_length = (tvb_get_ntohs(tvb, offset) >> 3); proto_tree_add_item(tree, hf_fp_mac_d_pdu_len, tvb, offset, 2, ENC_BIG_ENDIAN); offset += 2; macinf->pdu_len = pdu_length; if ((p_fp_info->release == 6) || (p_fp_info->release == 7)) { /* Flush bit */ proto_tree_add_item(tree, hf_fp_flush, tvb, offset-1, 1, ENC_BIG_ENDIAN); /* FSN/DRT reset bit */ proto_tree_add_item(tree, hf_fp_fsn_drt_reset, tvb, offset-1, 1, ENC_BIG_ENDIAN); } /* Num of PDUs */ number_of_pdus = tvb_get_guint8(tvb, offset); proto_tree_add_item(tree, hf_fp_num_of_pdu, tvb, offset, 1, ENC_BIG_ENDIAN); offset++; /* User buffer size */ user_buffer_size = tvb_get_ntohs(tvb, offset); proto_tree_add_item(tree, hf_fp_user_buffer_size, tvb, offset, 2, ENC_BIG_ENDIAN); offset += 2; header_length = offset; /************************/ /*Configure the pdus*/ for (i=0;i<number_of_pdus && i<MIN(MAX_MAC_FRAMES, MAX_RLC_CHANS); i++) { macinf->content[i] = hsdsch_macdflow_id_mac_content_map[p_fp_info->hsdsch_macflowd_id]; /*MAC_CONTENT_PS_DTCH;*/ macinf->lchid[i] = fake_lchid_macd_flow[p_fp_info->hsdsch_macflowd_id];/*Faked logical channel id 255 used as a mark if it doesn't exist...*/ macinf->fake_chid[i] = TRUE; /**/ macinf->macdflow_id[i] = p_fp_info->hsdsch_macflowd_id; /*Save the flow ID (+1 to make it human readable (it's zero indexed!))*/ /*Figure out RLC_MODE based on MACd-flow-ID, basically MACd-flow-ID = 0 then it's SRB0 == UM else AM*/ rlcinf->mode[i] = hsdsch_macdflow_id_rlc_map[p_fp_info->hsdsch_macflowd_id]; /*Check if this is multiplexed (signaled by RRC)*/ if ( /*!rlc_is_ciphered(pinfo) &&*/ p_fp_info->hsdhsch_macfdlow_is_mux[p_fp_info->hsdsch_macflowd_id] ) { macinf->ctmux[i] = TRUE; } else if (p_fp_info->hsdsch_macflowd_id == 0) { /*MACd-flow = 0 is often SRB */ expert_add_info(pinfo, NULL, &ei_fp_maybe_srb); } else { macinf->ctmux[i] = FALSE; /*Either it's multiplexed and not signled or it's not MUX*/ } rlcinf->urnti[i] = p_fp_info->com_context_id; rlcinf->li_size[i] = RLC_LI_7BITS; rlcinf->deciphered[i] = FALSE; rlcinf->ciphered[i] = FALSE; rlcinf->rbid[i] = macinf->lchid[i]; #if 0 /*When a flow has been reconfigured rlc needs to be reset. * This needs more work though since we must figure out when the re-configuration becomes * active based on the CFN value * */ /*Indicate we need to reset stream*/ if (p_fp_info->reset_frag) { rlc_reset_channel(rlcinf->mode[i], macinf->lchid[i], p_fp_info->is_uplink, rlcinf->urnti[i] ); p_fp_info->reset_frag = FALSE; } #endif } /* MAC-d PDUs */ offset = dissect_macd_pdu_data(tvb, pinfo, tree, offset, pdu_length, number_of_pdus, p_fp_info, data); col_append_fstr(pinfo->cinfo, COL_INFO, " %ux%u-bit PDUs User-Buffer-Size=%u", number_of_pdus, pdu_length, user_buffer_size); /* Extra IEs (if there is room for them) */ if (((p_fp_info->release == 6) || (p_fp_info->release == 7)) && (tvb_reported_length_remaining(tvb, offset) > 2)) { int n; guint8 flags; /* guint8 flag_bytes = 0; */ /* New IE flags */ do { proto_item *new_ie_flags_ti; proto_tree *new_ie_flags_tree; guint ies_found = 0; /* Add new IE flags subtree */ new_ie_flags_ti = proto_tree_add_string_format(tree, hf_fp_hsdsch_new_ie_flags, tvb, offset, 1, "", "New IE flags"); new_ie_flags_tree = proto_item_add_subtree(new_ie_flags_ti, ett_fp_hsdsch_new_ie_flags); /* Read next byte */ flags = tvb_get_guint8(tvb, offset); /* flag_bytes++; */ /* Dissect individual bits */ for (n=0; n < 8; n++) { proto_tree_add_item(new_ie_flags_tree, hf_fp_hsdsch_new_ie_flag[n], tvb, offset, 1, ENC_BIG_ENDIAN); if ((flags >> (7-n)) & 0x01) { ies_found++; } } offset++; proto_item_append_text(new_ie_flags_ti, " (%u IEs found)", ies_found); /* Last bit set will indicate another flags byte follows... */ } while (0); /*((flags & 0x01) && (flag_bytes < 31));*/ if (1) /*(flags & 0x8) */ { /* DRT is shown as mandatory in the diagram (3GPP TS 25.435 V6.3.0), but the description below it states that it should depend upon the first bit. The detailed description of New IE flags doesn't agree, so treat as mandatory for now... */ proto_tree_add_item(tree, hf_fp_hsdsch_drt, tvb, offset, 2, ENC_BIG_ENDIAN); offset += 2; } } if (preferences_header_checksum) { verify_header_crc(tvb, pinfo, header_crc_pi, header_crc, header_length); } /* Spare Extension and Payload CRC */ dissect_spare_extension_and_crc(tvb, pinfo, tree, 1, offset, header_length); } } /******************************************/ /* Dissect an HSDSCH type 2 channel */ /* (introduced in Release 7) */ /* N.B. there is currently no support for */ /* frame type 3 (IuR only?) */ static void dissect_hsdsch_type_2_channel_info(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, int offset, struct fp_info *p_fp_info, void *data) { gboolean is_control_frame; guint16 header_crc = 0; proto_item * header_crc_pi = NULL; guint16 header_length = 0; /* Header CRC */ header_crc = tvb_get_bits8(tvb, 0, 7); header_crc_pi = proto_tree_add_item(tree, hf_fp_header_crc, tvb, offset, 1, ENC_BIG_ENDIAN); /* Frame Type */ is_control_frame = tvb_get_guint8(tvb, offset) & 0x01; proto_tree_add_item(tree, hf_fp_ft, tvb, offset, 1, ENC_BIG_ENDIAN); offset++; col_append_str(pinfo->cinfo, COL_INFO, is_control_frame ? " [Control] " : " [Data] "); if (is_control_frame) { dissect_common_control(tvb, pinfo, tree, offset, p_fp_info); /* For control frame the header CRC is actually frame CRC covering all * bytes except the first */ if (preferences_header_checksum) { verify_control_frame_crc(tvb, pinfo, header_crc_pi, header_crc); } } else { guint8 number_of_pdu_blocks; gboolean drt_present = FALSE; gboolean fach_present = FALSE; guint16 user_buffer_size; int n; guint j; #define MAX_PDU_BLOCKS 31 guint64 lchid[MAX_PDU_BLOCKS]; guint64 pdu_length[MAX_PDU_BLOCKS]; guint64 no_of_pdus[MAX_PDU_BLOCKS]; umts_mac_info *macinf; rlc_info *rlcinf; rlcinf = (rlc_info *)p_get_proto_data(wmem_file_scope(), pinfo, proto_rlc, 0); macinf = (umts_mac_info *)p_get_proto_data(wmem_file_scope(), pinfo, proto_umts_mac, 0); /********************************/ /* HS-DCH type 2 data here */ col_append_str(pinfo->cinfo, COL_INFO, "(ehs)"); /* Frame Seq Nr (4 bits) */ if ((p_fp_info->release == 6) || (p_fp_info->release == 7)) { guint8 frame_seq_no = (tvb_get_guint8(tvb, offset) & 0xf0) >> 4; proto_tree_add_item(tree, hf_fp_frame_seq_nr, tvb, offset, 1, ENC_BIG_ENDIAN); col_append_fstr(pinfo->cinfo, COL_INFO, " seqno=%u", frame_seq_no); } /* CmCH-PI (4 bits) */ proto_tree_add_item(tree, hf_fp_cmch_pi, tvb, offset, 1, ENC_BIG_ENDIAN); offset++; /* Total number of PDU blocks (5 bits) */ number_of_pdu_blocks = (tvb_get_guint8(tvb, offset) >> 3); proto_tree_add_item(tree, hf_fp_total_pdu_blocks, tvb, offset, 1, ENC_BIG_ENDIAN); if (p_fp_info->release == 7) { /* Flush bit */ proto_tree_add_item(tree, hf_fp_flush, tvb, offset, 1, ENC_BIG_ENDIAN); /* FSN/DRT reset bit */ proto_tree_add_item(tree, hf_fp_fsn_drt_reset, tvb, offset, 1, ENC_BIG_ENDIAN); /* DRT Indicator */ drt_present = tvb_get_guint8(tvb, offset) & 0x01; proto_tree_add_item(tree, hf_fp_drt_indicator, tvb, offset, 1, ENC_BIG_ENDIAN); } offset++; /* FACH Indicator flag */ fach_present = (tvb_get_guint8(tvb, offset) & 0x80) >> 7; proto_tree_add_item(tree, hf_fp_fach_indicator, tvb, offset, 1, ENC_BIG_ENDIAN); offset++; /* User buffer size */ user_buffer_size = tvb_get_ntohs(tvb, offset); proto_tree_add_item(tree, hf_fp_user_buffer_size, tvb, offset, 2, ENC_BIG_ENDIAN); offset += 2; col_append_fstr(pinfo->cinfo, COL_INFO, " User-Buffer-Size=%u", user_buffer_size); /********************************************************************/ /* Now read number_of_pdu_blocks header entries */ for (n=0; n < number_of_pdu_blocks; n++) { proto_item *pdu_block_header_ti; proto_tree *pdu_block_header_tree; int block_header_start_offset = offset; /* Add PDU block header subtree */ pdu_block_header_ti = proto_tree_add_string_format(tree, hf_fp_hsdsch_pdu_block_header, tvb, offset, 0, "", "PDU Block Header"); pdu_block_header_tree = proto_item_add_subtree(pdu_block_header_ti, ett_fp_hsdsch_pdu_block_header); /* MAC-d/c PDU length in this block (11 bits) */ proto_tree_add_bits_ret_val(pdu_block_header_tree, hf_fp_pdu_length_in_block, tvb, (offset*8) + ((n % 2) ? 4 : 0), 11, &pdu_length[n], ENC_BIG_ENDIAN); if ((n % 2) == 0) offset++; else offset += 2; /* # PDUs in this block (4 bits) */ proto_tree_add_bits_ret_val(pdu_block_header_tree, hf_fp_pdus_in_block, tvb, (offset*8) + ((n % 2) ? 0 : 4), 4, &no_of_pdus[n], ENC_BIG_ENDIAN); if ((n % 2) == 0) { offset++; } /* Logical channel ID in block (4 bits) */ proto_tree_add_bits_ret_val(pdu_block_header_tree, hf_fp_lchid, tvb, (offset*8) + ((n % 2) ? 4 : 0), 4, &lchid[n], ENC_BIG_ENDIAN); if ((n % 2) == 1) { offset++; } else { if (n == (number_of_pdu_blocks-1)) { /* Byte is padded out for last block */ offset++; } } /* Append summary to header tree root */ proto_item_append_text(pdu_block_header_ti, " (lch:%u, %u pdus of %u bytes)", (guint16)lchid[n], (guint16)no_of_pdus[n], (guint16)pdu_length[n]); /* Set length of header tree item */ if (((n % 2) == 0) && (n < (number_of_pdu_blocks-1))) { proto_item_set_len(pdu_block_header_ti, offset - block_header_start_offset+1); } else { proto_item_set_len(pdu_block_header_ti, offset - block_header_start_offset); } } if (header_length == 0) { header_length = offset; } /**********************************************/ /* Optional fields indicated by earlier flags */ if (drt_present) { /* DRT */ proto_tree_add_item(tree, hf_fp_drt, tvb, offset, 2, ENC_BIG_ENDIAN); offset += 2; } if (fach_present) { /* H-RNTI: */ proto_tree_add_item(tree, hf_fp_hrnti, tvb, offset, 2, ENC_BIG_ENDIAN); offset += 2; /* RACH Measurement Result */ proto_tree_add_item(tree, hf_fp_rach_measurement_result, tvb, offset, 2, ENC_BIG_ENDIAN); offset++; } /********************************************************************/ /* Now read the MAC-d/c PDUs for each block using info from headers */ for (n=0; n < number_of_pdu_blocks; n++) { for (j=0;j<no_of_pdus[n];j++) { /*Configure (signal to lower layers) the PDU!*/ macinf->content[j] = lchId_type_table[lchid[n]+1];/*hsdsch_macdflow_id_mac_content_map[p_fp_info->hsdsch_macflowd_id];*/ /*MAC_CONTENT_PS_DTCH;*/ macinf->lchid[j] = (guint8)lchid[n]+1; /*Add 1 since C/T is zero indexed? ie C/T =0 => L-CHID = 1*/ macinf->macdflow_id[j] = p_fp_info->hsdsch_macflowd_id; /*Figure out RLC_MODE based on MACd-flow-ID, basically MACd-flow-ID = 0 then it's SRB0 == UM else AM*/ rlcinf->mode[j] = lchId_rlc_map[lchid[n]+1];/*hsdsch_macdflow_id_rlc_map[p_fp_info->hsdsch_macflowd_id];*/ macinf->ctmux[n] = FALSE; rlcinf->li_size[j] = RLC_LI_7BITS; /** Configure ciphering **/ #if 0 /*If this entry exists, SECRUITY_MODE is completed*/ if ( rrc_ciph_inf && g_tree_lookup(rrc_ciph_inf, GINT_TO_POINTER((gint)p_fp_info->com_context_id)) ) { rlcinf->ciphered[j] = TRUE; } else { rlcinf->ciphered[j] = FALSE; } #endif rlcinf->ciphered[j] = FALSE; rlcinf->deciphered[j] = FALSE; rlcinf->rbid[j] = (guint8)lchid[n]+1; rlcinf->urnti[j] = p_fp_info->com_context_id; /*Set URNIT to comuncation context id*/ } /* Add PDU block header subtree */ offset = dissect_macd_pdu_data_type_2(tvb, pinfo, tree, offset, (guint16)pdu_length[n], (guint16)no_of_pdus[n], p_fp_info, data); } if (preferences_header_checksum) { verify_header_crc(tvb, pinfo, header_crc_pi, header_crc, header_length); } /* Spare Extension and Payload CRC */ dissect_spare_extension_and_crc(tvb, pinfo, tree, 1, offset, header_length); } } /** * Dissect and CONFIGURE hsdsch_common channel. * * This will dissect hsdsch common channels of type 2, so this is * very similar to regular type two (ehs) the difference being how * the configuration is done. NOTE: VERY EXPERIMENTAL. * * @param tvb the tv buffer of the current data * @param pinfo the packet info of the current data * @param tree the tree to append this item to * @param offset the offset in the tvb * @param p_fp_info FP-packet information */ static void dissect_hsdsch_common_channel_info(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, int offset, struct fp_info *p_fp_info, void *data) { gboolean is_control_frame; guint16 header_crc = 0; proto_item * header_crc_pi = NULL; guint header_length = 0; /* Header CRC */ header_crc = tvb_get_bits8(tvb, 0, 7); header_crc_pi = proto_tree_add_item(tree, hf_fp_header_crc, tvb, offset, 1, ENC_BIG_ENDIAN); /* Frame Type */ is_control_frame = tvb_get_guint8(tvb, offset) & 0x01; proto_tree_add_item(tree, hf_fp_ft, tvb, offset, 1, ENC_BIG_ENDIAN); offset++; col_append_str(pinfo->cinfo, COL_INFO, is_control_frame ? " [Control] " : " [Data] "); if (is_control_frame) { dissect_common_control(tvb, pinfo, tree, offset, p_fp_info); /* For control frame the header CRC is actually frame CRC covering all * bytes except the first */ if (preferences_header_checksum) { verify_control_frame_crc(tvb, pinfo, header_crc_pi, header_crc); } } else { guint8 number_of_pdu_blocks; gboolean drt_present = FALSE; gboolean fach_present = FALSE; guint16 user_buffer_size; int n; guint j; #define MAX_PDU_BLOCKS 31 guint64 lchid[MAX_PDU_BLOCKS]; guint64 pdu_length[MAX_PDU_BLOCKS]; guint64 no_of_pdus[MAX_PDU_BLOCKS]; guint8 newieflags = 0; umts_mac_info *macinf; rlc_info *rlcinf; rlcinf = (rlc_info *)p_get_proto_data(wmem_file_scope(), pinfo, proto_rlc, 0); macinf = (umts_mac_info *)p_get_proto_data(wmem_file_scope(), pinfo, proto_umts_mac, 0); /********************************/ /* HS-DCH type 2 data here */ col_append_str(pinfo->cinfo, COL_INFO, "(ehs)"); /* Frame Seq Nr (4 bits) */ if ((p_fp_info->release == 6) || (p_fp_info->release == 7)) { guint8 frame_seq_no = (tvb_get_guint8(tvb, offset) & 0xf0) >> 4; proto_tree_add_item(tree, hf_fp_frame_seq_nr, tvb, offset, 1, ENC_BIG_ENDIAN); col_append_fstr(pinfo->cinfo, COL_INFO, " seqno=%u", frame_seq_no); } /* CmCH-PI (4 bits) */ proto_tree_add_item(tree, hf_fp_cmch_pi, tvb, offset, 1, ENC_BIG_ENDIAN); offset++; /* Total number of PDU blocks (5 bits) */ number_of_pdu_blocks = (tvb_get_guint8(tvb, offset) >> 3); proto_tree_add_item(tree, hf_fp_total_pdu_blocks, tvb, offset, 1, ENC_BIG_ENDIAN); if (p_fp_info->release == 7) { /* Flush bit */ proto_tree_add_item(tree, hf_fp_flush, tvb, offset, 1, ENC_BIG_ENDIAN); /* FSN/DRT reset bit */ proto_tree_add_item(tree, hf_fp_fsn_drt_reset, tvb, offset, 1, ENC_BIG_ENDIAN); /* DRT Indicator */ drt_present = tvb_get_guint8(tvb, offset) & 0x01; proto_tree_add_item(tree, hf_fp_drt_indicator, tvb, offset, 1, ENC_BIG_ENDIAN); } offset++; /* FACH Indicator flag */ fach_present = (tvb_get_guint8(tvb, offset) & 0x80) >> 7; proto_tree_add_item(tree, hf_fp_fach_indicator, tvb, offset, 1, ENC_BIG_ENDIAN); offset++; /* User buffer size */ user_buffer_size = tvb_get_ntohs(tvb, offset); proto_tree_add_item(tree, hf_fp_user_buffer_size, tvb, offset, 2, ENC_BIG_ENDIAN); offset += 2; col_append_fstr(pinfo->cinfo, COL_INFO, " User-Buffer-Size=%u", user_buffer_size); /********************************************************************/ /* Now read number_of_pdu_blocks header entries */ for (n=0; n < number_of_pdu_blocks; n++) { proto_item *pdu_block_header_ti; proto_tree *pdu_block_header_tree; int block_header_start_offset = offset; /* Add PDU block header subtree */ pdu_block_header_ti = proto_tree_add_string_format(tree, hf_fp_hsdsch_pdu_block_header, tvb, offset, 0, "", "PDU Block Header"); pdu_block_header_tree = proto_item_add_subtree(pdu_block_header_ti, ett_fp_hsdsch_pdu_block_header); /* MAC-d/c PDU length in this block (11 bits) */ proto_tree_add_bits_ret_val(pdu_block_header_tree, hf_fp_pdu_length_in_block, tvb, (offset*8) + ((n % 2) ? 4 : 0), 11, &pdu_length[n], ENC_BIG_ENDIAN); if ((n % 2) == 0) offset++; else offset += 2; /* # PDUs in this block (4 bits) */ proto_tree_add_bits_ret_val(pdu_block_header_tree, hf_fp_pdus_in_block, tvb, (offset*8) + ((n % 2) ? 0 : 4), 4, &no_of_pdus[n], ENC_BIG_ENDIAN); if ((n % 2) == 0) { offset++; } /* Logical channel ID in block (4 bits) */ proto_tree_add_bits_ret_val(pdu_block_header_tree, hf_fp_lchid, tvb, (offset*8) + ((n % 2) ? 4 : 0), 4, &lchid[n], ENC_BIG_ENDIAN); if ((n % 2) == 1) { offset++; } else { if (n == (number_of_pdu_blocks-1)) { /* Byte is padded out for last block */ offset++; } } /* Append summary to header tree root */ proto_item_append_text(pdu_block_header_ti, " (lch:%u, %u pdus of %u bytes)", (guint16)lchid[n], (guint16)no_of_pdus[n], (guint16)pdu_length[n]); /* Set length of header tree item */ if (((n % 2) == 0) && (n < (number_of_pdu_blocks-1))) { proto_item_set_len(pdu_block_header_ti, offset - block_header_start_offset+1); } else { proto_item_set_len(pdu_block_header_ti, offset - block_header_start_offset); } } if (header_length == 0) { header_length = offset; } /**********************************************/ /* Optional fields indicated by earlier flags */ if (drt_present) { /* DRT */ proto_tree_add_item(tree, hf_fp_drt, tvb, offset, 2, ENC_BIG_ENDIAN); offset += 2; } if (fach_present) { /* H-RNTI: */ proto_tree_add_item(tree, hf_fp_hrnti, tvb, offset, 2, ENC_BIG_ENDIAN); offset += 2; /* RACH Measurement Result */ proto_tree_add_item(tree, hf_fp_rach_measurement_result, tvb, offset, 1, ENC_BIG_ENDIAN); offset++; } /********************************************************************/ /* Now read the MAC-d/c PDUs for each block using info from headers */ for (n=0; n < number_of_pdu_blocks; n++) { tvbuff_t *next_tvb; for (j=0; j<no_of_pdus[n]; j++) { /* If all bits are set, then this is BCCH or PCCH according to: 25.435 paragraph: 6.2.7.31 */ if (lchid[n] == 0xF) { /* In the very few test cases I've seen, this seems to be * BCCH with transparent MAC layer. Therefore skip right to * rlc_bcch and hope for the best. */ next_tvb = tvb_new_subset_length(tvb, offset, (gint)pdu_length[n]); call_dissector_with_data(rlc_bcch_handle, next_tvb, pinfo, top_level_tree, data); offset += (gint)pdu_length[n]; } else { /* Else go for CCCH UM, this seems to work. */ p_fp_info->hsdsch_entity = ehs; /* HSDSCH type 2 */ /* TODO: use cur_tb or subnum everywhere. */ p_fp_info->cur_tb = j; /* set cur_tb for MAC */ pinfo->fd->subnum = j; /* set subframe number for RRC */ macinf->content[j] = MAC_CONTENT_CCCH; macinf->lchid[j] = (guint8)lchid[n]+1; /*Add 1 since it is zero indexed? */ macinf->macdflow_id[j] = p_fp_info->hsdsch_macflowd_id; macinf->ctmux[j] = FALSE; rlcinf->li_size[j] = RLC_LI_7BITS; rlcinf->ciphered[j] = FALSE; rlcinf->deciphered[j] = FALSE; rlcinf->rbid[j] = (guint8)lchid[n]+1; rlcinf->urnti[j] = p_fp_info->channel; /*We need to fake urnti*/ next_tvb = tvb_new_subset_length(tvb, offset, (gint)pdu_length[n]); call_dissector_with_data(mac_fdd_hsdsch_handle, next_tvb, pinfo, top_level_tree, data); offset += (gint)pdu_length[n]; } } } /* New IE Flags */ newieflags = tvb_get_guint8(tvb, offset); /* If newieflags == 0000 0010 then this indicates that there is a * HS-DSCH physical layer category and no other New IE flags. */ if (newieflags == 2) { /* HS-DSCH physical layer category presence bit. */ proto_tree_add_uint(tree, hf_fp_hsdsch_new_ie_flag[6], tvb, offset, 1, newieflags); offset++; /* HS-DSCH physical layer category. */ proto_tree_add_bits_item(tree, hf_fp_hsdsch_physical_layer_category, tvb, offset*8, 6, ENC_BIG_ENDIAN); offset++; } if (preferences_header_checksum) { verify_header_crc(tvb, pinfo, header_crc_pi, header_crc, header_length); } /* Spare Extension and Payload CRC */ dissect_spare_extension_and_crc(tvb, pinfo, tree, 1, offset, header_length); } } static gboolean heur_dissect_fp(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_) { struct fp_info *p_fp_info; p_fp_info = (fp_info *)p_get_proto_data(wmem_file_scope(), pinfo, proto_fp, 0); /* if no FP info is present, this might be FP in a pcap(ng) file */ if (!p_fp_info) { /* We only know the header length of control frames, so check that bit first */ int offset = 0, length; guint8 oct, calc_crc = 0, crc; unsigned char *buf; oct = tvb_get_guint8(tvb, offset); crc = oct & 0xfe; if ((oct & 0x01) == 1) { /* * 6.3.2.1 Frame CRC * Description: It is the result of the CRC applied to the remaining part of the frame, * i.e. from bit 0 of the first byte of the header (the FT IE) to bit 0 of the last byte of the payload, * with the corresponding generator polynomial: G(D) = D7+D6+D2+1. See subclause 7.2. */ length = tvb_reported_length(tvb); buf = (unsigned char *)tvb_memdup(wmem_packet_scope(), tvb, 0, length); buf[0] = 01; calc_crc = crc7update(calc_crc, buf, length); if (calc_crc == crc) { /* assume this is FP, set conversatio dissector to catch the data frames too */ conversation_set_dissector(find_or_create_conversation(pinfo), fp_handle); dissect_fp(tvb, pinfo, tree, data); return TRUE; } } return FALSE; } /* if FP info is present, check that it really is an ethernet link */ if (p_fp_info->link_type != FP_Link_Ethernet) { return FALSE; } /* discriminate 'lower' UDP layer from 'user data' UDP layer * (i.e. if an FP over UDP packet contains a user UDP packet */ if (p_fp_info->srcport != pinfo->srcport || p_fp_info->destport != pinfo->destport) return FALSE; /* assume this is FP */ dissect_fp(tvb, pinfo, tree, data); return TRUE; } static guint8 fakes =5; /*[] ={1,5,8};*/ static guint8 fake_map[256]; /* * TODO: This need to be fixed! * Basically you would want the actual RRC messages, that sooner or later maps * transport channel id's to logical id's or RAB IDs * to set the proper logical channel/RAB ID, but for now we make syntethic ones. * */ static guint8 make_fake_lchid(packet_info *pinfo _U_, gint trchld) { if ( fake_map[trchld] == 0) { fake_map[trchld] = fakes; fakes++; } return fake_map[trchld]; } /* * july 2012: * Alot of configuration has been move into the actual dissecting functions * since most of the configuration/signalign has to be set per tb (pdu) rather * for the channel! */ static fp_info * fp_set_per_packet_inf_from_conv(umts_fp_conversation_info_t *p_conv_data, tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree _U_) { fp_info *fpi; guint8 tfi, c_t; int offset = 0, i=0, j=0, num_tbs, chan, tb_size, tb_bit_off; gboolean is_control_frame; umts_mac_info *macinf; rlc_info *rlcinf; guint8 fake_lchid=0; gint *cur_val=NULL; fpi = wmem_new0(wmem_file_scope(), fp_info); p_add_proto_data(wmem_file_scope(), pinfo, proto_fp, 0, fpi); fpi->iface_type = p_conv_data->iface_type; fpi->division = p_conv_data->division; fpi->release = 7; /* Set values greater then the checks performed */ fpi->release_year = 2006; fpi->release_month = 12; fpi->channel = p_conv_data->channel; fpi->dch_crc_present = p_conv_data->dch_crc_present; /*fpi->paging_indications;*/ fpi->link_type = FP_Link_Ethernet; #if 0 /*Only do this the first run, signals that we need to reset the RLC fragtable*/ if (!pinfo->fd->flags.visited && p_conv_data->reset_frag ) { fpi->reset_frag = p_conv_data->reset_frag; p_conv_data->reset_frag = FALSE; } #endif /* remember 'lower' UDP layer port information so we can later * differentiate 'lower' UDP layer from 'user data' UDP layer */ fpi->srcport = pinfo->srcport; fpi->destport = pinfo->destport; fpi->com_context_id = p_conv_data->com_context_id; if (pinfo->link_dir == P2P_DIR_UL) { fpi->is_uplink = TRUE; } else { fpi->is_uplink = FALSE; } is_control_frame = tvb_get_guint8(tvb, offset) & 0x01; switch (fpi->channel) { case CHANNEL_HSDSCH: /* HS-DSCH - High Speed Downlink Shared Channel */ fpi->hsdsch_entity = p_conv_data->hsdsch_entity; macinf = wmem_new0(wmem_file_scope(), umts_mac_info); fpi->hsdsch_macflowd_id = p_conv_data->hsdsch_macdflow_id; macinf->content[0] = hsdsch_macdflow_id_mac_content_map[p_conv_data->hsdsch_macdflow_id]; /*MAC_CONTENT_PS_DTCH;*/ macinf->lchid[0] = p_conv_data->hsdsch_macdflow_id; /*macinf->content[0] = lchId_type_table[p_conv_data->edch_lchId[0]];*/ p_add_proto_data(wmem_file_scope(), pinfo, proto_umts_mac, 0, macinf); rlcinf = wmem_new0(wmem_file_scope(), rlc_info); /*Figure out RLC_MODE based on MACd-flow-ID, basically MACd-flow-ID = 0 then it's SRB0 == UM else AM*/ rlcinf->mode[0] = hsdsch_macdflow_id_rlc_map[p_conv_data->hsdsch_macdflow_id]; if (fpi->hsdsch_entity == hs /*&& !rlc_is_ciphered(pinfo)*/) { for (i=0; i<MAX_NUM_HSDHSCH_MACDFLOW; i++) { /*Figure out if this channel is multiplexed (signaled from RRC)*/ if ((cur_val=(gint *)g_tree_lookup(hsdsch_muxed_flows, GINT_TO_POINTER((gint)p_conv_data->hrnti))) != NULL) { j = 1 << i; fpi->hsdhsch_macfdlow_is_mux[i] = j & *cur_val; } else { fpi->hsdhsch_macfdlow_is_mux[i] = FALSE; } } } /* Make configurable ?(available in NBAP?) */ /* urnti[MAX_RLC_CHANS] */ /* switch (p_conv_data->rlc_mode) { case FP_RLC_TM: rlcinf->mode[0] = RLC_TM; break; case FP_RLC_UM: rlcinf->mode[0] = RLC_UM; break; case FP_RLC_AM: rlcinf->mode[0] = RLC_AM; break; case FP_RLC_MODE_UNKNOWN: default: rlcinf->mode[0] = RLC_UNKNOWN_MODE; break; }*/ /* rbid[MAX_RLC_CHANS] */ /* For RLC re-assembly to work we urnti signaled from NBAP */ rlcinf->urnti[0] = fpi->com_context_id; rlcinf->li_size[0] = RLC_LI_7BITS; rlcinf->ciphered[0] = FALSE; rlcinf->deciphered[0] = FALSE; p_add_proto_data(wmem_file_scope(), pinfo, proto_rlc, 0, rlcinf); return fpi; case CHANNEL_EDCH: /*Most configuration is now done in the actual dissecting function*/ macinf = wmem_new0(wmem_file_scope(), umts_mac_info); rlcinf = wmem_new0(wmem_file_scope(), rlc_info); fpi->no_ddi_entries = p_conv_data->no_ddi_entries; for (i=0; i<fpi->no_ddi_entries; i++) { fpi->edch_ddi[i] = p_conv_data->edch_ddi[i]; /*Set the DDI value*/ fpi->edch_macd_pdu_size[i] = p_conv_data->edch_macd_pdu_size[i]; /*Set the size*/ fpi->edch_lchId[i] = p_conv_data->edch_lchId[i]; /*Set the channel id for this entry*/ /*macinf->content[i] = lchId_type_table[p_conv_data->edch_lchId[i]]; */ /*Set the proper Content type for the mac layer.*/ /* rlcinf->mode[i] = lchId_rlc_map[p_conv_data->edch_lchId[i]];*/ /* Set RLC mode by lchid to RLC_MODE map in nbap.h */ } fpi->edch_type = p_conv_data->edch_type; /* macinf = wmem_new0(wmem_file_scope(), umts_mac_info); macinf->content[0] = MAC_CONTENT_PS_DTCH;*/ p_add_proto_data(wmem_file_scope(), pinfo, proto_umts_mac, 0, macinf); /* For RLC re-assembly to work we need a urnti signaled from NBAP */ rlcinf->urnti[0] = fpi->com_context_id; /* rlcinf->mode[0] = RLC_AM;*/ rlcinf->li_size[0] = RLC_LI_7BITS; rlcinf->ciphered[0] = FALSE; rlcinf->deciphered[0] = FALSE; p_add_proto_data(wmem_file_scope(), pinfo, proto_rlc, 0, rlcinf); return fpi; case CHANNEL_PCH: fpi->paging_indications = p_conv_data->paging_indications; fpi->num_chans = p_conv_data->num_dch_in_flow; /* Set offset to point to first TFI */ if (is_control_frame) { /* control frame, we're done */ return fpi; } /* Set offset to TFI */ offset = 3; break; case CHANNEL_DCH: fpi->num_chans = p_conv_data->num_dch_in_flow; if (is_control_frame) { /* control frame, we're done */ return fpi; } rlcinf = wmem_new0(wmem_file_scope(), rlc_info); macinf = wmem_new0(wmem_file_scope(), umts_mac_info); offset = 2; /*To correctly read the tfi*/ fakes = 5; /* Reset fake counter. */ for (chan=0; chan < fpi->num_chans; chan++) { /*Iterate over the what channels*/ /*Iterate over the transport blocks*/ /*tfi = tvb_get_guint8(tvb, offset);*/ /*TFI is 5 bits according to 3GPP TS 25.321, paragraph 6.2.4.4*/ tfi = tvb_get_bits8(tvb, 3+offset*8, 5); /*Figure out the number of tbs and size*/ num_tbs = (fpi->is_uplink) ? p_conv_data->fp_dch_channel_info[chan].ul_chan_num_tbs[tfi] : p_conv_data->fp_dch_channel_info[chan].dl_chan_num_tbs[tfi]; tb_size= (fpi->is_uplink) ? p_conv_data->fp_dch_channel_info[i].ul_chan_tf_size[tfi] : p_conv_data->fp_dch_channel_info[i].dl_chan_tf_size[tfi]; /*TODO: This stuff has to be reworked!*/ /*Generates a fake logical channel id for non multiplexed channel*/ if ( p_conv_data->dchs_in_flow_list[chan] != 31 && (p_conv_data->dchs_in_flow_list[chan] == 24 && tb_size != 340) ) { fake_lchid = make_fake_lchid(pinfo, p_conv_data->dchs_in_flow_list[chan]); } tb_bit_off = (2+p_conv_data->num_dch_in_flow)*8; /*Point to the C/T of first TB*/ /*Set configuration for individual blocks*/ for (j=0; j < num_tbs && j+chan < MAX_MAC_FRAMES; j++) { /*Set transport channel id (useful for debugging)*/ macinf->trchid[j+chan] = p_conv_data->dchs_in_flow_list[chan]; /*Transport Channel m31 and 24 might be multiplexed!*/ if ( p_conv_data->dchs_in_flow_list[chan] == 31 || p_conv_data->dchs_in_flow_list[chan] == 24) { /****** MUST FIGURE OUT IF THIS IS REALLY MULTIPLEXED OR NOT*******/ /*If Trchid == 31 and only on TB, we have no multiplexing*/ if (0/*p_conv_data->dchs_in_flow_list[chan] == 31 && num_tbs == 1*/) { macinf->ctmux[j+chan] = FALSE;/*Set TRUE if this channel is multiplexed (ie. C/T flag exists)*/ macinf->lchid[j+chan] = 1; macinf->content[j+chan] = lchId_type_table[1]; /*Base MAC content on logical channel id (Table is in packet-nbap.h)*/ rlcinf->mode[j+chan] = lchId_rlc_map[1]; /*Based RLC mode on logical channel id*/ } /*Indicate we don't have multiplexing.*/ else if (p_conv_data->dchs_in_flow_list[chan] == 24 && tb_size != 340) { macinf->ctmux[j+chan] = FALSE;/*Set TRUE if this channel is multiplexed (ie. C/T flag exists)*/ /*g_warning("settin this for %d", pinfo->num);*/ macinf->lchid[j+chan] = fake_lchid; macinf->fake_chid[j+chan] = TRUE; macinf->content[j+chan] = MAC_CONTENT_PS_DTCH; /*lchId_type_table[fake_lchid];*/ /*Base MAC content on logical channel id (Table is in packet-nbap.h)*/ rlcinf->mode[j+chan] = RLC_AM;/*lchId_rlc_map[fake_lchid];*/ /*Based RLC mode on logical channel id*/ } /*We have multiplexing*/ else { macinf->ctmux[j+chan] = TRUE;/*Set TRUE if this channel is multiplexed (ie. C/T flag exists)*/ /* Peek at C/T, different RLC params for different logical channels */ /*C/T is 4 bits according to 3GPP TS 25.321, paragraph 9.2.1, from MAC header (not FP)*/ c_t = tvb_get_bits8(tvb, tb_bit_off/*(2+p_conv_data->num_dch_in_flow)*8*/, 4); /* c_t = tvb_get_guint8(tvb, offset);*/ macinf->lchid[j+chan] = c_t+1; macinf->content[j+chan] = lchId_type_table[c_t+1]; /*Base MAC content on logical channel id (Table is in packet-nbap.h)*/ rlcinf->mode[j+chan] = lchId_rlc_map[c_t+1]; /*Based RLC mode on logical channel id*/ } } else { fake_lchid = make_fake_lchid(pinfo, p_conv_data->dchs_in_flow_list[chan]); macinf->ctmux[j+chan] = FALSE;/*Set TRUE if this channel is multiplexed (ie. C/T flag exists)*/ /*macinf->content[j+chan] = MAC_CONTENT_CS_DTCH;*/ macinf->content[j+chan] = lchId_type_table[fake_lchid]; rlcinf->mode[j+chan] = lchId_rlc_map[fake_lchid]; /*Generate virtual logical channel id*/ /************************/ /*TODO: Once proper lchid is always set, this has to be removed*/ macinf->fake_chid[j+chan] = TRUE; macinf->lchid[j+chan] = fake_lchid; /*make_fake_lchid(pinfo, p_conv_data->dchs_in_flow_list[chan]);*/ /************************/ } /*** Set rlc info ***/ rlcinf->urnti[j+chan] = p_conv_data->com_context_id; rlcinf->li_size[j+chan] = RLC_LI_7BITS; #if 0 /*If this entry exists, SECRUITY_MODE is completed (signled by RRC)*/ if ( rrc_ciph_inf && g_tree_lookup(rrc_ciph_inf, GINT_TO_POINTER((gint)p_conv_data->com_context_id)) != NULL ) { rlcinf->ciphered[j+chan] = TRUE; } else { rlcinf->ciphered[j+chan] = FALSE; } #endif rlcinf->ciphered[j+chan] = FALSE; rlcinf->deciphered[j+chan] = FALSE; rlcinf->rbid[j+chan] = macinf->lchid[j+chan]; /*Step over this TB and it's C/T flag.*/ tb_bit_off += tb_size+4; } offset++; } p_add_proto_data(wmem_file_scope(), pinfo, proto_umts_mac, 0, macinf); p_add_proto_data(wmem_file_scope(), pinfo, proto_rlc, 0, rlcinf); /* Set offset to point to first TFI * the Number of TFI's = number of DCH's in the flow */ offset = 2; break; case CHANNEL_FACH_FDD: fpi->num_chans = p_conv_data->num_dch_in_flow; if (is_control_frame) { /* control frame, we're done */ return fpi; } /* Set offset to point to first TFI * the Number of TFI's = number of DCH's in the flow */ offset = 2; /* Set MAC data */ macinf = wmem_new0(wmem_file_scope(), umts_mac_info); macinf->ctmux[0] = 1; macinf->content[0] = MAC_CONTENT_DCCH; p_add_proto_data(wmem_file_scope(), pinfo, proto_umts_mac, 0, macinf); /* Set RLC data */ rlcinf = wmem_new0(wmem_file_scope(), rlc_info); /* Make configurable ?(avaliable in NBAP?) */ /* For RLC re-assembly to work we need to fake urnti */ rlcinf->urnti[0] = fpi->channel; rlcinf->mode[0] = RLC_AM; /* rbid[MAX_RLC_CHANS] */ rlcinf->li_size[0] = RLC_LI_7BITS; rlcinf->ciphered[0] = FALSE; rlcinf->deciphered[0] = FALSE; p_add_proto_data(wmem_file_scope(), pinfo, proto_rlc, 0, rlcinf); break; case CHANNEL_RACH_FDD: fpi->num_chans = p_conv_data->num_dch_in_flow; if (is_control_frame) { /* control frame, we're done */ return fpi; } /* Set offset to point to first TFI * the Number of TFI's = number of DCH's in the flow */ offset = 2; /* set MAC data */ macinf = wmem_new0(wmem_file_scope(), umts_mac_info); rlcinf = wmem_new0(wmem_file_scope(), rlc_info); for ( chan = 0; chan < fpi->num_chans; chan++ ) { macinf->ctmux[chan] = 1; macinf->content[chan] = MAC_CONTENT_DCCH; rlcinf->urnti[chan] = fpi->com_context_id; /*Note that MAC probably will change this*/ } p_add_proto_data(wmem_file_scope(), pinfo, proto_umts_mac, 0, macinf); p_add_proto_data(wmem_file_scope(), pinfo, proto_rlc, 0, rlcinf); break; case CHANNEL_HSDSCH_COMMON: rlcinf = wmem_new0(wmem_file_scope(), rlc_info); macinf = wmem_new0(wmem_file_scope(), umts_mac_info); p_add_proto_data(wmem_file_scope(), pinfo, proto_umts_mac, 0, macinf); p_add_proto_data(wmem_file_scope(), pinfo, proto_rlc, 0, rlcinf); break; default: expert_add_info(pinfo, NULL, &ei_fp_transport_channel_type_unknown); return NULL; } /* Peek at the packet as the per packet info seems not to take the tfi into account */ for (i=0; i<fpi->num_chans; i++) { tfi = tvb_get_guint8(tvb, offset); /*TFI is 5 bits according to 3GPP TS 25.321, paragraph 6.2.4.4*/ /*tfi = tvb_get_bits8(tvb, offset*8, 5);*/ if (pinfo->link_dir == P2P_DIR_UL) { fpi->chan_tf_size[i] = p_conv_data->fp_dch_channel_info[i].ul_chan_tf_size[tfi]; fpi->chan_num_tbs[i] = p_conv_data->fp_dch_channel_info[i].ul_chan_num_tbs[tfi]; } else { fpi->chan_tf_size[i] = p_conv_data->fp_dch_channel_info[i].dl_chan_tf_size[tfi]; fpi->chan_num_tbs[i] = p_conv_data->fp_dch_channel_info[i].dl_chan_num_tbs[tfi]; } offset++; } return fpi; } /*****************************/ /* Main dissection function. */ static int dissect_fp_common(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data) { proto_tree *fp_tree; proto_item *ti; gint offset = 0; struct fp_info *p_fp_info; rlc_info *rlcinf; conversation_t *p_conv; umts_fp_conversation_info_t *p_conv_data = NULL; /* Append this protocol name rather than replace. */ col_set_str(pinfo->cinfo, COL_PROTOCOL, "FP"); /* Create fp tree. */ ti = proto_tree_add_item(tree, proto_fp, tvb, offset, -1, ENC_NA); fp_tree = proto_item_add_subtree(ti, ett_fp); top_level_tree = tree; /* Look for packet info! */ p_fp_info = (struct fp_info *)p_get_proto_data(wmem_file_scope(), pinfo, proto_fp, 0); /* Check if we have conversation info */ p_conv = (conversation_t *)find_conversation(pinfo->num, &pinfo->net_dst, &pinfo->net_src, pinfo->ptype, pinfo->destport, pinfo->srcport, NO_ADDR_B); if (p_conv) { /*Find correct conversation, basically find the one that's closest to this frame*/ #if 0 while (p_conv->next != NULL && p_conv->next->setup_frame < pinfo->num) { p_conv = p_conv->next; } #endif p_conv_data = (umts_fp_conversation_info_t *)conversation_get_proto_data(p_conv, proto_fp); if (p_conv_data) { /*Figure out the direction of the link*/ if (addresses_equal(&(pinfo->net_dst), (&p_conv_data->crnc_address))) { proto_item *item= proto_tree_add_uint(fp_tree, hf_fp_ul_setup_frame, tvb, 0, 0, p_conv_data->ul_frame_number); PROTO_ITEM_SET_GENERATED(item); /* CRNC -> Node B */ pinfo->link_dir=P2P_DIR_UL; if (p_fp_info == NULL) { p_fp_info = fp_set_per_packet_inf_from_conv(p_conv_data, tvb, pinfo, fp_tree); } } else { /* Maybe the frame number should be stored in the proper location already in nbap?, in ul_frame_number*/ proto_item *item= proto_tree_add_uint(fp_tree, hf_fp_dl_setup_frame, tvb, 0, 0, p_conv_data->ul_frame_number); PROTO_ITEM_SET_GENERATED(item); pinfo->link_dir=P2P_DIR_DL; if (p_fp_info == NULL) { p_fp_info = fp_set_per_packet_inf_from_conv(p_conv_data, tvb, pinfo, fp_tree); } } } } if (pinfo->p2p_dir == P2P_DIR_UNKNOWN) { if (pinfo->link_dir == P2P_DIR_UL) { pinfo->p2p_dir = P2P_DIR_RECV; } else { pinfo->p2p_dir = P2P_DIR_SENT; } } /* Can't dissect anything without it... */ if (p_fp_info == NULL) { proto_tree_add_expert(fp_tree, pinfo, &ei_fp_no_per_frame_info, tvb, offset, -1); return 1; } rlcinf = (rlc_info *)p_get_proto_data(wmem_file_scope(), pinfo, proto_rlc, 0); /* Show release information */ if (preferences_show_release_info) { proto_item *release_ti; proto_tree *release_tree; proto_item *temp_ti; release_ti = proto_tree_add_item(fp_tree, hf_fp_release, tvb, 0, 0, ENC_NA); PROTO_ITEM_SET_GENERATED(release_ti); proto_item_append_text(release_ti, " R%u (%d/%d)", p_fp_info->release, p_fp_info->release_year, p_fp_info->release_month); release_tree = proto_item_add_subtree(release_ti, ett_fp_release); temp_ti = proto_tree_add_uint(release_tree, hf_fp_release_version, tvb, 0, 0, p_fp_info->release); PROTO_ITEM_SET_GENERATED(temp_ti); temp_ti = proto_tree_add_uint(release_tree, hf_fp_release_year, tvb, 0, 0, p_fp_info->release_year); PROTO_ITEM_SET_GENERATED(temp_ti); temp_ti = proto_tree_add_uint(release_tree, hf_fp_release_month, tvb, 0, 0, p_fp_info->release_month); PROTO_ITEM_SET_GENERATED(temp_ti); } /* Show channel type in info column, tree */ col_set_str(pinfo->cinfo, COL_INFO, val_to_str_const(p_fp_info->channel, channel_type_vals, "Unknown channel type")); if (p_conv_data) { int i; col_append_fstr(pinfo->cinfo, COL_INFO, "(%u", p_conv_data->dchs_in_flow_list[0]); for (i=1; i < p_conv_data->num_dch_in_flow; i++) { col_append_fstr(pinfo->cinfo, COL_INFO, ",%u", p_conv_data->dchs_in_flow_list[i]); } col_append_fstr(pinfo->cinfo, COL_INFO, ") "); } proto_item_append_text(ti, " (%s)", val_to_str_const(p_fp_info->channel, channel_type_vals, "Unknown channel type")); /* Add channel type as a generated field */ ti = proto_tree_add_uint(fp_tree, hf_fp_channel_type, tvb, 0, 0, p_fp_info->channel); PROTO_ITEM_SET_GENERATED(ti); /* Add division type as a generated field */ if (p_fp_info->release == 7) { ti = proto_tree_add_uint(fp_tree, hf_fp_division, tvb, 0, 0, p_fp_info->division); PROTO_ITEM_SET_GENERATED(ti); } /* Add link direction as a generated field */ ti = proto_tree_add_uint(fp_tree, hf_fp_direction, tvb, 0, 0, p_fp_info->is_uplink); PROTO_ITEM_SET_GENERATED(ti); /* Don't currently handle IuR-specific formats, but it's useful to even see the channel type and direction */ if (p_fp_info->iface_type == IuR_Interface) { return 1; } /* Show DDI config info */ if (p_fp_info->no_ddi_entries > 0) { int n; proto_item *ddi_config_ti; proto_tree *ddi_config_tree; ddi_config_ti = proto_tree_add_string_format(fp_tree, hf_fp_ddi_config, tvb, offset, 0, "", "DDI Config ("); PROTO_ITEM_SET_GENERATED(ddi_config_ti); ddi_config_tree = proto_item_add_subtree(ddi_config_ti, ett_fp_ddi_config); /* Add each entry */ for (n=0; n < p_fp_info->no_ddi_entries; n++) { proto_item_append_text(ddi_config_ti, "%s%u->%ubits", (n == 0) ? "" : " ", p_fp_info->edch_ddi[n], p_fp_info->edch_macd_pdu_size[n]); ti = proto_tree_add_uint(ddi_config_tree, hf_fp_ddi_config_ddi, tvb, 0, 0, p_fp_info->edch_ddi[n]); PROTO_ITEM_SET_GENERATED(ti); ti = proto_tree_add_uint(ddi_config_tree, hf_fp_ddi_config_macd_pdu_size, tvb, 0, 0, p_fp_info->edch_macd_pdu_size[n]); PROTO_ITEM_SET_GENERATED(ti); } proto_item_append_text(ddi_config_ti, ")"); } /*************************************/ /* Dissect according to channel type */ switch (p_fp_info->channel) { case CHANNEL_RACH_TDD: case CHANNEL_RACH_TDD_128: case CHANNEL_RACH_FDD: dissect_rach_channel_info(tvb, pinfo, fp_tree, offset, p_fp_info, data); break; case CHANNEL_DCH: dissect_dch_channel_info(tvb, pinfo, fp_tree, offset, p_fp_info, data); break; case CHANNEL_FACH_FDD: case CHANNEL_FACH_TDD: dissect_fach_channel_info(tvb, pinfo, fp_tree, offset, p_fp_info, data); break; case CHANNEL_DSCH_FDD: case CHANNEL_DSCH_TDD: dissect_dsch_channel_info(tvb, pinfo, fp_tree, offset, p_fp_info); break; case CHANNEL_USCH_TDD_128: case CHANNEL_USCH_TDD_384: dissect_usch_channel_info(tvb, pinfo, fp_tree, offset, p_fp_info); break; case CHANNEL_PCH: dissect_pch_channel_info(tvb, pinfo, fp_tree, offset, p_fp_info, data); break; case CHANNEL_CPCH: dissect_cpch_channel_info(tvb, pinfo, fp_tree, offset, p_fp_info); break; case CHANNEL_BCH: dissect_bch_channel_info(tvb, pinfo, fp_tree, offset, p_fp_info); break; case CHANNEL_HSDSCH: /* Show configured MAC HS-DSCH entity in use */ if (fp_tree) { proto_item *entity_ti; entity_ti = proto_tree_add_uint(fp_tree, hf_fp_hsdsch_entity, tvb, 0, 0, p_fp_info->hsdsch_entity); PROTO_ITEM_SET_GENERATED(entity_ti); } switch (p_fp_info->hsdsch_entity) { case entity_not_specified: case hs: /* This is the pre-R7 default */ dissect_hsdsch_channel_info(tvb, pinfo, fp_tree, offset, p_fp_info, data); break; case ehs: dissect_hsdsch_type_2_channel_info(tvb, pinfo, fp_tree, offset, p_fp_info, data); break; default: /* Report Error */ expert_add_info(pinfo, NULL, &ei_fp_hsdsch_entity_not_specified); break; } break; case CHANNEL_HSDSCH_COMMON: expert_add_info(pinfo, NULL, &ei_fp_hsdsch_common_experimental_support); /*if (FALSE)*/ dissect_hsdsch_common_channel_info(tvb, pinfo, fp_tree, offset, p_fp_info, data); break; case CHANNEL_HSDSCH_COMMON_T3: expert_add_info(pinfo, NULL, &ei_fp_hsdsch_common_t3_not_implemented); /* TODO: */ break; case CHANNEL_IUR_CPCHF: /* TODO: */ break; case CHANNEL_IUR_FACH: /* TODO: */ break; case CHANNEL_IUR_DSCH: dissect_iur_dsch_channel_info(tvb, pinfo, fp_tree, offset, p_fp_info); break; case CHANNEL_EDCH: case CHANNEL_EDCH_COMMON: dissect_e_dch_channel_info(tvb, pinfo, fp_tree, offset, p_fp_info, p_fp_info->channel == CHANNEL_EDCH_COMMON, rlcinf, data); break; default: expert_add_info(pinfo, NULL, &ei_fp_channel_type_unknown); break; } return tvb_captured_length(tvb); } static int dissect_fp(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_) { return dissect_fp_common(tvb, pinfo, tree, NULL); } static int dissect_fp_aal2(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data) { return dissect_fp_common(tvb, pinfo, tree, data); } #ifdef UMTS_FP_USE_UAT UAT_VS_DEF(uat_umts_fp_ep_and_ch_records, protocol, uat_umts_fp_ep_and_ch_record_t, guint8, UMTS_FP_IPV4, "IPv4") UAT_CSTRING_CB_DEF(uat_umts_fp_ep_and_ch_records, srcIP, uat_umts_fp_ep_and_ch_record_t) UAT_DEC_CB_DEF(uat_umts_fp_ep_and_ch_records, src_port, uat_umts_fp_ep_and_ch_record_t) UAT_CSTRING_CB_DEF(uat_umts_fp_ep_and_ch_records, dstIP, uat_umts_fp_ep_and_ch_record_t) UAT_DEC_CB_DEF(uat_umts_fp_ep_and_ch_records, dst_port, uat_umts_fp_ep_and_ch_record_t) UAT_VS_DEF(uat_umts_fp_ep_and_ch_records, interface_type, uat_umts_fp_ep_and_ch_record_t, guint8, IuB_Interface, "IuB Interface") UAT_VS_DEF(uat_umts_fp_ep_and_ch_records, division, uat_umts_fp_ep_and_ch_record_t, guint8, Division_FDD, "Division FDD") UAT_VS_DEF(uat_umts_fp_ep_and_ch_records, rlc_mode, uat_umts_fp_ep_and_ch_record_t, guint8, FP_RLC_TM, "RLC mode") UAT_VS_DEF(uat_umts_fp_ep_and_ch_records, channel_type, uat_umts_fp_ep_and_ch_record_t, guint8, CHANNEL_RACH_FDD, "RACH FDD") static void *uat_umts_fp_record_copy_cb(void *n, const void *o, size_t siz _U_) { uat_umts_fp_ep_and_ch_record_t *new_rec = (uat_umts_fp_ep_and_ch_record_t *)n; const uat_umts_fp_ep_and_ch_record_t *old_rec = (const uat_umts_fp_ep_and_ch_record_t *)o; new_rec->srcIP = (old_rec->srcIP) ? g_strdup(old_rec->srcIP) : NULL; new_rec->dstIP = (old_rec->dstIP) ? g_strdup(old_rec->dstIP) : NULL; return new_rec; } static void uat_umts_fp_record_free_cb(void*r) { uat_umts_fp_ep_and_ch_record_t *rec = (uat_umts_fp_ep_and_ch_record_t *)r; g_free(rec->srcIP); g_free(rec->dstIP); } /* * Set up UAT predefined conversations for specified channels * typedef struct { * guint8 protocol; * gchar *srcIP; * guint16 src_port; * gchar *dstIP; * guint16 dst_port; * guint8 interface_type; * guint8 division; * guint8 rlc_mode; * guint8 channel_type; * } uat_umts_fp_ep_and_ch_record_t; */ static void umts_fp_init_protocol(void) { guint32 hosta_addr[4]; guint32 hostb_addr[4]; address src_addr, dst_addr; conversation_t *conversation; umts_fp_conversation_info_t *umts_fp_conversation_info; guint i, j, num_tf; for (i=0; i<num_umts_fp_ep_and_ch_items; i++) { /* check if we have a conversation allready */ /* Convert the strings to ADDR */ if (uat_umts_fp_ep_and_ch_records[i].protocol == UMTS_FP_IPV4) { if ((uat_umts_fp_ep_and_ch_records[i].srcIP) && (!str_to_ip(uat_umts_fp_ep_and_ch_records[i].srcIP, &hosta_addr))) { continue; /* parsing failed, skip this entry */ } if ((uat_umts_fp_ep_and_ch_records[i].dstIP) && (!str_to_ip(uat_umts_fp_ep_and_ch_records[i].dstIP, &hostb_addr))) { continue; /* parsing failed, skip this entry */ } set_address(&src_addr, AT_IPv4, 4, &hosta_addr); set_address(&dst_addr, AT_IPv4, 4, &hostb_addr); } else { continue; /* Not implemented yet */ } conversation = find_conversation(1, &src_addr, &dst_addr, PT_UDP, uat_umts_fp_ep_and_ch_records[i].src_port, 0, NO_ADDR2|NO_PORT2); if (conversation == NULL) { /* It's not part of any conversation - create a new one. */ conversation = conversation_new(1, &src_addr, &dst_addr, PT_UDP, uat_umts_fp_ep_and_ch_records[i].src_port, 0, NO_ADDR2|NO_PORT2); if (conversation == NULL) continue; conversation_set_dissector(conversation, fp_handle); switch (uat_umts_fp_ep_and_ch_records[i].channel_type) { case CHANNEL_RACH_FDD: /* set up conversation info for RACH FDD channels */ umts_fp_conversation_info = wmem_new0(wmem_file_scope(), umts_fp_conversation_info_t); /* Fill in the data */ umts_fp_conversation_info->iface_type = (enum fp_interface_type)uat_umts_fp_ep_and_ch_records[i].interface_type; umts_fp_conversation_info->division = (enum division_type) uat_umts_fp_ep_and_ch_records[i].division; umts_fp_conversation_info->channel = uat_umts_fp_ep_and_ch_records[i].channel_type; umts_fp_conversation_info->dl_frame_number = 0; umts_fp_conversation_info->ul_frame_number = 1; copy_address_wmem(wmem_file_scope(), &(umts_fp_conversation_info->crnc_address), &src_addr); umts_fp_conversation_info->crnc_port = uat_umts_fp_ep_and_ch_records[i].src_port; umts_fp_conversation_info->rlc_mode = (enum fp_rlc_mode) uat_umts_fp_ep_and_ch_records[i].rlc_mode; /*Save unique UE-identifier */ umts_fp_conversation_info->com_context_id = 1; /* DCH's in this flow */ umts_fp_conversation_info->dch_crc_present = 2; /* Set data for First or single channel */ umts_fp_conversation_info->fp_dch_channel_info[0].num_ul_chans = num_tf = 1; for (j = 0; j < num_tf; j++) { umts_fp_conversation_info->fp_dch_channel_info[0].ul_chan_tf_size[j] = 168; umts_fp_conversation_info->fp_dch_channel_info[0].ul_chan_num_tbs[j] = 1; } umts_fp_conversation_info->dchs_in_flow_list[0] = 1; umts_fp_conversation_info->num_dch_in_flow=1; set_umts_fp_conv_data(conversation, umts_fp_conversation_info); default: break; } } } } #endif /* UMTS_FP_USE_UAT */ void proto_register_fp(void) { static hf_register_info hf[] = { { &hf_fp_release, { "Release", "fp.release", FT_NONE, BASE_NONE, NULL, 0x0, "Release information", HFILL } }, { &hf_fp_release_version, { "Release Version", "fp.release.version", FT_UINT8, BASE_DEC, NULL, 0x0, "3GPP Release number", HFILL } }, { &hf_fp_release_year, { "Release year", "fp.release.year", FT_UINT16, BASE_DEC, NULL, 0x0, NULL, HFILL } }, { &hf_fp_release_month, { "Release month", "fp.release.month", FT_UINT8, BASE_DEC, NULL, 0x0, NULL, HFILL } }, { &hf_fp_channel_type, { "Channel Type", "fp.channel-type", FT_UINT8, BASE_HEX, VALS(channel_type_vals), 0x0, NULL, HFILL } }, { &hf_fp_division, { "Division", "fp.division", FT_UINT8, BASE_HEX, VALS(division_vals), 0x0, "Radio division type", HFILL } }, { &hf_fp_direction, { "Direction", "fp.direction", FT_UINT8, BASE_HEX, VALS(direction_vals), 0x0, "Link direction", HFILL } }, { &hf_fp_ddi_config, { "DDI Config", "fp.ddi-config", FT_STRING, BASE_NONE, NULL, 0x0, "DDI Config (for E-DCH)", HFILL } }, { &hf_fp_ddi_config_ddi, { "DDI", "fp.ddi-config.ddi", FT_UINT8, BASE_DEC, NULL, 0x0, NULL, HFILL } }, { &hf_fp_ddi_config_macd_pdu_size, { "MACd PDU Size", "fp.ddi-config.macd-pdu-size", FT_UINT16, BASE_DEC, NULL, 0x0, NULL, HFILL } }, { &hf_fp_header_crc, { "Header CRC", "fp.header-crc", FT_UINT8, BASE_HEX, NULL, 0xfe, NULL, HFILL } }, { &hf_fp_ft, { "Frame Type", "fp.ft", FT_UINT8, BASE_HEX, VALS(data_control_vals), 0x01, NULL, HFILL } }, { &hf_fp_cfn, { "CFN", "fp.cfn", FT_UINT8, BASE_DEC, NULL, 0x0, "Connection Frame Number", HFILL } }, { &hf_fp_pch_cfn, { "CFN (PCH)", "fp.pch.cfn", FT_UINT16, BASE_DEC, NULL, 0xfff0, "PCH Connection Frame Number", HFILL } }, { &hf_fp_pch_toa, { "ToA (PCH)", "fp.pch.toa", FT_INT24, BASE_DEC, NULL, 0x0, "PCH Time of Arrival", HFILL } }, { &hf_fp_cfn_control, { "CFN control", "fp.cfn-control", FT_UINT8, BASE_DEC, NULL, 0x0, "Connection Frame Number Control", HFILL } }, { &hf_fp_toa, { "ToA", "fp.toa", FT_INT16, BASE_DEC, NULL, 0x0, "Time of arrival (units are 125 microseconds)", HFILL } }, { &hf_fp_tb, { "TB", "fp.tb", FT_BYTES, BASE_NONE, NULL, 0x0, "Transport Block", HFILL } }, { &hf_fp_chan_zero_tbs, { "No TBs for channel", "fp.channel-with-zero-tbs", FT_UINT32, BASE_DEC, NULL, 0x0, "Channel with 0 TBs", HFILL } }, { &hf_fp_tfi, { "TFI", "fp.tfi", FT_UINT8, BASE_DEC, NULL, 0x0, "Transport Format Indicator", HFILL } }, { &hf_fp_usch_tfi, { "TFI", "fp.usch.tfi", FT_UINT8, BASE_DEC, NULL, 0x1f, "USCH Transport Format Indicator", HFILL } }, { &hf_fp_cpch_tfi, { "TFI", "fp.cpch.tfi", FT_UINT8, BASE_DEC, NULL, 0x1f, "CPCH Transport Format Indicator", HFILL } }, { &hf_fp_propagation_delay, { "Propagation Delay", "fp.propagation-delay", FT_UINT8, BASE_DEC, NULL, 0x0, NULL, HFILL } }, { &hf_fp_dch_control_frame_type, { "Control Frame Type", "fp.dch.control.frame-type", FT_UINT8, BASE_HEX, VALS(dch_control_frame_type_vals), 0x0, "DCH Control Frame Type", HFILL } }, { &hf_fp_dch_rx_timing_deviation, { "Rx Timing Deviation", "fp.dch.control.rx-timing-deviation", FT_UINT8, BASE_DEC, 0, 0x0, "DCH Rx Timing Deviation", HFILL } }, { &hf_fp_quality_estimate, { "Quality Estimate", "fp.dch.quality-estimate", FT_UINT8, BASE_DEC, 0, 0x0, NULL, HFILL } }, { &hf_fp_payload_crc, { "Payload CRC", "fp.payload-crc", FT_UINT16, BASE_HEX, 0, 0x0, NULL, HFILL } }, { &hf_fp_common_control_frame_type, { "Control Frame Type", "fp.common.control.frame-type", FT_UINT8, BASE_HEX, VALS(common_control_frame_type_vals), 0x0, "Common Control Frame Type", HFILL } }, { &hf_fp_crci[0], { "CRCI", "fp.crci", FT_UINT8, BASE_HEX, VALS(crci_vals), 0x80, "CRC correctness indicator", HFILL } }, { &hf_fp_crci[1], { "CRCI", "fp.crci", FT_UINT8, BASE_HEX, VALS(crci_vals), 0x40, "CRC correctness indicator", HFILL } }, { &hf_fp_crci[2], { "CRCI", "fp.crci", FT_UINT8, BASE_HEX, VALS(crci_vals), 0x20, "CRC correctness indicator", HFILL } }, { &hf_fp_crci[3], { "CRCI", "fp.crci", FT_UINT8, BASE_HEX, VALS(crci_vals), 0x10, "CRC correctness indicator", HFILL } }, { &hf_fp_crci[4], { "CRCI", "fp.crci", FT_UINT8, BASE_HEX, VALS(crci_vals), 0x08, "CRC correctness indicator", HFILL } }, { &hf_fp_crci[5], { "CRCI", "fp.crci", FT_UINT8, BASE_HEX, VALS(crci_vals), 0x04, "CRC correctness indicator", HFILL } }, { &hf_fp_crci[6], { "CRCI", "fp.crci", FT_UINT8, BASE_HEX, VALS(crci_vals), 0x02, "CRC correctness indicator", HFILL } }, { &hf_fp_crci[7], { "CRCI", "fp.crci", FT_UINT8, BASE_HEX, VALS(crci_vals), 0x01, "CRC correctness indicator", HFILL } }, { &hf_fp_received_sync_ul_timing_deviation, { "Received SYNC UL Timing Deviation", "fp.rx-sync-ul-timing-deviation", FT_UINT8, BASE_DEC, 0, 0x0, NULL, HFILL } }, { &hf_fp_pch_pi, { "Paging Indication", "fp.pch.pi", FT_UINT8, BASE_DEC, VALS(paging_indication_vals), 0x01, "Indicates if the PI Bitmap is present", HFILL } }, { &hf_fp_pch_tfi, { "TFI", "fp.pch.tfi", FT_UINT8, BASE_DEC, 0, 0x1f, "PCH Transport Format Indicator", HFILL } }, { &hf_fp_fach_tfi, { "TFI", "fp.fach.tfi", FT_UINT8, BASE_DEC, 0, 0x1f, "FACH Transport Format Indicator", HFILL } }, { &hf_fp_transmit_power_level, { "Transmit Power Level", "fp.transmit-power-level", FT_FLOAT, BASE_NONE, 0, 0x0, "Transmit Power Level (dB)", HFILL } }, { &hf_fp_pdsch_set_id, { "PDSCH Set Id", "fp.pdsch-set-id", FT_UINT8, BASE_DEC, 0, 0x0, "A pointer to the PDSCH Set which shall be used to transmit", HFILL } }, { &hf_fp_paging_indication_bitmap, { "Paging Indications bitmap", "fp.pch.pi-bitmap", FT_NONE, BASE_NONE, NULL, 0x0, "Paging Indication bitmap", HFILL } }, { &hf_fp_rx_timing_deviation, { "Rx Timing Deviation", "fp.common.control.rx-timing-deviation", FT_UINT8, BASE_DEC, 0, 0x0, "Common Rx Timing Deviation", HFILL } }, { &hf_fp_dch_e_rucch_flag, { "E-RUCCH Flag", "fp.common.control.e-rucch-flag", FT_UINT8, BASE_DEC, VALS(e_rucch_flag_vals), 0x0, NULL, HFILL } }, { &hf_fp_edch_header_crc, { "E-DCH Header CRC", "fp.edch.header-crc", FT_UINT16, BASE_HEX, 0, 0, NULL, HFILL } }, { &hf_fp_edch_fsn, { "FSN", "fp.edch.fsn", FT_UINT8, BASE_DEC, 0, 0x0f, "E-DCH Frame Sequence Number", HFILL } }, { &hf_fp_edch_number_of_subframes, { "No of subframes", "fp.edch.no-of-subframes", FT_UINT8, BASE_DEC, 0, 0x0f, "E-DCH Number of subframes", HFILL } }, { &hf_fp_edch_harq_retransmissions, { "No of HARQ Retransmissions", "fp.edch.no-of-harq-retransmissions", FT_UINT8, BASE_DEC, 0, 0x78, "E-DCH Number of HARQ retransmissions", HFILL } }, { &hf_fp_edch_subframe_number, { "Subframe number", "fp.edch.subframe-number", FT_UINT8, BASE_DEC, 0, 0x0, "E-DCH Subframe number", HFILL } }, { &hf_fp_edch_number_of_mac_es_pdus, { "Number of Mac-es PDUs", "fp.edch.number-of-mac-es-pdus", FT_UINT8, BASE_DEC, 0, 0xf0, NULL, HFILL } }, { &hf_fp_edch_ddi, { "DDI", "fp.edch.ddi", FT_UINT8, BASE_DEC, 0, 0x0, "E-DCH Data Description Indicator", HFILL } }, { &hf_fp_edch_subframe, { "Subframe", "fp.edch.subframe", FT_STRING, BASE_NONE, NULL, 0x0, "EDCH Subframe", HFILL } }, { &hf_fp_edch_subframe_header, { "Subframe header", "fp.edch.subframe-header", FT_STRING, BASE_NONE, NULL, 0x0, "EDCH Subframe header", HFILL } }, { &hf_fp_edch_number_of_mac_d_pdus, { "Number of Mac-d PDUs", "fp.edch.number-of-mac-d-pdus", FT_UINT8, BASE_DEC, 0, 0x0, NULL, HFILL } }, { &hf_fp_edch_pdu_padding, { "Padding", "fp.edch-data-padding", FT_UINT8, BASE_DEC, 0, 0xc0, "E-DCH padding before PDU", HFILL } }, { &hf_fp_edch_tsn, { "TSN", "fp.edch-tsn", FT_UINT8, BASE_DEC, 0, 0x3f, "E-DCH Transmission Sequence Number", HFILL } }, { &hf_fp_edch_mac_es_pdu, { "MAC-es PDU", "fp.edch.mac-es-pdu", FT_NONE, BASE_NONE, NULL, 0x0, NULL, HFILL } }, { &hf_fp_edch_user_buffer_size, { "User Buffer Size", "fp.edch.user-buffer-size", FT_UINT24, BASE_DEC, NULL, 0x0, NULL, HFILL } }, { &hf_fp_edch_no_macid_sdus, { "No of MAC-is SDUs", "fp.edch.no-macis-sdus", FT_UINT16, BASE_DEC, NULL, 0x0, NULL, HFILL } }, { &hf_fp_edch_number_of_mac_is_pdus, { "Number of Mac-is PDUs", "fp.edch.number-of-mac-is-pdus", FT_UINT8, BASE_DEC, 0, 0x0, NULL, HFILL } }, { &hf_fp_edch_mac_is_pdu, { "Mac-is PDU", "fp.edch.mac-is-pdu", FT_BYTES, BASE_NONE, 0, 0x0, NULL, HFILL } }, { &hf_fp_edch_e_rnti, { "E-RNTI", "fp.edch.e-rnti", FT_UINT16, BASE_DEC, 0, 0x0, NULL, HFILL } }, { &hf_fp_edch_macis_descriptors, { "MAC-is Descriptors", "fp.edch.mac-is.descriptors", FT_STRING, BASE_NONE, NULL, 0x0, NULL, HFILL } }, { &hf_fp_edch_macis_lchid, { "LCH-ID", "fp.edch.mac-is.lchid", FT_UINT8, BASE_HEX, VALS(lchid_vals), 0xf0, NULL, HFILL } }, { &hf_fp_edch_macis_length, { "Length", "fp.edch.mac-is.length", FT_UINT16, BASE_DEC, 0, 0x0ffe, NULL, HFILL } }, { &hf_fp_edch_macis_flag, { "Flag", "fp.edch.mac-is.lchid", FT_UINT8, BASE_HEX, 0, 0x01, "Indicates if another entry follows", HFILL } }, { &hf_fp_frame_seq_nr, { "Frame Seq Nr", "fp.frame-seq-nr", FT_UINT8, BASE_DEC, 0, 0xf0, "Frame Sequence Number", HFILL } }, { &hf_fp_hsdsch_pdu_block_header, { "PDU block header", "fp.hsdsch.pdu-block-header", FT_STRING, BASE_NONE, NULL, 0x0, "HS-DSCH type 2 PDU block header", HFILL } }, #if 0 { &hf_fp_hsdsch_pdu_block, { "PDU block", "fp.hsdsch.pdu-block", FT_STRING, BASE_NONE, NULL, 0x0, "HS-DSCH type 2 PDU block data", HFILL } }, #endif { &hf_fp_flush, { "Flush", "fp.flush", FT_UINT8, BASE_DEC, 0, 0x04, "Whether all PDUs for this priority queue should be removed", HFILL } }, { &hf_fp_fsn_drt_reset, { "FSN-DRT reset", "fp.fsn-drt-reset", FT_UINT8, BASE_DEC, 0, 0x02, "FSN/DRT Reset Flag", HFILL } }, { &hf_fp_drt_indicator, { "DRT Indicator", "fp.drt-indicator", FT_UINT8, BASE_DEC, 0, 0x01, NULL, HFILL } }, { &hf_fp_fach_indicator, { "FACH Indicator", "fp.fach-indicator", FT_UINT8, BASE_DEC, 0, 0x80, NULL, HFILL } }, { &hf_fp_total_pdu_blocks, { "PDU Blocks", "fp.pdu_blocks", FT_UINT8, BASE_DEC, 0, 0xf8, "Total number of PDU blocks", HFILL } }, { &hf_fp_drt, { "DelayRefTime", "fp.drt", FT_UINT16, BASE_DEC, 0, 0x0, NULL, HFILL } }, { &hf_fp_hrnti, { "HRNTI", "fp.hrnti", FT_UINT16, BASE_DEC, 0, 0x0, NULL, HFILL } }, { &hf_fp_rach_measurement_result, { "RACH Measurement Result", "fp.rach-measurement-result", FT_UINT16, BASE_DEC, 0, 0x0, NULL, HFILL } }, { &hf_fp_lchid, { "Logical Channel ID", "fp.lchid", FT_UINT8, BASE_DEC, NULL, 0x0, NULL, HFILL } }, { &hf_fp_pdu_length_in_block, { "PDU length in block", "fp.pdu-length-in-block", FT_UINT8, BASE_DEC, 0, 0x0, "Length of each PDU in this block in bytes", HFILL } }, { &hf_fp_pdus_in_block, { "PDUs in block", "fp.no-pdus-in-block", FT_UINT8, BASE_DEC, 0, 0x0, "Number of PDUs in block", HFILL } }, { &hf_fp_cmch_pi, { "CmCH-PI", "fp.cmch-pi", FT_UINT8, BASE_DEC, 0, 0x0f, "Common Transport Channel Priority Indicator", HFILL } }, { &hf_fp_user_buffer_size, { "User buffer size", "fp.user-buffer-size", FT_UINT16, BASE_DEC, 0, 0x0, "User buffer size in octets", HFILL } }, { &hf_fp_hsdsch_credits, { "HS-DSCH Credits", "fp.hsdsch-credits", FT_UINT16, BASE_DEC, 0, 0x0, NULL, HFILL } }, { &hf_fp_hsdsch_max_macd_pdu_len, { "Max MAC-d PDU Length", "fp.hsdsch.max-macd-pdu-len", FT_UINT16, BASE_DEC, 0, 0xfff8, "Maximum MAC-d PDU Length in bits", HFILL } }, { &hf_fp_hsdsch_max_macdc_pdu_len, { "Max MAC-d/c PDU Length", "fp.hsdsch.max-macdc-pdu-len", FT_UINT16, BASE_DEC, 0, 0x07ff, "Maximum MAC-d/c PDU Length in bits", HFILL } }, { &hf_fp_hsdsch_interval, { "HS-DSCH Interval in milliseconds", "fp.hsdsch-interval", FT_UINT8, BASE_DEC, 0, 0x0, NULL, HFILL } }, { &hf_fp_hsdsch_calculated_rate, { "Calculated rate allocation (bps)", "fp.hsdsch-calculated-rate", FT_UINT32, BASE_DEC, 0, 0x0, "Calculated rate RNC is allowed to send in bps", HFILL } }, { &hf_fp_hsdsch_unlimited_rate, { "Unlimited rate", "fp.hsdsch-unlimited-rate", FT_NONE, BASE_NONE, 0, 0x0, "No restriction on rate at which date may be sent", HFILL } }, { &hf_fp_hsdsch_repetition_period, { "HS-DSCH Repetition Period", "fp.hsdsch-repetition-period", FT_UINT8, BASE_DEC, 0, 0x0, "HS-DSCH Repetition Period in milliseconds", HFILL } }, { &hf_fp_hsdsch_data_padding, { "Padding", "fp.hsdsch-data-padding", FT_UINT8, BASE_DEC, 0, 0xf0, "HS-DSCH Repetition Period in milliseconds", HFILL } }, { &hf_fp_hsdsch_new_ie_flags, { "New IEs flags", "fp.hsdsch.new-ie-flags", FT_STRING, BASE_NONE, 0, 0x0, NULL, HFILL } }, { &hf_fp_hsdsch_new_ie_flag[0], { "DRT IE present", "fp.hsdsch.new-ie-flag", FT_UINT8, BASE_DEC, 0, 0x80, NULL, HFILL } }, { &hf_fp_hsdsch_new_ie_flag[1], { "New IE present", "fp.hsdsch.new-ie-flag", FT_UINT8, BASE_DEC, 0, 0x40, NULL, HFILL } }, { &hf_fp_hsdsch_new_ie_flag[2], { "New IE present", "fp.hsdsch.new-ie-flag", FT_UINT8, BASE_DEC, 0, 0x20, NULL, HFILL } }, { &hf_fp_hsdsch_new_ie_flag[3], { "New IE present", "fp.hsdsch.new-ie-flag", FT_UINT8, BASE_DEC, 0, 0x10, NULL, HFILL } }, { &hf_fp_hsdsch_new_ie_flag[4], { "New IE present", "fp.hsdsch.new-ie-flag", FT_UINT8, BASE_DEC, 0, 0x08, NULL, HFILL } }, { &hf_fp_hsdsch_new_ie_flag[5], { "New IE present", "fp.hsdsch.new-ie-flag", FT_UINT8, BASE_DEC, 0, 0x04, NULL, HFILL } }, { &hf_fp_hsdsch_new_ie_flag[6], { "HS-DSCH physical layer category present", "fp.hsdsch.new-ie-flag", FT_UINT8, BASE_DEC, 0, 0x02, NULL, HFILL } }, { &hf_fp_hsdsch_new_ie_flag[7], { "Another new IE flags byte", "fp.hsdsch.new-ie-flags-byte", FT_UINT8, BASE_DEC, 0, 0x01, "Another new IE flagsbyte", HFILL } }, { &hf_fp_hsdsch_drt, { "DRT", "fp.hsdsch.drt", FT_UINT8, BASE_DEC, 0, 0xf0, "Delay Reference Time", HFILL } }, { &hf_fp_hsdsch_entity, { "HS-DSCH Entity", "fp.hsdsch.entity", FT_UINT8, BASE_DEC, VALS(hsdshc_mac_entity_vals), 0x0, "Type of MAC entity for this HS-DSCH channel", HFILL } }, { &hf_fp_timing_advance, { "Timing advance", "fp.timing-advance", FT_UINT8, BASE_DEC, 0, 0x3f, "Timing advance in chips", HFILL } }, { &hf_fp_num_of_pdu, { "Number of PDUs", "fp.hsdsch.num-of-pdu", FT_UINT8, BASE_DEC, 0, 0x0, "Number of PDUs in the payload", HFILL } }, { &hf_fp_mac_d_pdu_len, { "MAC-d PDU Length", "fp.hsdsch.mac-d-pdu-len", FT_UINT16, BASE_DEC, 0, 0xfff8, "MAC-d PDU Length in bits", HFILL } }, { &hf_fp_mac_d_pdu, { "MAC-d PDU", "fp.mac-d-pdu", FT_BYTES, BASE_NONE, NULL, 0x0, NULL, HFILL } }, { &hf_fp_data, { "Data", "fp.data", FT_BYTES, BASE_NONE, NULL, 0x0, NULL, HFILL } }, { &hf_fp_crcis, { "CRCIs", "fp.crcis", FT_BYTES, BASE_NONE, NULL, 0x0, "CRC Indicators for uplink TBs", HFILL } }, { &hf_fp_t1, { "T1", "fp.t1", FT_UINT24, BASE_DEC, NULL, 0x0, "RNC frame number indicating time it sends frame", HFILL } }, { &hf_fp_t2, { "T2", "fp.t2", FT_UINT24, BASE_DEC, NULL, 0x0, "NodeB frame number indicating time it received DL Sync", HFILL } }, { &hf_fp_t3, { "T3", "fp.t3", FT_UINT24, BASE_DEC, NULL, 0x0, "NodeB frame number indicating time it sends frame", HFILL } }, { &hf_fp_ul_sir_target, { "UL_SIR_TARGET", "fp.ul-sir-target", FT_FLOAT, BASE_NONE, 0, 0x0, "Value (in dB) of the SIR target to be used by the UL inner loop power control", HFILL } }, { &hf_fp_pusch_set_id, { "PUSCH Set Id", "fp.pusch-set-id", FT_UINT8, BASE_DEC, NULL, 0x0, "Identifies PUSCH Set from those configured in NodeB", HFILL } }, { &hf_fp_activation_cfn, { "Activation CFN", "fp.activation-cfn", FT_UINT8, BASE_DEC, NULL, 0x0, "Activation Connection Frame Number", HFILL } }, { &hf_fp_duration, { "Duration (ms)", "fp.pusch-set-id", FT_UINT8, BASE_DEC, NULL, 0x0, "Duration of the activation period of the PUSCH Set", HFILL } }, { &hf_fp_power_offset, { "Power offset", "fp.power-offset", FT_FLOAT, BASE_NONE, NULL, 0x0, "Power offset (in dB)", HFILL } }, { &hf_fp_code_number, { "Code number", "fp.code-number", FT_UINT8, BASE_DEC, NULL, 0x0, NULL, HFILL } }, { &hf_fp_spreading_factor, { "Spreading factor", "fp.spreading-factor", FT_UINT8, BASE_DEC, VALS(spreading_factor_vals), 0xf0, NULL, HFILL } }, { &hf_fp_mc_info, { "MC info", "fp.mc-info", FT_UINT8, BASE_DEC, NULL, 0x0e, NULL, HFILL } }, { &hf_fp_rach_new_ie_flags, { "New IEs flags", "fp.rach.new-ie-flags", FT_STRING, BASE_NONE, 0, 0x0, NULL, HFILL } }, { &hf_fp_rach_new_ie_flag_unused[0], { "New IE present", "fp.rach.new-ie-flag", FT_UINT8, BASE_DEC, 0, 0x80, NULL, HFILL } }, { &hf_fp_rach_new_ie_flag_unused[1], { "New IE present", "fp.rach.new-ie-flag", FT_UINT8, BASE_DEC, 0, 0x40, NULL, HFILL } }, { &hf_fp_rach_new_ie_flag_unused[2], { "New IE present", "fp.rach.new-ie-flag", FT_UINT8, BASE_DEC, 0, 0x20, "New IE present (unused)", HFILL } }, { &hf_fp_rach_new_ie_flag_unused[3], { "New IE present", "fp.rach.new-ie-flag", FT_UINT8, BASE_DEC, 0, 0x10, "New IE present (unused)", HFILL } }, { &hf_fp_rach_new_ie_flag_unused[4], { "New IE present", "fp.rach.new-ie-flag", FT_UINT8, BASE_DEC, 0, 0x08, "New IE present (unused)", HFILL } }, { &hf_fp_rach_new_ie_flag_unused[5], { "New IE present", "fp.rach.new-ie-flag", FT_UINT8, BASE_DEC, 0, 0x04, "New IE present (unused)", HFILL } }, { &hf_fp_rach_new_ie_flag_unused[6], { "New IE present", "fp.rach.new-ie-flag", FT_UINT8, BASE_DEC, 0, 0x02, "New IE present (unused)", HFILL } }, { &hf_fp_rach_cell_portion_id_present, { "Cell portion ID present", "fp.rach.cell-portion-id-present", FT_UINT8, BASE_DEC, 0, 0x01, NULL, HFILL } }, { &hf_fp_rach_angle_of_arrival_present, { "Angle of arrival present", "fp.rach.angle-of-arrival-present", FT_UINT8, BASE_DEC, 0, 0x01, NULL, HFILL } }, { &hf_fp_rach_ext_propagation_delay_present, { "Ext Propagation Delay Present", "fp.rach.ext-propagation-delay-present", FT_UINT8, BASE_DEC, 0, 0x02, NULL, HFILL } }, { &hf_fp_rach_ext_rx_sync_ul_timing_deviation_present, { "Ext Received Sync UL Timing Deviation present", "fp.rach.ext-rx-sync-ul-timing-deviation-present", FT_UINT8, BASE_DEC, 0, 0x02, NULL, HFILL } }, { &hf_fp_rach_ext_rx_timing_deviation_present, { "Ext Rx Timing Deviation present", "fp.rach.ext-rx-timing-deviation-present", FT_UINT8, BASE_DEC, 0, 0x01, NULL, HFILL } }, { &hf_fp_cell_portion_id, { "Cell Portion ID", "fp.cell-portion-id", FT_UINT8, BASE_DEC, NULL, 0x3f, NULL, HFILL } }, { &hf_fp_ext_propagation_delay, { "Ext Propagation Delay", "fp.ext-propagation-delay", FT_UINT16, BASE_DEC, NULL, 0x03ff, NULL, HFILL } }, { &hf_fp_angle_of_arrival, { "Angle of Arrival", "fp.angle-of-arrival", FT_UINT16, BASE_DEC, NULL, 0x03ff, NULL, HFILL } }, { &hf_fp_ext_received_sync_ul_timing_deviation, { "Ext Received SYNC UL Timing Deviation", "fp.ext-received-sync-ul-timing-deviation", FT_UINT16, BASE_DEC, NULL, 0x1fff, NULL, HFILL } }, { &hf_fp_radio_interface_parameter_update_flag[0], { "CFN valid", "fp.radio-interface-param.cfn-valid", FT_UINT16, BASE_DEC, 0, 0x0001, NULL, HFILL } }, { &hf_fp_radio_interface_parameter_update_flag[1], { "TPC PO valid", "fp.radio-interface-param.tpc-po-valid", FT_UINT16, BASE_DEC, 0, 0x0002, NULL, HFILL } }, { &hf_fp_radio_interface_parameter_update_flag[2], { "DPC mode valid", "fp.radio-interface-param.dpc-mode-valid", FT_UINT16, BASE_DEC, 0, 0x0004, NULL, HFILL } }, { &hf_fp_radio_interface_parameter_update_flag[3], { "RL sets indicator valid", "fp.radio-interface_param.rl-sets-indicator-valid", FT_UINT16, BASE_DEC, 0, 0x0020, NULL, HFILL } }, { &hf_fp_radio_interface_parameter_update_flag[4], { "MAX_UE_TX_POW valid", "fp.radio-interface-param.max-ue-tx-pow-valid", FT_UINT16, BASE_DEC, 0, 0x0040, "MAX UE TX POW valid", HFILL } }, { &hf_fp_dpc_mode, { "DPC Mode", "fp.dpc-mode", FT_UINT8, BASE_DEC, NULL, 0x20, "DPC Mode to be applied in the uplink", HFILL } }, { &hf_fp_tpc_po, { "TPC PO", "fp.tpc-po", FT_UINT8, BASE_DEC, NULL, 0x1f, NULL, HFILL } }, { &hf_fp_multiple_rl_set_indicator, { "Multiple RL sets indicator", "fp.multiple-rl-sets-indicator", FT_UINT8, BASE_DEC, NULL, 0x80, NULL, HFILL } }, { &hf_fp_max_ue_tx_pow, { "MAX_UE_TX_POW", "fp.max-ue-tx-pow", FT_INT8, BASE_DEC, NULL, 0x0, "Max UE TX POW (dBm)", HFILL } }, { &hf_fp_congestion_status, { "Congestion Status", "fp.congestion-status", FT_UINT8, BASE_DEC, VALS(congestion_status_vals), 0x0, NULL, HFILL } }, { &hf_fp_e_rucch_present, { "E-RUCCH Present", "fp.erucch-present", FT_UINT8, BASE_DEC, NULL, 0x0, NULL, HFILL } }, { &hf_fp_extended_bits_present, { "Extended Bits Present", "fp.extended-bits-present", FT_UINT8, BASE_DEC, NULL, 0x0, NULL, HFILL } }, { &hf_fp_extended_bits, { "Extended Bits", "fp.extended-bits", FT_UINT8, BASE_HEX, NULL, 0x0, NULL, HFILL } }, { &hf_fp_spare_extension, { "Spare Extension", "fp.spare-extension", FT_NONE, BASE_NONE, NULL, 0x0, NULL, HFILL } }, { &hf_fp_ul_setup_frame, { "UL setup frame", "fp.ul.setup_frame", FT_FRAMENUM, BASE_NONE, NULL, 0x0, NULL, HFILL } }, { &hf_fp_dl_setup_frame, { "DL setup frame", "fp.dl.setup_frame", FT_FRAMENUM, BASE_NONE, NULL, 0x0, NULL, HFILL } }, { &hf_fp_hsdsch_physical_layer_category, { "HS-DSCH physical layer category", "fp.hsdsch.physical_layer_category", FT_UINT8, BASE_DEC, NULL, 0x0, NULL, HFILL } } }; static gint *ett[] = { &ett_fp, &ett_fp_data, &ett_fp_crcis, &ett_fp_ddi_config, &ett_fp_edch_subframe_header, &ett_fp_edch_subframe, &ett_fp_edch_maces, &ett_fp_edch_macis_descriptors, &ett_fp_hsdsch_new_ie_flags, &ett_fp_rach_new_ie_flags, &ett_fp_hsdsch_pdu_block_header, &ett_fp_release }; static ei_register_info ei[] = { { &ei_fp_bad_header_checksum, { "fp.header.bad_checksum.", PI_CHECKSUM, PI_WARN, "Bad header checksum.", EXPFILL }}, { &ei_fp_crci_no_subdissector, { "fp.crci.no_subdissector", PI_UNDECODED, PI_NOTE, "Not sent to subdissectors as CRCI is set", EXPFILL }}, { &ei_fp_crci_error_bit_set_for_tb, { "fp.crci.error_bit_set_for_tb", PI_CHECKSUM, PI_WARN, "CRCI error bit set for TB", EXPFILL }}, { &ei_fp_spare_extension, { "fp.spare-extension.expert", PI_UNDECODED, PI_WARN, "Spare Extension present (%u bytes)", EXPFILL }}, { &ei_fp_bad_payload_checksum, { "fp.payload-crc.bad.", PI_CHECKSUM, PI_WARN, "Bad payload checksum.", EXPFILL }}, { &ei_fp_stop_hsdpa_transmission, { "fp.stop_hsdpa_transmission", PI_RESPONSE_CODE, PI_NOTE, "Stop HSDPA transmission", EXPFILL }}, { &ei_fp_timing_adjustmentment_reported, { "fp.timing_adjustmentment_reported", PI_SEQUENCE, PI_WARN, "Timing adjustmentment reported (%f ms)", EXPFILL }}, { &ei_fp_expecting_tdd, { "fp.expecting_tdd", PI_MALFORMED, PI_NOTE, "Error: expecting TDD-384 or TDD-768", EXPFILL }}, { &ei_fp_ddi_not_defined, { "fp.ddi_not_defined", PI_MALFORMED, PI_ERROR, "DDI %u not defined for this UE!", EXPFILL }}, { &ei_fp_unable_to_locate_ddi_entry, { "fp.unable_to_locate_ddi_entry", PI_UNDECODED, PI_ERROR, "Unable to locate DDI entry.", EXPFILL }}, { &ei_fp_mac_is_sdus_miscount, { "fp.mac_is_sdus.miscount", PI_MALFORMED, PI_ERROR, "Found too many (%u) MAC-is SDUs - header said there were %u", EXPFILL }}, { &ei_fp_e_rnti_t2_edch_frames, { "fp.e_rnti.t2_edch_frames", PI_MALFORMED, PI_ERROR, "E-RNTI not supposed to appear for T2 EDCH frames", EXPFILL }}, { &ei_fp_e_rnti_first_entry, { "fp.e_rnti.first_entry", PI_MALFORMED, PI_ERROR, "E-RNTI must be first entry among descriptors", EXPFILL }}, { &ei_fp_maybe_srb, { "fp.maybe_srb", PI_PROTOCOL, PI_NOTE, "Found MACd-Flow = 0 and not MUX detected. (This might be SRB)", EXPFILL }}, { &ei_fp_transport_channel_type_unknown, { "fp.transport_channel_type.unknown", PI_UNDECODED, PI_WARN, "Unknown transport channel type", EXPFILL }}, { &ei_fp_hsdsch_entity_not_specified, { "fp.hsdsch_entity_not_specified", PI_MALFORMED, PI_ERROR, "HSDSCH Entity not specified", EXPFILL }}, { &ei_fp_hsdsch_common_experimental_support, { "fp.hsdsch_common.experimental_support", PI_DEBUG, PI_WARN, "HSDSCH COMMON - Experimental support!", EXPFILL }}, { &ei_fp_hsdsch_common_t3_not_implemented, { "fp.hsdsch_common_t3.not_implemented", PI_DEBUG, PI_ERROR, "HSDSCH COMMON T3 - Not implemeneted!", EXPFILL }}, { &ei_fp_channel_type_unknown, { "fp.channel_type.unknown", PI_MALFORMED, PI_ERROR, "Unknown channel type", EXPFILL }}, { &ei_fp_no_per_frame_info, { "fp.no_per_frame_info", PI_UNDECODED, PI_ERROR, "Can't dissect FP frame because no per-frame info was attached!", EXPFILL }}, }; module_t *fp_module; expert_module_t *expert_fp; #ifdef UMTS_FP_USE_UAT /* Define a UAT to set channel configuration data */ static const value_string umts_fp_proto_type_vals[] = { { UMTS_FP_IPV4, "IPv4" }, { UMTS_FP_IPV6, "IPv6" }, { 0x00, NULL } }; static const value_string umts_fp_uat_channel_type_vals[] = { { CHANNEL_RACH_FDD, "RACH FDD" }, { 0x00, NULL } }; static const value_string umts_fp_uat_interface_type_vals[] = { { IuB_Interface, "IuB Interface" }, { 0x00, NULL } }; static const value_string umts_fp_uat_division_type_vals[] = { { Division_FDD, "Division FDD" }, { 0x00, NULL } }; static const value_string umts_fp_uat_rlc_mode_vals[] = { { FP_RLC_TM, "FP RLC TM" }, { 0x00, NULL } }; static uat_field_t umts_fp_uat_flds[] = { UAT_FLD_VS(uat_umts_fp_ep_and_ch_records, protocol, "IP address type", umts_fp_proto_type_vals, "IPv4 or IPv6"), UAT_FLD_CSTRING(uat_umts_fp_ep_and_ch_records, srcIP, "RNC IP Address", "Source Address"), UAT_FLD_DEC(uat_umts_fp_ep_and_ch_records, src_port, "RNC port for this channel", "Source port"), UAT_FLD_CSTRING(uat_umts_fp_ep_and_ch_records, dstIP, "NodeB IP Address", "Destination Address"), UAT_FLD_DEC(uat_umts_fp_ep_and_ch_records, dst_port, "NodeB port for this channel", "Destination port"), UAT_FLD_VS(uat_umts_fp_ep_and_ch_records, interface_type, "Interface type", umts_fp_uat_interface_type_vals, "Interface type used"), UAT_FLD_VS(uat_umts_fp_ep_and_ch_records, division, "division", umts_fp_uat_division_type_vals, "Division type used"), UAT_FLD_VS(uat_umts_fp_ep_and_ch_records, channel_type, "Channel type", umts_fp_uat_channel_type_vals, "Channel type used"), UAT_FLD_VS(uat_umts_fp_ep_and_ch_records, rlc_mode, "RLC mode", umts_fp_uat_rlc_mode_vals, "RLC mode used"), UAT_END_FIELDS }; #endif /* UMTS_FP_USE_UAT */ /* Register protocol. */ proto_fp = proto_register_protocol("FP", "FP", "fp"); proto_register_field_array(proto_fp, hf, array_length(hf)); proto_register_subtree_array(ett, array_length(ett)); expert_fp = expert_register_protocol(proto_fp); expert_register_field_array(expert_fp, ei, array_length(ei)); /* Allow other dissectors to find this one by name. */ fp_handle = register_dissector("fp", dissect_fp, proto_fp); /* Preferences */ fp_module = prefs_register_protocol(proto_fp, NULL); /* Determines whether release information should be displayed */ prefs_register_bool_preference(fp_module, "show_release_info", "Show reported release info", "Show reported release info", &preferences_show_release_info); /* Determines whether MAC dissector should be called for payloads */ prefs_register_bool_preference(fp_module, "call_mac", "Call MAC dissector for payloads", "Call MAC dissector for payloads", &preferences_call_mac_dissectors); /* Determines whether or not to validate FP payload checksums */ prefs_register_bool_preference(fp_module, "payload_checksum", "Validate FP payload checksums", "Validate FP payload checksums", &preferences_payload_checksum); /* Determines whether or not to validate FP header checksums */ prefs_register_bool_preference(fp_module, "header_checksum", "Validate FP header checksums", "Validate FP header checksums", &preferences_header_checksum); /* Determines whether or not to validate FP header checksums */ prefs_register_obsolete_preference(fp_module, "udp_heur"); #ifdef UMTS_FP_USE_UAT umts_fp_uat = uat_new("Endpoint and Channel Configuration", sizeof(uat_umts_fp_ep_and_ch_record_t), /* record size */ "umts_fp_ep_and_channel_cnf", /* filename */ TRUE, /* from_profile */ &uat_umts_fp_ep_and_ch_records, /* data_ptr */ &num_umts_fp_ep_and_ch_items, /* numitems_ptr */ UAT_AFFECTS_DISSECTION, /* affects dissection of packets, but not set of named fields */ NULL, /* help */ uat_umts_fp_record_copy_cb, /* copy callback */ NULL, /* update callback */ uat_umts_fp_record_free_cb, /* free callback */ NULL, /* post update callback */ umts_fp_uat_flds); /* UAT field definitions */ prefs_register_uat_preference(fp_module, "epandchannelconfigurationtable", "Endpoints and Radio Channels configuration", "Preconfigured endpoint and Channels data", umts_fp_uat); register_init_routine(&umts_fp_init_protocol); #endif } void proto_reg_handoff_fp(void) { dissector_handle_t fp_aal2_handle; rlc_bcch_handle = find_dissector_add_dependency("rlc.bcch", proto_fp); mac_fdd_rach_handle = find_dissector_add_dependency("mac.fdd.rach", proto_fp); mac_fdd_fach_handle = find_dissector_add_dependency("mac.fdd.fach", proto_fp); mac_fdd_pch_handle = find_dissector_add_dependency("mac.fdd.pch", proto_fp); mac_fdd_dch_handle = find_dissector_add_dependency("mac.fdd.dch", proto_fp); mac_fdd_edch_handle = find_dissector_add_dependency("mac.fdd.edch", proto_fp); mac_fdd_edch_type2_handle = find_dissector_add_dependency("mac.fdd.edch.type2", proto_fp); mac_fdd_hsdsch_handle = find_dissector_add_dependency("mac.fdd.hsdsch", proto_fp); heur_dissector_add("udp", heur_dissect_fp, "FP over UDP", "fp_udp", proto_fp, HEURISTIC_DISABLE); fp_aal2_handle = create_dissector_handle(dissect_fp_aal2, proto_fp); dissector_add_uint("atm.aal2.type", TRAF_UMTS_FP, fp_aal2_handle); } /* * Editor modelines - http://www.wireshark.org/tools/modelines.html * * Local variables: * c-basic-offset: 4 * tab-width: 8 * indent-tabs-mode: nil * End: * * vi: set shiftwidth=4 tabstop=8 expandtab: * :indentSize=4:tabSize=8:noTabs=true: */
./CrossVul/dataset_final_sorted/CWE-20/c/bad_5107_0
crossvul-cpp_data_bad_5845_6
/* net/atm/common.c - ATM sockets (common part for PVC and SVC) */ /* Written 1995-2000 by Werner Almesberger, EPFL LRC/ICA */ #define pr_fmt(fmt) KBUILD_MODNAME ":%s: " fmt, __func__ #include <linux/module.h> #include <linux/kmod.h> #include <linux/net.h> /* struct socket, struct proto_ops */ #include <linux/atm.h> /* ATM stuff */ #include <linux/atmdev.h> #include <linux/socket.h> /* SOL_SOCKET */ #include <linux/errno.h> /* error codes */ #include <linux/capability.h> #include <linux/mm.h> #include <linux/sched.h> #include <linux/time.h> /* struct timeval */ #include <linux/skbuff.h> #include <linux/bitops.h> #include <linux/init.h> #include <linux/slab.h> #include <net/sock.h> /* struct sock */ #include <linux/uaccess.h> #include <linux/poll.h> #include <linux/atomic.h> #include "resources.h" /* atm_find_dev */ #include "common.h" /* prototypes */ #include "protocols.h" /* atm_init_<transport> */ #include "addr.h" /* address registry */ #include "signaling.h" /* for WAITING and sigd_attach */ struct hlist_head vcc_hash[VCC_HTABLE_SIZE]; EXPORT_SYMBOL(vcc_hash); DEFINE_RWLOCK(vcc_sklist_lock); EXPORT_SYMBOL(vcc_sklist_lock); static ATOMIC_NOTIFIER_HEAD(atm_dev_notify_chain); static void __vcc_insert_socket(struct sock *sk) { struct atm_vcc *vcc = atm_sk(sk); struct hlist_head *head = &vcc_hash[vcc->vci & (VCC_HTABLE_SIZE - 1)]; sk->sk_hash = vcc->vci & (VCC_HTABLE_SIZE - 1); sk_add_node(sk, head); } void vcc_insert_socket(struct sock *sk) { write_lock_irq(&vcc_sklist_lock); __vcc_insert_socket(sk); write_unlock_irq(&vcc_sklist_lock); } EXPORT_SYMBOL(vcc_insert_socket); static void vcc_remove_socket(struct sock *sk) { write_lock_irq(&vcc_sklist_lock); sk_del_node_init(sk); write_unlock_irq(&vcc_sklist_lock); } static struct sk_buff *alloc_tx(struct atm_vcc *vcc, unsigned int size) { struct sk_buff *skb; struct sock *sk = sk_atm(vcc); if (sk_wmem_alloc_get(sk) && !atm_may_send(vcc, size)) { pr_debug("Sorry: wmem_alloc = %d, size = %d, sndbuf = %d\n", sk_wmem_alloc_get(sk), size, sk->sk_sndbuf); return NULL; } while (!(skb = alloc_skb(size, GFP_KERNEL))) schedule(); pr_debug("%d += %d\n", sk_wmem_alloc_get(sk), skb->truesize); atomic_add(skb->truesize, &sk->sk_wmem_alloc); return skb; } static void vcc_sock_destruct(struct sock *sk) { if (atomic_read(&sk->sk_rmem_alloc)) printk(KERN_DEBUG "%s: rmem leakage (%d bytes) detected.\n", __func__, atomic_read(&sk->sk_rmem_alloc)); if (atomic_read(&sk->sk_wmem_alloc)) printk(KERN_DEBUG "%s: wmem leakage (%d bytes) detected.\n", __func__, atomic_read(&sk->sk_wmem_alloc)); } static void vcc_def_wakeup(struct sock *sk) { struct socket_wq *wq; rcu_read_lock(); wq = rcu_dereference(sk->sk_wq); if (wq_has_sleeper(wq)) wake_up(&wq->wait); rcu_read_unlock(); } static inline int vcc_writable(struct sock *sk) { struct atm_vcc *vcc = atm_sk(sk); return (vcc->qos.txtp.max_sdu + atomic_read(&sk->sk_wmem_alloc)) <= sk->sk_sndbuf; } static void vcc_write_space(struct sock *sk) { struct socket_wq *wq; rcu_read_lock(); if (vcc_writable(sk)) { wq = rcu_dereference(sk->sk_wq); if (wq_has_sleeper(wq)) wake_up_interruptible(&wq->wait); sk_wake_async(sk, SOCK_WAKE_SPACE, POLL_OUT); } rcu_read_unlock(); } static void vcc_release_cb(struct sock *sk) { struct atm_vcc *vcc = atm_sk(sk); if (vcc->release_cb) vcc->release_cb(vcc); } static struct proto vcc_proto = { .name = "VCC", .owner = THIS_MODULE, .obj_size = sizeof(struct atm_vcc), .release_cb = vcc_release_cb, }; int vcc_create(struct net *net, struct socket *sock, int protocol, int family) { struct sock *sk; struct atm_vcc *vcc; sock->sk = NULL; if (sock->type == SOCK_STREAM) return -EINVAL; sk = sk_alloc(net, family, GFP_KERNEL, &vcc_proto); if (!sk) return -ENOMEM; sock_init_data(sock, sk); sk->sk_state_change = vcc_def_wakeup; sk->sk_write_space = vcc_write_space; vcc = atm_sk(sk); vcc->dev = NULL; memset(&vcc->local, 0, sizeof(struct sockaddr_atmsvc)); memset(&vcc->remote, 0, sizeof(struct sockaddr_atmsvc)); vcc->qos.txtp.max_sdu = 1 << 16; /* for meta VCs */ atomic_set(&sk->sk_wmem_alloc, 1); atomic_set(&sk->sk_rmem_alloc, 0); vcc->push = NULL; vcc->pop = NULL; vcc->owner = NULL; vcc->push_oam = NULL; vcc->release_cb = NULL; vcc->vpi = vcc->vci = 0; /* no VCI/VPI yet */ vcc->atm_options = vcc->aal_options = 0; sk->sk_destruct = vcc_sock_destruct; return 0; } static void vcc_destroy_socket(struct sock *sk) { struct atm_vcc *vcc = atm_sk(sk); struct sk_buff *skb; set_bit(ATM_VF_CLOSE, &vcc->flags); clear_bit(ATM_VF_READY, &vcc->flags); if (vcc->dev) { if (vcc->dev->ops->close) vcc->dev->ops->close(vcc); if (vcc->push) vcc->push(vcc, NULL); /* atmarpd has no push */ module_put(vcc->owner); while ((skb = skb_dequeue(&sk->sk_receive_queue)) != NULL) { atm_return(vcc, skb->truesize); kfree_skb(skb); } module_put(vcc->dev->ops->owner); atm_dev_put(vcc->dev); } vcc_remove_socket(sk); } int vcc_release(struct socket *sock) { struct sock *sk = sock->sk; if (sk) { lock_sock(sk); vcc_destroy_socket(sock->sk); release_sock(sk); sock_put(sk); } return 0; } void vcc_release_async(struct atm_vcc *vcc, int reply) { struct sock *sk = sk_atm(vcc); set_bit(ATM_VF_CLOSE, &vcc->flags); sk->sk_shutdown |= RCV_SHUTDOWN; sk->sk_err = -reply; clear_bit(ATM_VF_WAITING, &vcc->flags); sk->sk_state_change(sk); } EXPORT_SYMBOL(vcc_release_async); void vcc_process_recv_queue(struct atm_vcc *vcc) { struct sk_buff_head queue, *rq; struct sk_buff *skb, *tmp; unsigned long flags; __skb_queue_head_init(&queue); rq = &sk_atm(vcc)->sk_receive_queue; spin_lock_irqsave(&rq->lock, flags); skb_queue_splice_init(rq, &queue); spin_unlock_irqrestore(&rq->lock, flags); skb_queue_walk_safe(&queue, skb, tmp) { __skb_unlink(skb, &queue); vcc->push(vcc, skb); } } EXPORT_SYMBOL(vcc_process_recv_queue); void atm_dev_signal_change(struct atm_dev *dev, char signal) { pr_debug("%s signal=%d dev=%p number=%d dev->signal=%d\n", __func__, signal, dev, dev->number, dev->signal); /* atm driver sending invalid signal */ WARN_ON(signal < ATM_PHY_SIG_LOST || signal > ATM_PHY_SIG_FOUND); if (dev->signal == signal) return; /* no change */ dev->signal = signal; atomic_notifier_call_chain(&atm_dev_notify_chain, signal, dev); } EXPORT_SYMBOL(atm_dev_signal_change); void atm_dev_release_vccs(struct atm_dev *dev) { int i; write_lock_irq(&vcc_sklist_lock); for (i = 0; i < VCC_HTABLE_SIZE; i++) { struct hlist_head *head = &vcc_hash[i]; struct hlist_node *tmp; struct sock *s; struct atm_vcc *vcc; sk_for_each_safe(s, tmp, head) { vcc = atm_sk(s); if (vcc->dev == dev) { vcc_release_async(vcc, -EPIPE); sk_del_node_init(s); } } } write_unlock_irq(&vcc_sklist_lock); } EXPORT_SYMBOL(atm_dev_release_vccs); static int adjust_tp(struct atm_trafprm *tp, unsigned char aal) { int max_sdu; if (!tp->traffic_class) return 0; switch (aal) { case ATM_AAL0: max_sdu = ATM_CELL_SIZE-1; break; case ATM_AAL34: max_sdu = ATM_MAX_AAL34_PDU; break; default: pr_warning("AAL problems ... (%d)\n", aal); /* fall through */ case ATM_AAL5: max_sdu = ATM_MAX_AAL5_PDU; } if (!tp->max_sdu) tp->max_sdu = max_sdu; else if (tp->max_sdu > max_sdu) return -EINVAL; if (!tp->max_cdv) tp->max_cdv = ATM_MAX_CDV; return 0; } static int check_ci(const struct atm_vcc *vcc, short vpi, int vci) { struct hlist_head *head = &vcc_hash[vci & (VCC_HTABLE_SIZE - 1)]; struct sock *s; struct atm_vcc *walk; sk_for_each(s, head) { walk = atm_sk(s); if (walk->dev != vcc->dev) continue; if (test_bit(ATM_VF_ADDR, &walk->flags) && walk->vpi == vpi && walk->vci == vci && ((walk->qos.txtp.traffic_class != ATM_NONE && vcc->qos.txtp.traffic_class != ATM_NONE) || (walk->qos.rxtp.traffic_class != ATM_NONE && vcc->qos.rxtp.traffic_class != ATM_NONE))) return -EADDRINUSE; } /* allow VCCs with same VPI/VCI iff they don't collide on TX/RX (but we may refuse such sharing for other reasons, e.g. if protocol requires to have both channels) */ return 0; } static int find_ci(const struct atm_vcc *vcc, short *vpi, int *vci) { static short p; /* poor man's per-device cache */ static int c; short old_p; int old_c; int err; if (*vpi != ATM_VPI_ANY && *vci != ATM_VCI_ANY) { err = check_ci(vcc, *vpi, *vci); return err; } /* last scan may have left values out of bounds for current device */ if (*vpi != ATM_VPI_ANY) p = *vpi; else if (p >= 1 << vcc->dev->ci_range.vpi_bits) p = 0; if (*vci != ATM_VCI_ANY) c = *vci; else if (c < ATM_NOT_RSV_VCI || c >= 1 << vcc->dev->ci_range.vci_bits) c = ATM_NOT_RSV_VCI; old_p = p; old_c = c; do { if (!check_ci(vcc, p, c)) { *vpi = p; *vci = c; return 0; } if (*vci == ATM_VCI_ANY) { c++; if (c >= 1 << vcc->dev->ci_range.vci_bits) c = ATM_NOT_RSV_VCI; } if ((c == ATM_NOT_RSV_VCI || *vci != ATM_VCI_ANY) && *vpi == ATM_VPI_ANY) { p++; if (p >= 1 << vcc->dev->ci_range.vpi_bits) p = 0; } } while (old_p != p || old_c != c); return -EADDRINUSE; } static int __vcc_connect(struct atm_vcc *vcc, struct atm_dev *dev, short vpi, int vci) { struct sock *sk = sk_atm(vcc); int error; if ((vpi != ATM_VPI_UNSPEC && vpi != ATM_VPI_ANY && vpi >> dev->ci_range.vpi_bits) || (vci != ATM_VCI_UNSPEC && vci != ATM_VCI_ANY && vci >> dev->ci_range.vci_bits)) return -EINVAL; if (vci > 0 && vci < ATM_NOT_RSV_VCI && !capable(CAP_NET_BIND_SERVICE)) return -EPERM; error = -ENODEV; if (!try_module_get(dev->ops->owner)) return error; vcc->dev = dev; write_lock_irq(&vcc_sklist_lock); if (test_bit(ATM_DF_REMOVED, &dev->flags) || (error = find_ci(vcc, &vpi, &vci))) { write_unlock_irq(&vcc_sklist_lock); goto fail_module_put; } vcc->vpi = vpi; vcc->vci = vci; __vcc_insert_socket(sk); write_unlock_irq(&vcc_sklist_lock); switch (vcc->qos.aal) { case ATM_AAL0: error = atm_init_aal0(vcc); vcc->stats = &dev->stats.aal0; break; case ATM_AAL34: error = atm_init_aal34(vcc); vcc->stats = &dev->stats.aal34; break; case ATM_NO_AAL: /* ATM_AAL5 is also used in the "0 for default" case */ vcc->qos.aal = ATM_AAL5; /* fall through */ case ATM_AAL5: error = atm_init_aal5(vcc); vcc->stats = &dev->stats.aal5; break; default: error = -EPROTOTYPE; } if (!error) error = adjust_tp(&vcc->qos.txtp, vcc->qos.aal); if (!error) error = adjust_tp(&vcc->qos.rxtp, vcc->qos.aal); if (error) goto fail; pr_debug("VCC %d.%d, AAL %d\n", vpi, vci, vcc->qos.aal); pr_debug(" TX: %d, PCR %d..%d, SDU %d\n", vcc->qos.txtp.traffic_class, vcc->qos.txtp.min_pcr, vcc->qos.txtp.max_pcr, vcc->qos.txtp.max_sdu); pr_debug(" RX: %d, PCR %d..%d, SDU %d\n", vcc->qos.rxtp.traffic_class, vcc->qos.rxtp.min_pcr, vcc->qos.rxtp.max_pcr, vcc->qos.rxtp.max_sdu); if (dev->ops->open) { error = dev->ops->open(vcc); if (error) goto fail; } return 0; fail: vcc_remove_socket(sk); fail_module_put: module_put(dev->ops->owner); /* ensure we get dev module ref count correct */ vcc->dev = NULL; return error; } int vcc_connect(struct socket *sock, int itf, short vpi, int vci) { struct atm_dev *dev; struct atm_vcc *vcc = ATM_SD(sock); int error; pr_debug("(vpi %d, vci %d)\n", vpi, vci); if (sock->state == SS_CONNECTED) return -EISCONN; if (sock->state != SS_UNCONNECTED) return -EINVAL; if (!(vpi || vci)) return -EINVAL; if (vpi != ATM_VPI_UNSPEC && vci != ATM_VCI_UNSPEC) clear_bit(ATM_VF_PARTIAL, &vcc->flags); else if (test_bit(ATM_VF_PARTIAL, &vcc->flags)) return -EINVAL; pr_debug("(TX: cl %d,bw %d-%d,sdu %d; " "RX: cl %d,bw %d-%d,sdu %d,AAL %s%d)\n", vcc->qos.txtp.traffic_class, vcc->qos.txtp.min_pcr, vcc->qos.txtp.max_pcr, vcc->qos.txtp.max_sdu, vcc->qos.rxtp.traffic_class, vcc->qos.rxtp.min_pcr, vcc->qos.rxtp.max_pcr, vcc->qos.rxtp.max_sdu, vcc->qos.aal == ATM_AAL5 ? "" : vcc->qos.aal == ATM_AAL0 ? "" : " ??? code ", vcc->qos.aal == ATM_AAL0 ? 0 : vcc->qos.aal); if (!test_bit(ATM_VF_HASQOS, &vcc->flags)) return -EBADFD; if (vcc->qos.txtp.traffic_class == ATM_ANYCLASS || vcc->qos.rxtp.traffic_class == ATM_ANYCLASS) return -EINVAL; if (likely(itf != ATM_ITF_ANY)) { dev = try_then_request_module(atm_dev_lookup(itf), "atm-device-%d", itf); } else { dev = NULL; mutex_lock(&atm_dev_mutex); if (!list_empty(&atm_devs)) { dev = list_entry(atm_devs.next, struct atm_dev, dev_list); atm_dev_hold(dev); } mutex_unlock(&atm_dev_mutex); } if (!dev) return -ENODEV; error = __vcc_connect(vcc, dev, vpi, vci); if (error) { atm_dev_put(dev); return error; } if (vpi == ATM_VPI_UNSPEC || vci == ATM_VCI_UNSPEC) set_bit(ATM_VF_PARTIAL, &vcc->flags); if (test_bit(ATM_VF_READY, &ATM_SD(sock)->flags)) sock->state = SS_CONNECTED; return 0; } int vcc_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t size, int flags) { struct sock *sk = sock->sk; struct atm_vcc *vcc; struct sk_buff *skb; int copied, error = -EINVAL; msg->msg_namelen = 0; if (sock->state != SS_CONNECTED) return -ENOTCONN; /* only handle MSG_DONTWAIT and MSG_PEEK */ if (flags & ~(MSG_DONTWAIT | MSG_PEEK)) return -EOPNOTSUPP; vcc = ATM_SD(sock); if (test_bit(ATM_VF_RELEASED, &vcc->flags) || test_bit(ATM_VF_CLOSE, &vcc->flags) || !test_bit(ATM_VF_READY, &vcc->flags)) return 0; skb = skb_recv_datagram(sk, flags, flags & MSG_DONTWAIT, &error); if (!skb) return error; copied = skb->len; if (copied > size) { copied = size; msg->msg_flags |= MSG_TRUNC; } error = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied); if (error) return error; sock_recv_ts_and_drops(msg, sk, skb); if (!(flags & MSG_PEEK)) { pr_debug("%d -= %d\n", atomic_read(&sk->sk_rmem_alloc), skb->truesize); atm_return(vcc, skb->truesize); } skb_free_datagram(sk, skb); return copied; } int vcc_sendmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *m, size_t total_len) { struct sock *sk = sock->sk; DEFINE_WAIT(wait); struct atm_vcc *vcc; struct sk_buff *skb; int eff, error; const void __user *buff; int size; lock_sock(sk); if (sock->state != SS_CONNECTED) { error = -ENOTCONN; goto out; } if (m->msg_name) { error = -EISCONN; goto out; } if (m->msg_iovlen != 1) { error = -ENOSYS; /* fix this later @@@ */ goto out; } buff = m->msg_iov->iov_base; size = m->msg_iov->iov_len; vcc = ATM_SD(sock); if (test_bit(ATM_VF_RELEASED, &vcc->flags) || test_bit(ATM_VF_CLOSE, &vcc->flags) || !test_bit(ATM_VF_READY, &vcc->flags)) { error = -EPIPE; send_sig(SIGPIPE, current, 0); goto out; } if (!size) { error = 0; goto out; } if (size < 0 || size > vcc->qos.txtp.max_sdu) { error = -EMSGSIZE; goto out; } eff = (size+3) & ~3; /* align to word boundary */ prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE); error = 0; while (!(skb = alloc_tx(vcc, eff))) { if (m->msg_flags & MSG_DONTWAIT) { error = -EAGAIN; break; } schedule(); if (signal_pending(current)) { error = -ERESTARTSYS; break; } if (test_bit(ATM_VF_RELEASED, &vcc->flags) || test_bit(ATM_VF_CLOSE, &vcc->flags) || !test_bit(ATM_VF_READY, &vcc->flags)) { error = -EPIPE; send_sig(SIGPIPE, current, 0); break; } prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE); } finish_wait(sk_sleep(sk), &wait); if (error) goto out; skb->dev = NULL; /* for paths shared with net_device interfaces */ ATM_SKB(skb)->atm_options = vcc->atm_options; if (copy_from_user(skb_put(skb, size), buff, size)) { kfree_skb(skb); error = -EFAULT; goto out; } if (eff != size) memset(skb->data + size, 0, eff-size); error = vcc->dev->ops->send(vcc, skb); error = error ? error : size; out: release_sock(sk); return error; } unsigned int vcc_poll(struct file *file, struct socket *sock, poll_table *wait) { struct sock *sk = sock->sk; struct atm_vcc *vcc; unsigned int mask; sock_poll_wait(file, sk_sleep(sk), wait); mask = 0; vcc = ATM_SD(sock); /* exceptional events */ if (sk->sk_err) mask = POLLERR; if (test_bit(ATM_VF_RELEASED, &vcc->flags) || test_bit(ATM_VF_CLOSE, &vcc->flags)) mask |= POLLHUP; /* readable? */ if (!skb_queue_empty(&sk->sk_receive_queue)) mask |= POLLIN | POLLRDNORM; /* writable? */ if (sock->state == SS_CONNECTING && test_bit(ATM_VF_WAITING, &vcc->flags)) return mask; if (vcc->qos.txtp.traffic_class != ATM_NONE && vcc_writable(sk)) mask |= POLLOUT | POLLWRNORM | POLLWRBAND; return mask; } static int atm_change_qos(struct atm_vcc *vcc, struct atm_qos *qos) { int error; /* * Don't let the QoS change the already connected AAL type nor the * traffic class. */ if (qos->aal != vcc->qos.aal || qos->rxtp.traffic_class != vcc->qos.rxtp.traffic_class || qos->txtp.traffic_class != vcc->qos.txtp.traffic_class) return -EINVAL; error = adjust_tp(&qos->txtp, qos->aal); if (!error) error = adjust_tp(&qos->rxtp, qos->aal); if (error) return error; if (!vcc->dev->ops->change_qos) return -EOPNOTSUPP; if (sk_atm(vcc)->sk_family == AF_ATMPVC) return vcc->dev->ops->change_qos(vcc, qos, ATM_MF_SET); return svc_change_qos(vcc, qos); } static int check_tp(const struct atm_trafprm *tp) { /* @@@ Should be merged with adjust_tp */ if (!tp->traffic_class || tp->traffic_class == ATM_ANYCLASS) return 0; if (tp->traffic_class != ATM_UBR && !tp->min_pcr && !tp->pcr && !tp->max_pcr) return -EINVAL; if (tp->min_pcr == ATM_MAX_PCR) return -EINVAL; if (tp->min_pcr && tp->max_pcr && tp->max_pcr != ATM_MAX_PCR && tp->min_pcr > tp->max_pcr) return -EINVAL; /* * We allow pcr to be outside [min_pcr,max_pcr], because later * adjustment may still push it in the valid range. */ return 0; } static int check_qos(const struct atm_qos *qos) { int error; if (!qos->txtp.traffic_class && !qos->rxtp.traffic_class) return -EINVAL; if (qos->txtp.traffic_class != qos->rxtp.traffic_class && qos->txtp.traffic_class && qos->rxtp.traffic_class && qos->txtp.traffic_class != ATM_ANYCLASS && qos->rxtp.traffic_class != ATM_ANYCLASS) return -EINVAL; error = check_tp(&qos->txtp); if (error) return error; return check_tp(&qos->rxtp); } int vcc_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen) { struct atm_vcc *vcc; unsigned long value; int error; if (__SO_LEVEL_MATCH(optname, level) && optlen != __SO_SIZE(optname)) return -EINVAL; vcc = ATM_SD(sock); switch (optname) { case SO_ATMQOS: { struct atm_qos qos; if (copy_from_user(&qos, optval, sizeof(qos))) return -EFAULT; error = check_qos(&qos); if (error) return error; if (sock->state == SS_CONNECTED) return atm_change_qos(vcc, &qos); if (sock->state != SS_UNCONNECTED) return -EBADFD; vcc->qos = qos; set_bit(ATM_VF_HASQOS, &vcc->flags); return 0; } case SO_SETCLP: if (get_user(value, (unsigned long __user *)optval)) return -EFAULT; if (value) vcc->atm_options |= ATM_ATMOPT_CLP; else vcc->atm_options &= ~ATM_ATMOPT_CLP; return 0; default: if (level == SOL_SOCKET) return -EINVAL; break; } if (!vcc->dev || !vcc->dev->ops->setsockopt) return -EINVAL; return vcc->dev->ops->setsockopt(vcc, level, optname, optval, optlen); } int vcc_getsockopt(struct socket *sock, int level, int optname, char __user *optval, int __user *optlen) { struct atm_vcc *vcc; int len; if (get_user(len, optlen)) return -EFAULT; if (__SO_LEVEL_MATCH(optname, level) && len != __SO_SIZE(optname)) return -EINVAL; vcc = ATM_SD(sock); switch (optname) { case SO_ATMQOS: if (!test_bit(ATM_VF_HASQOS, &vcc->flags)) return -EINVAL; return copy_to_user(optval, &vcc->qos, sizeof(vcc->qos)) ? -EFAULT : 0; case SO_SETCLP: return put_user(vcc->atm_options & ATM_ATMOPT_CLP ? 1 : 0, (unsigned long __user *)optval) ? -EFAULT : 0; case SO_ATMPVC: { struct sockaddr_atmpvc pvc; if (!vcc->dev || !test_bit(ATM_VF_ADDR, &vcc->flags)) return -ENOTCONN; memset(&pvc, 0, sizeof(pvc)); pvc.sap_family = AF_ATMPVC; pvc.sap_addr.itf = vcc->dev->number; pvc.sap_addr.vpi = vcc->vpi; pvc.sap_addr.vci = vcc->vci; return copy_to_user(optval, &pvc, sizeof(pvc)) ? -EFAULT : 0; } default: if (level == SOL_SOCKET) return -EINVAL; break; } if (!vcc->dev || !vcc->dev->ops->getsockopt) return -EINVAL; return vcc->dev->ops->getsockopt(vcc, level, optname, optval, len); } int register_atmdevice_notifier(struct notifier_block *nb) { return atomic_notifier_chain_register(&atm_dev_notify_chain, nb); } EXPORT_SYMBOL_GPL(register_atmdevice_notifier); void unregister_atmdevice_notifier(struct notifier_block *nb) { atomic_notifier_chain_unregister(&atm_dev_notify_chain, nb); } EXPORT_SYMBOL_GPL(unregister_atmdevice_notifier); static int __init atm_init(void) { int error; error = proto_register(&vcc_proto, 0); if (error < 0) goto out; error = atmpvc_init(); if (error < 0) { pr_err("atmpvc_init() failed with %d\n", error); goto out_unregister_vcc_proto; } error = atmsvc_init(); if (error < 0) { pr_err("atmsvc_init() failed with %d\n", error); goto out_atmpvc_exit; } error = atm_proc_init(); if (error < 0) { pr_err("atm_proc_init() failed with %d\n", error); goto out_atmsvc_exit; } error = atm_sysfs_init(); if (error < 0) { pr_err("atm_sysfs_init() failed with %d\n", error); goto out_atmproc_exit; } out: return error; out_atmproc_exit: atm_proc_exit(); out_atmsvc_exit: atmsvc_exit(); out_atmpvc_exit: atmsvc_exit(); out_unregister_vcc_proto: proto_unregister(&vcc_proto); goto out; } static void __exit atm_exit(void) { atm_proc_exit(); atm_sysfs_exit(); atmsvc_exit(); atmpvc_exit(); proto_unregister(&vcc_proto); } subsys_initcall(atm_init); module_exit(atm_exit); MODULE_LICENSE("GPL"); MODULE_ALIAS_NETPROTO(PF_ATMPVC); MODULE_ALIAS_NETPROTO(PF_ATMSVC);
./CrossVul/dataset_final_sorted/CWE-20/c/bad_5845_6
crossvul-cpp_data_good_3547_2
/* * 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. * * Copyright (C) Jonathan Naylor G4KLX (g4klx@g4klx.demon.co.uk) */ #include <linux/types.h> #include <linux/slab.h> #include <linux/socket.h> #include <linux/timer.h> #include <net/ax25.h> #include <linux/skbuff.h> #include <net/rose.h> #include <linux/init.h> static struct sk_buff_head loopback_queue; static struct timer_list loopback_timer; static void rose_set_loopback_timer(void); void rose_loopback_init(void) { skb_queue_head_init(&loopback_queue); init_timer(&loopback_timer); } static int rose_loopback_running(void) { return timer_pending(&loopback_timer); } int rose_loopback_queue(struct sk_buff *skb, struct rose_neigh *neigh) { struct sk_buff *skbn; skbn = skb_clone(skb, GFP_ATOMIC); kfree_skb(skb); if (skbn != NULL) { skb_queue_tail(&loopback_queue, skbn); if (!rose_loopback_running()) rose_set_loopback_timer(); } return 1; } static void rose_loopback_timer(unsigned long); static void rose_set_loopback_timer(void) { del_timer(&loopback_timer); loopback_timer.data = 0; loopback_timer.function = &rose_loopback_timer; loopback_timer.expires = jiffies + 10; add_timer(&loopback_timer); } static void rose_loopback_timer(unsigned long param) { struct sk_buff *skb; struct net_device *dev; rose_address *dest; struct sock *sk; unsigned short frametype; unsigned int lci_i, lci_o; while ((skb = skb_dequeue(&loopback_queue)) != NULL) { if (skb->len < ROSE_MIN_LEN) { kfree_skb(skb); continue; } lci_i = ((skb->data[0] << 8) & 0xF00) + ((skb->data[1] << 0) & 0x0FF); frametype = skb->data[2]; if (frametype == ROSE_CALL_REQUEST && (skb->len <= ROSE_CALL_REQ_FACILITIES_OFF || skb->data[ROSE_CALL_REQ_ADDR_LEN_OFF] != ROSE_CALL_REQ_ADDR_LEN_VAL)) { kfree_skb(skb); continue; } dest = (rose_address *)(skb->data + ROSE_CALL_REQ_DEST_ADDR_OFF); lci_o = ROSE_DEFAULT_MAXVC + 1 - lci_i; skb_reset_transport_header(skb); sk = rose_find_socket(lci_o, rose_loopback_neigh); if (sk) { if (rose_process_rx_frame(sk, skb) == 0) kfree_skb(skb); continue; } if (frametype == ROSE_CALL_REQUEST) { if ((dev = rose_dev_get(dest)) != NULL) { if (rose_rx_call_request(skb, dev, rose_loopback_neigh, lci_o) == 0) kfree_skb(skb); } else { kfree_skb(skb); } } else { kfree_skb(skb); } } } void __exit rose_loopback_clear(void) { struct sk_buff *skb; del_timer(&loopback_timer); while ((skb = skb_dequeue(&loopback_queue)) != NULL) { skb->sk = NULL; kfree_skb(skb); } }
./CrossVul/dataset_final_sorted/CWE-20/c/good_3547_2
crossvul-cpp_data_bad_2391_0
/* * linux/fs/isofs/rock.c * * (C) 1992, 1993 Eric Youngdale * * Rock Ridge Extensions to iso9660 */ #include <linux/slab.h> #include <linux/pagemap.h> #include "isofs.h" #include "rock.h" /* * These functions are designed to read the system areas of a directory record * and extract relevant information. There are different functions provided * depending upon what information we need at the time. One function fills * out an inode structure, a second one extracts a filename, a third one * returns a symbolic link name, and a fourth one returns the extent number * for the file. */ #define SIG(A,B) ((A) | ((B) << 8)) /* isonum_721() */ struct rock_state { void *buffer; unsigned char *chr; int len; int cont_size; int cont_extent; int cont_offset; int cont_loops; struct inode *inode; }; /* * This is a way of ensuring that we have something in the system * use fields that is compatible with Rock Ridge. Return zero on success. */ static int check_sp(struct rock_ridge *rr, struct inode *inode) { if (rr->u.SP.magic[0] != 0xbe) return -1; if (rr->u.SP.magic[1] != 0xef) return -1; ISOFS_SB(inode->i_sb)->s_rock_offset = rr->u.SP.skip; return 0; } static void setup_rock_ridge(struct iso_directory_record *de, struct inode *inode, struct rock_state *rs) { rs->len = sizeof(struct iso_directory_record) + de->name_len[0]; if (rs->len & 1) (rs->len)++; rs->chr = (unsigned char *)de + rs->len; rs->len = *((unsigned char *)de) - rs->len; if (rs->len < 0) rs->len = 0; if (ISOFS_SB(inode->i_sb)->s_rock_offset != -1) { rs->len -= ISOFS_SB(inode->i_sb)->s_rock_offset; rs->chr += ISOFS_SB(inode->i_sb)->s_rock_offset; if (rs->len < 0) rs->len = 0; } } static void init_rock_state(struct rock_state *rs, struct inode *inode) { memset(rs, 0, sizeof(*rs)); rs->inode = inode; } /* Maximum number of Rock Ridge continuation entries */ #define RR_MAX_CE_ENTRIES 32 /* * Returns 0 if the caller should continue scanning, 1 if the scan must end * and -ve on error. */ static int rock_continue(struct rock_state *rs) { int ret = 1; int blocksize = 1 << rs->inode->i_blkbits; const int min_de_size = offsetof(struct rock_ridge, u); kfree(rs->buffer); rs->buffer = NULL; if ((unsigned)rs->cont_offset > blocksize - min_de_size || (unsigned)rs->cont_size > blocksize || (unsigned)(rs->cont_offset + rs->cont_size) > blocksize) { printk(KERN_NOTICE "rock: corrupted directory entry. " "extent=%d, offset=%d, size=%d\n", rs->cont_extent, rs->cont_offset, rs->cont_size); ret = -EIO; goto out; } if (rs->cont_extent) { struct buffer_head *bh; rs->buffer = kmalloc(rs->cont_size, GFP_KERNEL); if (!rs->buffer) { ret = -ENOMEM; goto out; } ret = -EIO; if (++rs->cont_loops >= RR_MAX_CE_ENTRIES) goto out; bh = sb_bread(rs->inode->i_sb, rs->cont_extent); if (bh) { memcpy(rs->buffer, bh->b_data + rs->cont_offset, rs->cont_size); put_bh(bh); rs->chr = rs->buffer; rs->len = rs->cont_size; rs->cont_extent = 0; rs->cont_size = 0; rs->cont_offset = 0; return 0; } printk("Unable to read rock-ridge attributes\n"); } out: kfree(rs->buffer); rs->buffer = NULL; return ret; } /* * We think there's a record of type `sig' at rs->chr. Parse the signature * and make sure that there's really room for a record of that type. */ static int rock_check_overflow(struct rock_state *rs, int sig) { int len; switch (sig) { case SIG('S', 'P'): len = sizeof(struct SU_SP_s); break; case SIG('C', 'E'): len = sizeof(struct SU_CE_s); break; case SIG('E', 'R'): len = sizeof(struct SU_ER_s); break; case SIG('R', 'R'): len = sizeof(struct RR_RR_s); break; case SIG('P', 'X'): len = sizeof(struct RR_PX_s); break; case SIG('P', 'N'): len = sizeof(struct RR_PN_s); break; case SIG('S', 'L'): len = sizeof(struct RR_SL_s); break; case SIG('N', 'M'): len = sizeof(struct RR_NM_s); break; case SIG('C', 'L'): len = sizeof(struct RR_CL_s); break; case SIG('P', 'L'): len = sizeof(struct RR_PL_s); break; case SIG('T', 'F'): len = sizeof(struct RR_TF_s); break; case SIG('Z', 'F'): len = sizeof(struct RR_ZF_s); break; default: len = 0; break; } len += offsetof(struct rock_ridge, u); if (len > rs->len) { printk(KERN_NOTICE "rock: directory entry would overflow " "storage\n"); printk(KERN_NOTICE "rock: sig=0x%02x, size=%d, remaining=%d\n", sig, len, rs->len); return -EIO; } return 0; } /* * return length of name field; 0: not found, -1: to be ignored */ int get_rock_ridge_filename(struct iso_directory_record *de, char *retname, struct inode *inode) { struct rock_state rs; struct rock_ridge *rr; int sig; int retnamlen = 0; int truncate = 0; int ret = 0; if (!ISOFS_SB(inode->i_sb)->s_rock) return 0; *retname = 0; init_rock_state(&rs, inode); setup_rock_ridge(de, inode, &rs); repeat: while (rs.len > 2) { /* There may be one byte for padding somewhere */ rr = (struct rock_ridge *)rs.chr; /* * Ignore rock ridge info if rr->len is out of range, but * don't return -EIO because that would make the file * invisible. */ if (rr->len < 3) goto out; /* Something got screwed up here */ sig = isonum_721(rs.chr); if (rock_check_overflow(&rs, sig)) goto eio; rs.chr += rr->len; rs.len -= rr->len; /* * As above, just ignore the rock ridge info if rr->len * is bogus. */ if (rs.len < 0) goto out; /* Something got screwed up here */ switch (sig) { case SIG('R', 'R'): if ((rr->u.RR.flags[0] & RR_NM) == 0) goto out; break; case SIG('S', 'P'): if (check_sp(rr, inode)) goto out; break; case SIG('C', 'E'): rs.cont_extent = isonum_733(rr->u.CE.extent); rs.cont_offset = isonum_733(rr->u.CE.offset); rs.cont_size = isonum_733(rr->u.CE.size); break; case SIG('N', 'M'): if (truncate) break; if (rr->len < 5) break; /* * If the flags are 2 or 4, this indicates '.' or '..'. * We don't want to do anything with this, because it * screws up the code that calls us. We don't really * care anyways, since we can just use the non-RR * name. */ if (rr->u.NM.flags & 6) break; if (rr->u.NM.flags & ~1) { printk("Unsupported NM flag settings (%d)\n", rr->u.NM.flags); break; } if ((strlen(retname) + rr->len - 5) >= 254) { truncate = 1; break; } strncat(retname, rr->u.NM.name, rr->len - 5); retnamlen += rr->len - 5; break; case SIG('R', 'E'): kfree(rs.buffer); return -1; default: break; } } ret = rock_continue(&rs); if (ret == 0) goto repeat; if (ret == 1) return retnamlen; /* If 0, this file did not have a NM field */ out: kfree(rs.buffer); return ret; eio: ret = -EIO; goto out; } #define RR_REGARD_XA 1 #define RR_RELOC_DE 2 static int parse_rock_ridge_inode_internal(struct iso_directory_record *de, struct inode *inode, int flags) { int symlink_len = 0; int cnt, sig; unsigned int reloc_block; struct inode *reloc; struct rock_ridge *rr; int rootflag; struct rock_state rs; int ret = 0; if (!ISOFS_SB(inode->i_sb)->s_rock) return 0; init_rock_state(&rs, inode); setup_rock_ridge(de, inode, &rs); if (flags & RR_REGARD_XA) { rs.chr += 14; rs.len -= 14; if (rs.len < 0) rs.len = 0; } repeat: while (rs.len > 2) { /* There may be one byte for padding somewhere */ rr = (struct rock_ridge *)rs.chr; /* * Ignore rock ridge info if rr->len is out of range, but * don't return -EIO because that would make the file * invisible. */ if (rr->len < 3) goto out; /* Something got screwed up here */ sig = isonum_721(rs.chr); if (rock_check_overflow(&rs, sig)) goto eio; rs.chr += rr->len; rs.len -= rr->len; /* * As above, just ignore the rock ridge info if rr->len * is bogus. */ if (rs.len < 0) goto out; /* Something got screwed up here */ switch (sig) { #ifndef CONFIG_ZISOFS /* No flag for SF or ZF */ case SIG('R', 'R'): if ((rr->u.RR.flags[0] & (RR_PX | RR_TF | RR_SL | RR_CL)) == 0) goto out; break; #endif case SIG('S', 'P'): if (check_sp(rr, inode)) goto out; break; case SIG('C', 'E'): rs.cont_extent = isonum_733(rr->u.CE.extent); rs.cont_offset = isonum_733(rr->u.CE.offset); rs.cont_size = isonum_733(rr->u.CE.size); break; case SIG('E', 'R'): ISOFS_SB(inode->i_sb)->s_rock = 1; printk(KERN_DEBUG "ISO 9660 Extensions: "); { int p; for (p = 0; p < rr->u.ER.len_id; p++) printk("%c", rr->u.ER.data[p]); } printk("\n"); break; case SIG('P', 'X'): inode->i_mode = isonum_733(rr->u.PX.mode); set_nlink(inode, isonum_733(rr->u.PX.n_links)); i_uid_write(inode, isonum_733(rr->u.PX.uid)); i_gid_write(inode, isonum_733(rr->u.PX.gid)); break; case SIG('P', 'N'): { int high, low; high = isonum_733(rr->u.PN.dev_high); low = isonum_733(rr->u.PN.dev_low); /* * The Rock Ridge standard specifies that if * sizeof(dev_t) <= 4, then the high field is * unused, and the device number is completely * stored in the low field. Some writers may * ignore this subtlety, * and as a result we test to see if the entire * device number is * stored in the low field, and use that. */ if ((low & ~0xff) && high == 0) { inode->i_rdev = MKDEV(low >> 8, low & 0xff); } else { inode->i_rdev = MKDEV(high, low); } } break; case SIG('T', 'F'): /* * Some RRIP writers incorrectly place ctime in the * TF_CREATE field. Try to handle this correctly for * either case. */ /* Rock ridge never appears on a High Sierra disk */ cnt = 0; if (rr->u.TF.flags & TF_CREATE) { inode->i_ctime.tv_sec = iso_date(rr->u.TF.times[cnt++].time, 0); inode->i_ctime.tv_nsec = 0; } if (rr->u.TF.flags & TF_MODIFY) { inode->i_mtime.tv_sec = iso_date(rr->u.TF.times[cnt++].time, 0); inode->i_mtime.tv_nsec = 0; } if (rr->u.TF.flags & TF_ACCESS) { inode->i_atime.tv_sec = iso_date(rr->u.TF.times[cnt++].time, 0); inode->i_atime.tv_nsec = 0; } if (rr->u.TF.flags & TF_ATTRIBUTES) { inode->i_ctime.tv_sec = iso_date(rr->u.TF.times[cnt++].time, 0); inode->i_ctime.tv_nsec = 0; } break; case SIG('S', 'L'): { int slen; struct SL_component *slp; struct SL_component *oldslp; slen = rr->len - 5; slp = &rr->u.SL.link; inode->i_size = symlink_len; while (slen > 1) { rootflag = 0; switch (slp->flags & ~1) { case 0: inode->i_size += slp->len; break; case 2: inode->i_size += 1; break; case 4: inode->i_size += 2; break; case 8: rootflag = 1; inode->i_size += 1; break; default: printk("Symlink component flag " "not implemented\n"); } slen -= slp->len + 2; oldslp = slp; slp = (struct SL_component *) (((char *)slp) + slp->len + 2); if (slen < 2) { if (((rr->u.SL. flags & 1) != 0) && ((oldslp-> flags & 1) == 0)) inode->i_size += 1; break; } /* * If this component record isn't * continued, then append a '/'. */ if (!rootflag && (oldslp->flags & 1) == 0) inode->i_size += 1; } } symlink_len = inode->i_size; break; case SIG('R', 'E'): printk(KERN_WARNING "Attempt to read inode for " "relocated directory\n"); goto out; case SIG('C', 'L'): if (flags & RR_RELOC_DE) { printk(KERN_ERR "ISOFS: Recursive directory relocation " "is not supported\n"); goto eio; } reloc_block = isonum_733(rr->u.CL.location); if (reloc_block == ISOFS_I(inode)->i_iget5_block && ISOFS_I(inode)->i_iget5_offset == 0) { printk(KERN_ERR "ISOFS: Directory relocation points to " "itself\n"); goto eio; } ISOFS_I(inode)->i_first_extent = reloc_block; reloc = isofs_iget_reloc(inode->i_sb, reloc_block, 0); if (IS_ERR(reloc)) { ret = PTR_ERR(reloc); goto out; } inode->i_mode = reloc->i_mode; set_nlink(inode, reloc->i_nlink); inode->i_uid = reloc->i_uid; inode->i_gid = reloc->i_gid; inode->i_rdev = reloc->i_rdev; inode->i_size = reloc->i_size; inode->i_blocks = reloc->i_blocks; inode->i_atime = reloc->i_atime; inode->i_ctime = reloc->i_ctime; inode->i_mtime = reloc->i_mtime; iput(reloc); break; #ifdef CONFIG_ZISOFS case SIG('Z', 'F'): { int algo; if (ISOFS_SB(inode->i_sb)->s_nocompress) break; algo = isonum_721(rr->u.ZF.algorithm); if (algo == SIG('p', 'z')) { int block_shift = isonum_711(&rr->u.ZF.parms[1]); if (block_shift > 17) { printk(KERN_WARNING "isofs: " "Can't handle ZF block " "size of 2^%d\n", block_shift); } else { /* * Note: we don't change * i_blocks here */ ISOFS_I(inode)->i_file_format = isofs_file_compressed; /* * Parameters to compression * algorithm (header size, * block size) */ ISOFS_I(inode)->i_format_parm[0] = isonum_711(&rr->u.ZF.parms[0]); ISOFS_I(inode)->i_format_parm[1] = isonum_711(&rr->u.ZF.parms[1]); inode->i_size = isonum_733(rr->u.ZF. real_size); } } else { printk(KERN_WARNING "isofs: Unknown ZF compression " "algorithm: %c%c\n", rr->u.ZF.algorithm[0], rr->u.ZF.algorithm[1]); } break; } #endif default: break; } } ret = rock_continue(&rs); if (ret == 0) goto repeat; if (ret == 1) ret = 0; out: kfree(rs.buffer); return ret; eio: ret = -EIO; goto out; } static char *get_symlink_chunk(char *rpnt, struct rock_ridge *rr, char *plimit) { int slen; int rootflag; struct SL_component *oldslp; struct SL_component *slp; slen = rr->len - 5; slp = &rr->u.SL.link; while (slen > 1) { rootflag = 0; switch (slp->flags & ~1) { case 0: if (slp->len > plimit - rpnt) return NULL; memcpy(rpnt, slp->text, slp->len); rpnt += slp->len; break; case 2: if (rpnt >= plimit) return NULL; *rpnt++ = '.'; break; case 4: if (2 > plimit - rpnt) return NULL; *rpnt++ = '.'; *rpnt++ = '.'; break; case 8: if (rpnt >= plimit) return NULL; rootflag = 1; *rpnt++ = '/'; break; default: printk("Symlink component flag not implemented (%d)\n", slp->flags); } slen -= slp->len + 2; oldslp = slp; slp = (struct SL_component *)((char *)slp + slp->len + 2); if (slen < 2) { /* * If there is another SL record, and this component * record isn't continued, then add a slash. */ if ((!rootflag) && (rr->u.SL.flags & 1) && !(oldslp->flags & 1)) { if (rpnt >= plimit) return NULL; *rpnt++ = '/'; } break; } /* * If this component record isn't continued, then append a '/'. */ if (!rootflag && !(oldslp->flags & 1)) { if (rpnt >= plimit) return NULL; *rpnt++ = '/'; } } return rpnt; } int parse_rock_ridge_inode(struct iso_directory_record *de, struct inode *inode, int relocated) { int flags = relocated ? RR_RELOC_DE : 0; int result = parse_rock_ridge_inode_internal(de, inode, flags); /* * if rockridge flag was reset and we didn't look for attributes * behind eventual XA attributes, have a look there */ if ((ISOFS_SB(inode->i_sb)->s_rock_offset == -1) && (ISOFS_SB(inode->i_sb)->s_rock == 2)) { result = parse_rock_ridge_inode_internal(de, inode, flags | RR_REGARD_XA); } return result; } /* * readpage() for symlinks: reads symlink contents into the page and either * makes it uptodate and returns 0 or returns error (-EIO) */ static int rock_ridge_symlink_readpage(struct file *file, struct page *page) { struct inode *inode = page->mapping->host; struct iso_inode_info *ei = ISOFS_I(inode); struct isofs_sb_info *sbi = ISOFS_SB(inode->i_sb); char *link = kmap(page); unsigned long bufsize = ISOFS_BUFFER_SIZE(inode); struct buffer_head *bh; char *rpnt = link; unsigned char *pnt; struct iso_directory_record *raw_de; unsigned long block, offset; int sig; struct rock_ridge *rr; struct rock_state rs; int ret; if (!sbi->s_rock) goto error; init_rock_state(&rs, inode); block = ei->i_iget5_block; bh = sb_bread(inode->i_sb, block); if (!bh) goto out_noread; offset = ei->i_iget5_offset; pnt = (unsigned char *)bh->b_data + offset; raw_de = (struct iso_directory_record *)pnt; /* * If we go past the end of the buffer, there is some sort of error. */ if (offset + *pnt > bufsize) goto out_bad_span; /* * Now test for possible Rock Ridge extensions which will override * some of these numbers in the inode structure. */ setup_rock_ridge(raw_de, inode, &rs); repeat: while (rs.len > 2) { /* There may be one byte for padding somewhere */ rr = (struct rock_ridge *)rs.chr; if (rr->len < 3) goto out; /* Something got screwed up here */ sig = isonum_721(rs.chr); if (rock_check_overflow(&rs, sig)) goto out; rs.chr += rr->len; rs.len -= rr->len; if (rs.len < 0) goto out; /* corrupted isofs */ switch (sig) { case SIG('R', 'R'): if ((rr->u.RR.flags[0] & RR_SL) == 0) goto out; break; case SIG('S', 'P'): if (check_sp(rr, inode)) goto out; break; case SIG('S', 'L'): rpnt = get_symlink_chunk(rpnt, rr, link + (PAGE_SIZE - 1)); if (rpnt == NULL) goto out; break; case SIG('C', 'E'): /* This tells is if there is a continuation record */ rs.cont_extent = isonum_733(rr->u.CE.extent); rs.cont_offset = isonum_733(rr->u.CE.offset); rs.cont_size = isonum_733(rr->u.CE.size); default: break; } } ret = rock_continue(&rs); if (ret == 0) goto repeat; if (ret < 0) goto fail; if (rpnt == link) goto fail; brelse(bh); *rpnt = '\0'; SetPageUptodate(page); kunmap(page); unlock_page(page); return 0; /* error exit from macro */ out: kfree(rs.buffer); goto fail; out_noread: printk("unable to read i-node block"); goto fail; out_bad_span: printk("symlink spans iso9660 blocks\n"); fail: brelse(bh); error: SetPageError(page); kunmap(page); unlock_page(page); return -EIO; } const struct address_space_operations isofs_symlink_aops = { .readpage = rock_ridge_symlink_readpage };
./CrossVul/dataset_final_sorted/CWE-20/c/bad_2391_0
crossvul-cpp_data_good_1563_1
/* Copyright (C) ABRT Team Copyright (C) RedHat inc. 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <glib.h> #include <sys/time.h> #include "problem_api.h" /* * Goes through all problems and for problems accessible by caller_uid * calls callback. If callback returns non-0, returns that value. */ int for_each_problem_in_dir(const char *path, uid_t caller_uid, int (*callback)(struct dump_dir *dd, void *arg), void *arg) { DIR *dp = opendir(path); if (!dp) { /* We don't want to yell if, say, $XDG_CACHE_DIR/abrt/spool doesn't exist */ //perror_msg("Can't open directory '%s'", path); return 0; } int brk = 0; struct dirent *dent; while ((dent = readdir(dp)) != NULL) { if (dot_or_dotdot(dent->d_name)) continue; /* skip "." and ".." */ char *full_name = concat_path_file(path, dent->d_name); int dir_fd = dd_openfd(full_name); if (dir_fd < 0) { VERB2 perror_msg("can't open problem directory '%s'", full_name); continue; } if (caller_uid == -1 || fdump_dir_accessible_by_uid(dir_fd, caller_uid)) { /* Silently ignore *any* errors, not only EACCES. * We saw "lock file is locked by process PID" error * when we raced with wizard. */ int sv_logmode = logmode; logmode = 0; struct dump_dir *dd = dd_fdopendir(dir_fd, full_name, DD_OPEN_READONLY | DD_FAIL_QUIETLY_EACCES | DD_DONT_WAIT_FOR_LOCK); logmode = sv_logmode; if (dd) { brk = callback ? callback(dd, arg) : 0; dd_close(dd); } } else close(dir_fd); free(full_name); if (brk) break; } closedir(dp); return brk; } /* get_problem_dirs_for_uid and its helpers */ static int add_dirname_to_GList(struct dump_dir *dd, void *arg) { GList **list = arg; *list = g_list_prepend(*list, xstrdup(dd->dd_dirname)); return 0; } GList *get_problem_dirs_for_uid(uid_t uid, const char *dump_location) { GList *list = NULL; for_each_problem_in_dir(dump_location, uid, add_dirname_to_GList, &list); /* * Why reverse? * Because N*prepend+reverse is faster than N*append */ return g_list_reverse(list); } /* get_problem_dirs_not_accessible_by_uid and its helpers */ struct add_dirname_to_GList_if_not_accessible_args { uid_t uid; GList *list; }; static int add_dirname_to_GList_if_not_accessible(struct dump_dir *dd, void *args) { struct add_dirname_to_GList_if_not_accessible_args *param = (struct add_dirname_to_GList_if_not_accessible_args *)args; /* Append if not accessible */ if (!dump_dir_accessible_by_uid(dd->dd_dirname, param->uid)) param->list = g_list_prepend(param->list, xstrdup(dd->dd_dirname)); return 0; } GList *get_problem_dirs_not_accessible_by_uid(uid_t uid, const char *dump_location) { struct add_dirname_to_GList_if_not_accessible_args args = { .uid = uid, .list = NULL, }; for_each_problem_in_dir(dump_location, /*disable default uid check*/-1, add_dirname_to_GList_if_not_accessible, &args); return g_list_reverse(args.list); } /* get_problem_storages */ GList *get_problem_storages(void) { GList *pths = NULL; load_abrt_conf(); pths = g_list_append(pths, xstrdup(g_settings_dump_location)); //not needed, we don't steal directories anymore pths = g_list_append(pths, concat_path_file(g_get_user_cache_dir(), "abrt/spool")); free_abrt_conf_data(); return pths; } int problem_dump_dir_is_complete(struct dump_dir *dd) { return dd_exist(dd, FILENAME_COUNT); }
./CrossVul/dataset_final_sorted/CWE-20/c/good_1563_1
crossvul-cpp_data_good_5849_0
/* * IKEv2 parent SA creation routines * Copyright (C) 2007-2008 Michael Richardson <mcr@xelerance.com> * Copyright (C) 2008-2011 Paul Wouters <paul@xelerance.com> * Copyright (C) 2008 Antony Antony <antony@xelerance.com> * Copyright (C) 2008-2009 David McCullough <david_mccullough@securecomputing.com> * Copyright (C) 2010,2012 Avesh Agarwal <avagarwa@redhat.com> * Copyright (C) 2010 Tuomo Soini <tis@foobar.fi * Copyright (C) 2012 Paul Wouters <pwouters@redhat.com> * Copyright (C) 2012 Antony Antony <antony@phenome.org> * * 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. See <http://www.fsf.org/copyleft/gpl.txt>. * * 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. * */ #include <stdio.h> #include <string.h> #include <stddef.h> #include <stdlib.h> #include <unistd.h> #include <gmp.h> #include <libreswan.h> #include <libreswan/ipsec_policy.h> #include "sysdep.h" #include "constants.h" #include "defs.h" #include "state.h" #include "id.h" #include "connections.h" #include "crypto.h" /* requires sha1.h and md5.h */ #include "x509.h" #include "x509more.h" #include "ike_alg.h" #include "kernel_alg.h" #include "plutoalg.h" #include "pluto_crypt.h" #include "packet.h" #include "demux.h" #include "ikev2.h" #include "log.h" #include "spdb.h" /* for out_sa */ #include "ipsec_doi.h" #include "vendor.h" #include "timer.h" #include "ike_continuations.h" #include "cookie.h" #include "rnd.h" #include "pending.h" #include "kernel.h" #define SEND_NOTIFICATION_AA(t, d) \ if (st) \ send_v2_notification_from_state(st, st->st_state, t, d); \ else \ send_v2_notification_from_md(md, t, d); #define SEND_NOTIFICATION(t) \ if (st) \ send_v2_notification_from_state(st, st->st_state, t, NULL); \ else \ send_v2_notification_from_md(md, t, NULL); static void ikev2_parent_outI1_continue(struct pluto_crypto_req_cont *pcrc, struct pluto_crypto_req *r, err_t ugh); static stf_status ikev2_parent_outI1_tail(struct pluto_crypto_req_cont *pcrc, struct pluto_crypto_req *r); static bool ikev2_get_dcookie(u_char *dcookie, chunk_t st_ni, ip_address *addr, u_int8_t *spiI); static stf_status ikev2_parent_outI1_common(struct msg_digest *md, struct state *st); static int build_ike_version(); /* * *************************************************************** ***** PARENT_OUTI1 ***** *************************************************************** * * * Initiate an Oakley Main Mode exchange. * HDR, SAi1, KEi, Ni --> * * Note: this is not called from demux.c, but from ipsecdoi_initiate(). * */ stf_status ikev2parent_outI1(int whack_sock, struct connection *c, struct state *predecessor, lset_t policy, unsigned long try, enum crypto_importance importance #ifdef HAVE_LABELED_IPSEC , struct xfrm_user_sec_ctx_ike * uctx #endif ) { struct state *st = new_state(); struct db_sa *sadb; int groupnum; int policy_index = POLICY_ISAKMP(policy, c->spd.this.xauth_server, c->spd.this.xauth_client); /* set up new state */ get_cookie(TRUE, st->st_icookie, COOKIE_SIZE, &c->spd.that.host_addr); initialize_new_state(st, c, policy, try, whack_sock, importance); st->st_ikev2 = TRUE; change_state(st, STATE_PARENT_I1); st->st_msgid_lastack = INVALID_MSGID; st->st_msgid_nextuse = 0; st->st_try = try; if (HAS_IPSEC_POLICY(policy)) { #ifdef HAVE_LABELED_IPSEC st->sec_ctx = NULL; if ( uctx != NULL) libreswan_log( "Labeled ipsec is not supported with ikev2 yet"); #endif add_pending(dup_any( whack_sock), st, c, policy, 1, predecessor == NULL ? SOS_NOBODY : predecessor->st_serialno #ifdef HAVE_LABELED_IPSEC , st->sec_ctx #endif ); } if (predecessor == NULL) libreswan_log("initiating v2 parent SA"); else libreswan_log("initiating v2 parent SA to replace #%lu", predecessor->st_serialno); if (predecessor != NULL) { update_pending(predecessor, st); whack_log(RC_NEW_STATE + STATE_PARENT_I1, "%s: initiate, replacing #%lu", enum_name(&state_names, st->st_state), predecessor->st_serialno); } else { whack_log(RC_NEW_STATE + STATE_PARENT_I1, "%s: initiate", enum_name(&state_names, st->st_state)); } /* * now, we need to initialize st->st_oakley, specifically, the group * number needs to be initialized. */ groupnum = 0; st->st_sadb = &oakley_sadb[policy_index]; sadb = oakley_alg_makedb(st->st_connection->alg_info_ike, st->st_sadb, 0); if (sadb != NULL) st->st_sadb = sadb; sadb = st->st_sadb = sa_v2_convert(st->st_sadb); { unsigned int pc_cnt; /* look at all the proposals */ if (st->st_sadb->prop_disj != NULL) { for (pc_cnt = 0; pc_cnt < st->st_sadb->prop_disj_cnt && groupnum == 0; pc_cnt++) { struct db_v2_prop *vp = &st->st_sadb->prop_disj[pc_cnt]; unsigned int pr_cnt; /* look at all the proposals */ if (vp->props != NULL) { for (pr_cnt = 0; pr_cnt < vp->prop_cnt && groupnum == 0; pr_cnt++) { unsigned int ts_cnt; struct db_v2_prop_conj *vpc = &vp->props[pr_cnt]; for (ts_cnt = 0; ts_cnt < vpc->trans_cnt && groupnum == 0; ts_cnt++) { struct db_v2_trans *tr = &vpc-> trans[ ts_cnt ]; if (tr != NULL && tr->transform_type == IKEv2_TRANS_TYPE_DH) { groupnum = tr-> transid; } } } } } } } if (groupnum == 0) groupnum = OAKLEY_GROUP_MODP2048; st->st_oakley.group = lookup_group(groupnum); st->st_oakley.groupnum = groupnum; /* now. we need to go calculate the nonce, and the KE */ { struct ke_continuation *ke = alloc_thing( struct ke_continuation, "ikev2_outI1 KE"); stf_status e; ke->md = alloc_md(); ke->md->from_state = STATE_IKEv2_BASE; ke->md->svm = ikev2_parent_firststate(); ke->md->st = st; set_suspended(st, ke->md); if (!st->st_sec_in_use) { pcrc_init(&ke->ke_pcrc); ke->ke_pcrc.pcrc_func = ikev2_parent_outI1_continue; e = build_ke(&ke->ke_pcrc, st, st->st_oakley.group, importance); if ( (e != STF_SUSPEND && e != STF_INLINE) || (e == STF_TOOMUCHCRYPTO)) { loglog(RC_CRYPTOFAILED, "system too busy - Enabling dcookies [TODO]"); delete_state(st); } } else { e = ikev2_parent_outI1_tail( (struct pluto_crypto_req_cont *)ke, NULL); } reset_globals(); return e; } } static void ikev2_parent_outI1_continue(struct pluto_crypto_req_cont *pcrc, struct pluto_crypto_req *r, err_t ugh) { struct ke_continuation *ke = (struct ke_continuation *)pcrc; struct msg_digest *md = ke->md; struct state *const st = md->st; stf_status e; DBG(DBG_CONTROLMORE, DBG_log("ikev2 parent outI1: calculated ke+nonce, sending I1")); if (st == NULL) { loglog(RC_LOG_SERIOUS, "%s: Request was disconnected from state", __FUNCTION__); if (ke->md) release_md(ke->md); return; } /* XXX should check out ugh */ passert(ugh == NULL); passert(cur_state == NULL); passert(st != NULL); passert(st->st_suspended_md == ke->md); set_suspended(st, NULL); /* no longer connected or suspended */ set_cur_state(st); st->st_calculating = FALSE; e = ikev2_parent_outI1_tail(pcrc, r); if (ke->md != NULL) { complete_v2_state_transition(&ke->md, e); if (ke->md) release_md(ke->md); } reset_cur_state(); reset_globals(); } /* * unpack the calculate KE value, store it in state. * used by IKEv2: parent, child (PFS) */ static int unpack_v2KE(struct state *st, struct pluto_crypto_req *r, chunk_t *g) { struct pcr_kenonce *kn = &r->pcr_d.kn; unpack_KE(st, r, g); return kn->oakley_group; } /* * package up the calculate KE value, and emit it as a KE payload. * used by IKEv2: parent, child (PFS) */ static bool justship_v2KE(struct state *st UNUSED, chunk_t *g, unsigned int oakley_group, pb_stream *outs, u_int8_t np) { struct ikev2_ke v2ke; pb_stream kepbs; memset(&v2ke, 0, sizeof(v2ke)); v2ke.isak_np = np; v2ke.isak_group = oakley_group; if (!out_struct(&v2ke, &ikev2_ke_desc, outs, &kepbs)) return FALSE; if (!out_chunk(*g, &kepbs, "ikev2 g^x")) return FALSE; close_output_pbs(&kepbs); return TRUE; } static bool ship_v2KE(struct state *st, struct pluto_crypto_req *r, chunk_t *g, pb_stream *outs, u_int8_t np) { int oakley_group = unpack_v2KE(st, r, g); return justship_v2KE(st, g, oakley_group, outs, np); } static stf_status ikev2_parent_outI1_tail(struct pluto_crypto_req_cont *pcrc, struct pluto_crypto_req *r) { struct ke_continuation *ke = (struct ke_continuation *)pcrc; struct msg_digest *md = ke->md; struct state *const st = md->st; unpack_v2KE(st, r, &st->st_gi); unpack_nonce(&st->st_ni, r); return ikev2_parent_outI1_common(md, st); } static stf_status ikev2_parent_outI1_common(struct msg_digest *md, struct state *st) { struct connection *c = st->st_connection; int numvidtosend = 0; /* set up reply */ init_pbs(&reply_stream, reply_buffer, sizeof(reply_buffer), "reply packet"); /* HDR out */ { struct isakmp_hdr hdr; zero(&hdr); /* default to 0 */ /* Impair function will raise major/minor by 1 for testing */ hdr.isa_version = build_ike_version(); if (st->st_dcookie.ptr) hdr.isa_np = ISAKMP_NEXT_v2N; else hdr.isa_np = ISAKMP_NEXT_v2SA; hdr.isa_xchg = ISAKMP_v2_SA_INIT; hdr.isa_flags = ISAKMP_FLAGS_I; memcpy(hdr.isa_icookie, st->st_icookie, COOKIE_SIZE); /* R-cookie, are left zero */ if (!out_struct(&hdr, &isakmp_hdr_desc, &reply_stream, &md->rbody)) { reset_cur_state(); return STF_INTERNAL_ERROR; } } /* send an anti DOS cookie, 4306 2.6, if we have received one from the * responder */ if (st->st_dcookie.ptr) { chunk_t child_spi; memset(&child_spi, 0, sizeof(child_spi)); ship_v2N(ISAKMP_NEXT_v2SA, DBGP( IMPAIR_SEND_BOGUS_ISAKMP_FLAG) ? (ISAKMP_PAYLOAD_NONCRITICAL | ISAKMP_PAYLOAD_LIBRESWAN_BOGUS) : ISAKMP_PAYLOAD_NONCRITICAL, PROTO_ISAKMP, &child_spi, v2N_COOKIE, &st->st_dcookie, &md->rbody); } /* SA out */ { u_char *sa_start = md->rbody.cur; if (st->st_sadb->prop_disj_cnt == 0 || st->st_sadb->prop_disj) st->st_sadb = sa_v2_convert(st->st_sadb); if (!ikev2_out_sa(&md->rbody, PROTO_ISAKMP, st->st_sadb, st, TRUE, /* parentSA */ ISAKMP_NEXT_v2KE)) { libreswan_log("outsa fail"); reset_cur_state(); return STF_INTERNAL_ERROR; } /* save initiator SA for later HASH */ if (st->st_p1isa.ptr == NULL) { /* no leak! (MUST be first time) */ clonetochunk(st->st_p1isa, sa_start, md->rbody.cur - sa_start, "sa in main_outI1"); } } /* send KE */ if (!justship_v2KE(st, &st->st_gi, st->st_oakley.groupnum, &md->rbody, ISAKMP_NEXT_v2Ni)) return STF_INTERNAL_ERROR; /* * Check which Vendor ID's we need to send - there will be more soon * In IKEv2, DPD and NAT-T are no longer vendorid's */ if (c->send_vendorid) { numvidtosend++; /* if we need to send Libreswan VID */ } /* send NONCE */ { int np = numvidtosend > 0 ? ISAKMP_NEXT_v2V : ISAKMP_NEXT_v2NONE; struct ikev2_generic in; pb_stream pb; memset(&in, 0, sizeof(in)); in.isag_np = np; in.isag_critical = ISAKMP_PAYLOAD_NONCRITICAL; if (DBGP(IMPAIR_SEND_BOGUS_ISAKMP_FLAG)) { libreswan_log( " setting bogus ISAKMP_PAYLOAD_LIBRESWAN_BOGUS flag in ISAKMP payload"); in.isag_critical |= ISAKMP_PAYLOAD_LIBRESWAN_BOGUS; } if (!out_struct(&in, &ikev2_nonce_desc, &md->rbody, &pb) || !out_raw(st->st_ni.ptr, st->st_ni.len, &pb, "IKEv2 nonce")) return STF_INTERNAL_ERROR; close_output_pbs(&pb); } /* Send Vendor VID if needed */ if (c->send_vendorid) { const char *myvid = ipsec_version_vendorid(); int np = --numvidtosend > 0 ? ISAKMP_NEXT_v2V : ISAKMP_NEXT_v2NONE; if (!out_generic_raw(np, &isakmp_vendor_id_desc, &md->rbody, myvid, strlen(myvid), "Vendor ID")) return STF_INTERNAL_ERROR; /* ensure our VID chain was valid */ passert(numvidtosend == 0); } close_message(&md->rbody, st); close_output_pbs(&reply_stream); freeanychunk(st->st_tpacket); clonetochunk(st->st_tpacket, reply_stream.start, pbs_offset(&reply_stream), "reply packet for ikev2_parent_outI1_tail"); /* save packet for later signing */ freeanychunk(st->st_firstpacket_me); clonetochunk(st->st_firstpacket_me, reply_stream.start, pbs_offset(&reply_stream), "saved first packet"); /* Transmit */ send_ike_msg(st, __FUNCTION__); delete_event(st); event_schedule(EVENT_v2_RETRANSMIT, EVENT_RETRANSMIT_DELAY_0, st); reset_cur_state(); return STF_OK; } /* * *************************************************************** * PARENT_INI1 ***** *************************************************************** * - * * */ static void ikev2_parent_inI1outR1_continue(struct pluto_crypto_req_cont *pcrc, struct pluto_crypto_req *r, err_t ugh); static stf_status ikev2_parent_inI1outR1_tail( struct pluto_crypto_req_cont *pcrc, struct pluto_crypto_req *r); stf_status ikev2parent_inI1outR1(struct msg_digest *md) { struct state *st = md->st; lset_t policy = POLICY_IKEV2_ALLOW; struct connection *c = find_host_connection(&md->iface->ip_addr, md->iface->port, &md->sender, md->sender_port, POLICY_IKEV2_ALLOW); /* retrieve st->st_gi */ #if 0 if (c == NULL) { /* * make up a policy from the thing that was proposed, and see * if we can find a connection with that policy. */ pb_stream pre_sa_pbs = sa_pd->pbs; policy = preparse_isakmp_sa_body(&pre_sa_pbs); c = find_host_connection(&md->iface->ip_addr, pluto_port, (ip_address*)NULL, md->sender_port, policy); } #endif if (c == NULL) { /* See if a wildcarded connection can be found. * We cannot pick the right connection, so we're making a guess. * All Road Warrior connections are fair game: * we pick the first we come across (if any). * If we don't find any, we pick the first opportunistic * with the smallest subnet that includes the peer. * There is, of course, no necessary relationship between * an Initiator's address and that of its client, * but Food Groups kind of assumes one. */ { struct connection *d; d = find_host_connection(&md->iface->ip_addr, pluto_port, (ip_address*)NULL, md->sender_port, policy); for (; d != NULL; d = d->hp_next) { if (d->kind == CK_GROUP) { /* ignore */ } else { if (d->kind == CK_TEMPLATE && !(d->policy & POLICY_OPPO)) { /* must be Road Warrior: we have a winner */ c = d; break; } /* Opportunistic or Shunt: pick tightest match */ if (addrinsubnet(&md->sender, &d->spd.that.client) && (c == NULL || !subnetinsubnet(&c->spd.that. client, &d->spd.that. client))) c = d; } } } if (c == NULL) { loglog(RC_LOG_SERIOUS, "initial parent SA message received on %s:%u" " but no connection has been authorized%s%s", ip_str( &md->iface->ip_addr), ntohs(portof(&md->iface->ip_addr)), (policy != LEMPTY) ? " with policy=" : "", (policy != LEMPTY) ? bitnamesof(sa_policy_bit_names, policy) : ""); return STF_FAIL + v2N_NO_PROPOSAL_CHOSEN; } if (c->kind != CK_TEMPLATE) { loglog(RC_LOG_SERIOUS, "initial parent SA message received on %s:%u" " but \"%s\" forbids connection", ip_str( &md->iface->ip_addr), pluto_port, c->name); return STF_FAIL + v2N_NO_PROPOSAL_CHOSEN; } c = rw_instantiate(c, &md->sender, NULL, NULL); } else { /* we found a non-wildcard conn. double check if it needs instantiation anyway (eg vnet=) */ /* vnet=/vhost= should have set CK_TEMPLATE on connection loading */ if ((c->kind == CK_TEMPLATE) && c->spd.that.virt) { DBG(DBG_CONTROL, DBG_log( "local endpoint has virt (vnet/vhost) set without wildcards - needs instantiation")); c = rw_instantiate(c, &md->sender, NULL, NULL); } else if ((c->kind == CK_TEMPLATE) && (c->policy & POLICY_IKEV2_ALLOW_NARROWING)) { DBG(DBG_CONTROL, DBG_log( "local endpoint has narrowing=yes - needs instantiation")); c = rw_instantiate(c, &md->sender, NULL, NULL); } } DBG_log("found connection: %s\n", c ? c->name : "<none>"); if (!st) { st = new_state(); /* set up new state */ memcpy(st->st_icookie, md->hdr.isa_icookie, COOKIE_SIZE); /* initialize_new_state expects valid icookie/rcookie values, so create it now */ get_cookie(FALSE, st->st_rcookie, COOKIE_SIZE, &md->sender); initialize_new_state(st, c, policy, 0, NULL_FD, pcim_stranger_crypto); st->st_ikev2 = TRUE; change_state(st, STATE_PARENT_R1); st->st_msgid_lastack = INVALID_MSGID; st->st_msgid_nextuse = 0; md->st = st; md->from_state = STATE_IKEv2_BASE; } /* check,as a responder, are we under dos attack or not * if yes go to 6 message exchange mode. it is a config option for now. * TBD set force_busy dynamically * Paul: Can we check for STF_TOOMUCHCRYPTO ? */ if (force_busy == TRUE) { u_char dcookie[SHA1_DIGEST_SIZE]; chunk_t dc; ikev2_get_dcookie( dcookie, st->st_ni, &md->sender, st->st_icookie); dc.ptr = dcookie; dc.len = SHA1_DIGEST_SIZE; /* check if I1 packet contian KE and a v2N payload with type COOKIE */ if ( md->chain[ISAKMP_NEXT_v2KE] && md->chain[ISAKMP_NEXT_v2N] && (md->chain[ISAKMP_NEXT_v2N]->payload.v2n.isan_type == v2N_COOKIE)) { u_int8_t spisize; const pb_stream *dc_pbs; chunk_t blob; DBG(DBG_CONTROLMORE, DBG_log("received a DOS cookie in I1 verify it")); /* we received dcookie we send earlier verify it */ spisize = md->chain[ISAKMP_NEXT_v2N]->payload.v2n. isan_spisize; dc_pbs = &md->chain[ISAKMP_NEXT_v2N]->pbs; blob.ptr = dc_pbs->cur + spisize; blob.len = pbs_left(dc_pbs) - spisize; DBG(DBG_CONTROLMORE, DBG_dump_chunk("dcookie received in I1 Packet", blob); DBG_dump("dcookie computed", dcookie, SHA1_DIGEST_SIZE)); if (memcmp(blob.ptr, dcookie, SHA1_DIGEST_SIZE) != 0) { libreswan_log( "mismatch in DOS v2N_COOKIE,send a new one"); SEND_NOTIFICATION_AA(v2N_COOKIE, &dc); return STF_FAIL + v2N_INVALID_IKE_SPI; } DBG(DBG_CONTROLMORE, DBG_log("dcookie received match with computed one")); } else { /* we are under DOS attack I1 contains no DOS COOKIE */ DBG(DBG_CONTROLMORE, DBG_log( "busy mode on. receieved I1 without a valid dcookie"); DBG_log("send a dcookie and forget this state")); SEND_NOTIFICATION_AA(v2N_COOKIE, &dc); return STF_FAIL; } } else { DBG(DBG_CONTROLMORE, DBG_log("will not send/process a dcookie")); } /* * We have to agree to the DH group before we actually know who * we are talking to. If we support the group, we use it. * * It is really too hard here to go through all the possible policies * that might permit this group. If we think we are being DOS'ed * then we should demand a cookie. */ { struct ikev2_ke *ke; char fromname[ADDRTOT_BUF]; addrtot(&md->sender, 0, fromname, ADDRTOT_BUF); if (!md->chain[ISAKMP_NEXT_v2KE]) { /* is this a notify? If so, log it */ if(md->chain[ISAKMP_NEXT_v2N]) { libreswan_log("Received Notify(%d): %s", md->chain[ISAKMP_NEXT_v2N]->payload.v2n.isan_type, enum_name(&ikev2_notify_names, md->chain[ISAKMP_NEXT_v2N]->payload.v2n.isan_type)); } libreswan_log( "rejecting I1 from %s:%u, no KE payload present", fromname, md->sender_port); return STF_FAIL + v2N_INVALID_KE_PAYLOAD; } ke = &md->chain[ISAKMP_NEXT_v2KE]->payload.v2ke; st->st_oakley.group = lookup_group(ke->isak_group); if (st->st_oakley.group == NULL) { libreswan_log( "rejecting I1 from %s:%u, invalid DH group=%u", fromname, md->sender_port, ke->isak_group); return STF_FAIL + v2N_INVALID_KE_PAYLOAD; } } /* now. we need to go calculate the nonce, and the KE */ { struct ke_continuation *ke = alloc_thing( struct ke_continuation, "ikev2_inI1outR1 KE"); stf_status e; ke->md = md; set_suspended(st, ke->md); if (!st->st_sec_in_use) { pcrc_init(&ke->ke_pcrc); ke->ke_pcrc.pcrc_func = ikev2_parent_inI1outR1_continue; e = build_ke(&ke->ke_pcrc, st, st->st_oakley.group, pcim_stranger_crypto); if (e != STF_SUSPEND && e != STF_INLINE) { loglog(RC_CRYPTOFAILED, "system too busy"); delete_state(st); } } else { e = ikev2_parent_inI1outR1_tail((struct pluto_crypto_req_cont *)ke, NULL); } reset_globals(); return e; } } static void ikev2_parent_inI1outR1_continue(struct pluto_crypto_req_cont *pcrc, struct pluto_crypto_req *r, err_t ugh) { struct ke_continuation *ke = (struct ke_continuation *)pcrc; struct msg_digest *md = ke->md; struct state *const st = md->st; stf_status e; DBG(DBG_CONTROLMORE, DBG_log("ikev2 parent inI1outR1: calculated ke+nonce, sending R1")); if (st == NULL) { loglog(RC_LOG_SERIOUS, "%s: Request was disconnected from state", __FUNCTION__); if (ke->md) release_md(ke->md); return; } /* XXX should check out ugh */ passert(ugh == NULL); passert(cur_state == NULL); passert(st != NULL); passert(st->st_suspended_md == ke->md); set_suspended(st, NULL); /* no longer connected or suspended */ set_cur_state(st); st->st_calculating = FALSE; e = ikev2_parent_inI1outR1_tail(pcrc, r); if (ke->md != NULL) { complete_v2_state_transition(&ke->md, e); if (ke->md) release_md(ke->md); } reset_globals(); } static stf_status ikev2_parent_inI1outR1_tail( struct pluto_crypto_req_cont *pcrc, struct pluto_crypto_req *r) { struct ke_continuation *ke = (struct ke_continuation *)pcrc; struct msg_digest *md = ke->md; struct payload_digest *const sa_pd = md->chain[ISAKMP_NEXT_v2SA]; struct state *const st = md->st; struct connection *c = st->st_connection; pb_stream *keyex_pbs; int numvidtosend = 0; if (c->send_vendorid) { numvidtosend++; /* we send Libreswan VID */ } /* note that we don't update the state here yet */ /* record first packet for later checking of signature */ clonetochunk(st->st_firstpacket_him, md->message_pbs.start, pbs_offset( &md->message_pbs), "saved first received packet"); /* make sure HDR is at start of a clean buffer */ zero(reply_buffer); init_pbs(&reply_stream, reply_buffer, sizeof(reply_buffer), "reply packet"); /* HDR out */ { struct isakmp_hdr r_hdr = md->hdr; memcpy(r_hdr.isa_rcookie, st->st_rcookie, COOKIE_SIZE); r_hdr.isa_np = ISAKMP_NEXT_v2SA; /* major will be same, but their minor might be higher */ r_hdr.isa_version = build_ike_version(); r_hdr.isa_flags &= ~ISAKMP_FLAGS_I; r_hdr.isa_flags |= ISAKMP_FLAGS_R; /* PAUL shouldn't we set r_hdr.isa_msgid = [htonl](st->st_msgid); here? */ if (!out_struct(&r_hdr, &isakmp_hdr_desc, &reply_stream, &md->rbody)) return STF_INTERNAL_ERROR; } /* start of SA out */ { struct isakmp_sa r_sa = sa_pd->payload.sa; v2_notification_t rn; pb_stream r_sa_pbs; r_sa.isasa_np = ISAKMP_NEXT_v2KE; /* XXX */ if (!out_struct(&r_sa, &ikev2_sa_desc, &md->rbody, &r_sa_pbs)) return STF_INTERNAL_ERROR; /* SA body in and out */ rn = ikev2_parse_parent_sa_body(&sa_pd->pbs, &sa_pd->payload.v2sa, &r_sa_pbs, st, FALSE); if (rn != v2N_NOTHING_WRONG) return STF_FAIL + rn; } { v2_notification_t rn; chunk_t dc; keyex_pbs = &md->chain[ISAKMP_NEXT_v2KE]->pbs; /* KE in */ rn = accept_KE(&st->st_gi, "Gi", st->st_oakley.group, keyex_pbs); if (rn != v2N_NOTHING_WRONG) { u_int16_t group_number = htons( st->st_oakley.group->group); dc.ptr = (unsigned char *)&group_number; dc.len = 2; SEND_NOTIFICATION_AA(v2N_INVALID_KE_PAYLOAD, &dc); delete_state(st); return STF_FAIL + rn; } } /* Ni in */ RETURN_STF_FAILURE(accept_v2_nonce(md, &st->st_ni, "Ni")); /* send KE */ if (!ship_v2KE(st, r, &st->st_gr, &md->rbody, ISAKMP_NEXT_v2Nr)) return STF_INTERNAL_ERROR; /* send NONCE */ unpack_nonce(&st->st_nr, r); { int np = numvidtosend > 0 ? ISAKMP_NEXT_v2V : ISAKMP_NEXT_v2NONE; struct ikev2_generic in; pb_stream pb; memset(&in, 0, sizeof(in)); in.isag_np = np; in.isag_critical = ISAKMP_PAYLOAD_NONCRITICAL; if (DBGP(IMPAIR_SEND_BOGUS_ISAKMP_FLAG)) { libreswan_log( " setting bogus ISAKMP_PAYLOAD_LIBRESWAN_BOGUS flag in ISAKMP payload"); in.isag_critical |= ISAKMP_PAYLOAD_LIBRESWAN_BOGUS; } if (!out_struct(&in, &ikev2_nonce_desc, &md->rbody, &pb) || !out_raw(st->st_nr.ptr, st->st_nr.len, &pb, "IKEv2 nonce")) return STF_INTERNAL_ERROR; close_output_pbs(&pb); } /* Send VendrID if needed VID */ if (c->send_vendorid) { const char *myvid = ipsec_version_vendorid(); int np = --numvidtosend > 0 ? ISAKMP_NEXT_v2V : ISAKMP_NEXT_v2NONE; if (!out_generic_raw(np, &isakmp_vendor_id_desc, &md->rbody, myvid, strlen(myvid), "Vendor ID")) return STF_INTERNAL_ERROR; } close_message(&md->rbody, st); close_output_pbs(&reply_stream); /* keep it for a retransmit if necessary */ freeanychunk(st->st_tpacket); clonetochunk(st->st_tpacket, reply_stream.start, pbs_offset(&reply_stream), "reply packet for ikev2_parent_inI1outR1_tail"); /* save packet for later signing */ freeanychunk(st->st_firstpacket_me); clonetochunk(st->st_firstpacket_me, reply_stream.start, pbs_offset(&reply_stream), "saved first packet"); /* note: retransimission is driven by initiator */ return STF_OK; } /* * *************************************************************** * PARENT_inR1 ***** *************************************************************** * - * * */ static void ikev2_parent_inR1outI2_continue(struct pluto_crypto_req_cont *pcrc, struct pluto_crypto_req *r, err_t ugh); static stf_status ikev2_parent_inR1outI2_tail( struct pluto_crypto_req_cont *pcrc, struct pluto_crypto_req *r); stf_status ikev2parent_inR1outI2(struct msg_digest *md) { struct state *st = md->st; /* struct connection *c = st->st_connection; */ pb_stream *keyex_pbs; /* check if the responder replied with v2N with DOS COOKIE */ if ( md->chain[ISAKMP_NEXT_v2N] && md->chain[ISAKMP_NEXT_v2N]->payload.v2n.isan_type == v2N_COOKIE) { u_int8_t spisize; const pb_stream *dc_pbs; DBG(DBG_CONTROLMORE, DBG_log( "inR1OutI2 received a DOS v2N_COOKIE from the responder"); DBG_log("resend the I1 with a cookie payload")); spisize = md->chain[ISAKMP_NEXT_v2N]->payload.v2n.isan_spisize; dc_pbs = &md->chain[ISAKMP_NEXT_v2N]->pbs; clonetochunk(st->st_dcookie, (dc_pbs->cur + spisize), (pbs_left( dc_pbs) - spisize), "saved received dcookie"); DBG(DBG_CONTROLMORE, DBG_dump_chunk("dcookie received (instead of a R1):", st->st_dcookie); DBG_log("next STATE_PARENT_I1 resend I1 with the dcookie")); md->svm = ikev2_parent_firststate(); change_state(st, STATE_PARENT_I1); st->st_msgid_lastack = INVALID_MSGID; md->msgid_received = INVALID_MSGID; /* AAA hack */ st->st_msgid_nextuse = 0; return ikev2_parent_outI1_common(md, st); } /* * If we did not get a KE payload, we cannot continue. There * should be * a Notify telling us why. We inform the user, but continue to try this * connection via regular retransmit intervals. */ if ( md->chain[ISAKMP_NEXT_v2N] && (md->chain[ISAKMP_NEXT_v2KE] == NULL)) { const char *from_state_name = enum_name(&state_names, st->st_state); const u_int16_t isan_type = md->chain[ISAKMP_NEXT_v2N]->payload.v2n.isan_type; libreswan_log("%s: received %s", from_state_name, enum_name(&ikev2_notify_names, isan_type)); return STF_FAIL + isan_type; } else if ( md->chain[ISAKMP_NEXT_v2N]) { DBG(DBG_CONTROL, DBG_log("received a notify..")); } /* * the responder sent us back KE, Gr, Nr, and it's our time to calculate * the shared key values. */ DBG(DBG_CONTROLMORE, DBG_log( "ikev2 parent inR1: calculating g^{xy} in order to send I2")); /* KE in */ keyex_pbs = &md->chain[ISAKMP_NEXT_v2KE]->pbs; RETURN_STF_FAILURE(accept_KE(&st->st_gr, "Gr", st->st_oakley.group, keyex_pbs)); /* Ni in */ RETURN_STF_FAILURE(accept_v2_nonce(md, &st->st_nr, "Ni")); if (md->chain[ISAKMP_NEXT_v2SA] == NULL) { libreswan_log("No responder SA proposal found"); return v2N_INVALID_SYNTAX; } /* process and confirm the SA selected */ { struct payload_digest *const sa_pd = md->chain[ISAKMP_NEXT_v2SA]; v2_notification_t rn; /* SA body in and out */ rn = ikev2_parse_parent_sa_body(&sa_pd->pbs, &sa_pd->payload.v2sa, NULL, st, FALSE); if (rn != v2N_NOTHING_WRONG) return STF_FAIL + rn; } /* update state */ ikev2_update_counters(md); /* now. we need to go calculate the g^xy */ { struct dh_continuation *dh = alloc_thing( struct dh_continuation, "ikev2_inR1outI2 KE"); stf_status e; dh->md = md; set_suspended(st, dh->md); pcrc_init(&dh->dh_pcrc); dh->dh_pcrc.pcrc_func = ikev2_parent_inR1outI2_continue; e = start_dh_v2(&dh->dh_pcrc, st, st->st_import, INITIATOR, st->st_oakley.groupnum); if (e != STF_SUSPEND && e != STF_INLINE) { loglog(RC_CRYPTOFAILED, "system too busy"); delete_state(st); } reset_globals(); return e; } } static void ikev2_parent_inR1outI2_continue(struct pluto_crypto_req_cont *pcrc, struct pluto_crypto_req *r, err_t ugh) { struct dh_continuation *dh = (struct dh_continuation *)pcrc; struct msg_digest *md = dh->md; struct state *const st = md->st; stf_status e; DBG(DBG_CONTROLMORE, DBG_log("ikev2 parent inR1outI2: calculating g^{xy}, sending I2")); if (st == NULL) { loglog(RC_LOG_SERIOUS, "%s: Request was disconnected from state", __FUNCTION__); if (dh->md) release_md(dh->md); return; } /* XXX should check out ugh */ passert(ugh == NULL); passert(cur_state == NULL); passert(st != NULL); passert(st->st_suspended_md == dh->md); set_suspended(st, NULL); /* no longer connected or suspended */ set_cur_state(st); st->st_calculating = FALSE; e = ikev2_parent_inR1outI2_tail(pcrc, r); if (dh->md != NULL) { complete_v2_state_transition(&dh->md, e); if (dh->md) release_md(dh->md); } reset_globals(); } static void ikev2_padup_pre_encrypt(struct msg_digest *md, pb_stream *e_pbs_cipher) { struct state *st = md->st; struct state *pst = st; if (st->st_clonedfrom != 0) pst = state_with_serialno(st->st_clonedfrom); /* pads things up to message size boundary */ { size_t blocksize = pst->st_oakley.encrypter->enc_blocksize; char *b = alloca(blocksize); unsigned int i; size_t padding = pad_up(pbs_offset(e_pbs_cipher), blocksize); if (padding == 0) padding = blocksize; for (i = 0; i < padding; i++) b[i] = i; out_raw(b, padding, e_pbs_cipher, "padding and length"); } } static unsigned char *ikev2_authloc(struct msg_digest *md, pb_stream *e_pbs) { unsigned char *b12; struct state *st = md->st; struct state *pst = st; if (st->st_clonedfrom != 0) { pst = state_with_serialno(st->st_clonedfrom); if ( pst == NULL) return NULL; } b12 = e_pbs->cur; if (!out_zero(pst->st_oakley.integ_hasher->hash_integ_len, e_pbs, "length of truncated HMAC")) return NULL; return b12; } static stf_status ikev2_encrypt_msg(struct msg_digest *md, enum phase1_role init, unsigned char *authstart, unsigned char *iv, unsigned char *encstart, unsigned char *authloc, pb_stream *e_pbs UNUSED, pb_stream *e_pbs_cipher) { struct state *st = md->st; struct state *pst = st; chunk_t *cipherkey, *authkey; if (st->st_clonedfrom != 0) pst = state_with_serialno(st->st_clonedfrom); if (init == INITIATOR) { cipherkey = &pst->st_skey_ei; authkey = &pst->st_skey_ai; } else { cipherkey = &pst->st_skey_er; authkey = &pst->st_skey_ar; } /* encrypt the block */ { size_t blocksize = pst->st_oakley.encrypter->enc_blocksize; unsigned char *savediv = alloca(blocksize); unsigned int cipherlen = e_pbs_cipher->cur - encstart; DBG(DBG_CRYPT, DBG_dump("data before encryption:", encstart, cipherlen)); memcpy(savediv, iv, blocksize); /* now, encrypt */ (st->st_oakley.encrypter->do_crypt)(encstart, cipherlen, cipherkey->ptr, cipherkey->len, savediv, TRUE); DBG(DBG_CRYPT, DBG_dump("data after encryption:", encstart, cipherlen)); } /* okay, authenticate from beginning of IV */ { struct hmac_ctx ctx; DBG(DBG_PARSING, DBG_log("Inside authloc")); DBG(DBG_CRYPT, DBG_dump("authkey value: ", authkey->ptr, authkey->len)); hmac_init_chunk(&ctx, pst->st_oakley.integ_hasher, *authkey); DBG(DBG_PARSING, DBG_log("Inside authloc after init")); hmac_update(&ctx, authstart, authloc - authstart); DBG(DBG_PARSING, DBG_log("Inside authloc after update")); hmac_final(authloc, &ctx); DBG(DBG_PARSING, DBG_log("Inside authloc after final")); DBG(DBG_PARSING, { DBG_dump("data being hmac:", authstart, authloc - authstart); DBG_dump("out calculated auth:", authloc, pst->st_oakley.integ_hasher-> hash_integ_len); }); } return STF_OK; } static stf_status ikev2_decrypt_msg(struct msg_digest *md, enum phase1_role init) { struct state *st = md->st; unsigned char *encend; pb_stream *e_pbs; unsigned int np; unsigned char *iv; chunk_t *cipherkey, *authkey; unsigned char *authstart; struct state *pst = st; if (st->st_clonedfrom != 0) pst = state_with_serialno(st->st_clonedfrom); if (init == INITIATOR) { cipherkey = &pst->st_skey_er; authkey = &pst->st_skey_ar; } else { cipherkey = &pst->st_skey_ei; authkey = &pst->st_skey_ai; } e_pbs = &md->chain[ISAKMP_NEXT_v2E]->pbs; np = md->chain[ISAKMP_NEXT_v2E]->payload.generic.isag_np; authstart = md->packet_pbs.start; iv = e_pbs->cur; encend = e_pbs->roof - pst->st_oakley.integ_hasher->hash_integ_len; /* start by checking authenticator */ { unsigned char *b12 = alloca( pst->st_oakley.integ_hasher->hash_digest_len); struct hmac_ctx ctx; hmac_init_chunk(&ctx, pst->st_oakley.integ_hasher, *authkey); hmac_update(&ctx, authstart, encend - authstart); hmac_final(b12, &ctx); DBG(DBG_PARSING, { DBG_dump("data being hmac:", authstart, encend - authstart); DBG_dump("R2 calculated auth:", b12, pst->st_oakley.integ_hasher-> hash_integ_len); DBG_dump("R2 provided auth:", encend, pst->st_oakley.integ_hasher-> hash_integ_len); }); /* compare first 96 bits == 12 bytes */ /* It is not always 96 bytes, it depends upon which integ algo is used*/ if (memcmp(b12, encend, pst->st_oakley.integ_hasher->hash_integ_len) != 0) { libreswan_log("R2 failed to match authenticator"); return STF_FAIL; } } DBG(DBG_PARSING, DBG_log("authenticator matched")); /* decrypt */ { size_t blocksize = pst->st_oakley.encrypter->enc_blocksize; unsigned char *encstart = iv + blocksize; unsigned int enclen = encend - encstart; unsigned int padlen; DBG(DBG_CRYPT, DBG_dump("data before decryption:", encstart, enclen)); /* now, decrypt */ (pst->st_oakley.encrypter->do_crypt)(encstart, enclen, cipherkey->ptr, cipherkey->len, iv, FALSE); padlen = encstart[enclen - 1]; encend = encend - padlen + 1; if (encend < encstart) { libreswan_log("invalid pad length: %u", padlen); return STF_FAIL; } DBG(DBG_CRYPT, { DBG_dump("decrypted payload:", encstart, enclen); DBG_log("striping %u bytes as pad", padlen + 1); }); init_pbs(&md->clr_pbs, encstart, enclen - (padlen + 1), "cleartext"); } { stf_status ret; ret = ikev2_process_payloads(md, &md->clr_pbs, st->st_state, np); if (ret != STF_OK) return ret; } return STF_OK; } static stf_status ikev2_send_auth(struct connection *c, struct state *st, enum phase1_role role, unsigned int np, unsigned char *idhash_out, pb_stream *outpbs) { struct ikev2_a a; pb_stream a_pbs; struct state *pst = st; if (st->st_clonedfrom != 0) pst = state_with_serialno(st->st_clonedfrom); a.isaa_critical = ISAKMP_PAYLOAD_NONCRITICAL; if (DBGP(IMPAIR_SEND_BOGUS_ISAKMP_FLAG)) { libreswan_log( " setting bogus ISAKMP_PAYLOAD_LIBRESWAN_BOGUS flag in ISAKMP payload"); a.isaa_critical |= ISAKMP_PAYLOAD_LIBRESWAN_BOGUS; } a.isaa_np = np; if (c->policy & POLICY_RSASIG) { a.isaa_type = v2_AUTH_RSA; } else if (c->policy & POLICY_PSK) { a.isaa_type = v2_AUTH_SHARED; } else { /* what else is there?... DSS not implemented. */ return STF_FAIL; } if (!out_struct(&a, &ikev2_a_desc, outpbs, &a_pbs)) return STF_INTERNAL_ERROR; if (c->policy & POLICY_RSASIG) { if (!ikev2_calculate_rsa_sha1(pst, role, idhash_out, &a_pbs)) return STF_FATAL + v2N_AUTHENTICATION_FAILED; } else if (c->policy & POLICY_PSK) { if (!ikev2_calculate_psk_auth(pst, role, idhash_out, &a_pbs)) return STF_FAIL + v2N_AUTHENTICATION_FAILED; } close_output_pbs(&a_pbs); return STF_OK; } static stf_status ikev2_parent_inR1outI2_tail( struct pluto_crypto_req_cont *pcrc, struct pluto_crypto_req *r) { struct dh_continuation *dh = (struct dh_continuation *)pcrc; struct msg_digest *md = dh->md; struct state *st = md->st; struct connection *c = st->st_connection; struct ikev2_generic e; unsigned char *encstart; pb_stream e_pbs, e_pbs_cipher; unsigned char *iv; int ivsize; stf_status ret; unsigned char *idhash; unsigned char *authstart; struct state *pst = st; bool send_cert = FALSE; finish_dh_v2(st, r); if (DBGP(DBG_PRIVATE) && DBGP(DBG_CRYPT)) ikev2_log_parentSA(st); pst = st; st = duplicate_state(pst); st->st_msgid = htonl(pst->st_msgid_nextuse); /* PAUL: note ordering */ insert_state(st); md->st = st; md->pst = pst; /* parent had crypto failed, replace it with rekey! */ delete_event(pst); event_schedule(EVENT_SA_REPLACE, c->sa_ike_life_seconds, pst); /* need to force parent state to I2 */ change_state(pst, STATE_PARENT_I2); /* record first packet for later checking of signature */ clonetochunk(pst->st_firstpacket_him, md->message_pbs.start, pbs_offset( &md->message_pbs), "saved first received packet"); /* beginning of data going out */ authstart = reply_stream.cur; /* make sure HDR is at start of a clean buffer */ zero(reply_buffer); init_pbs(&reply_stream, reply_buffer, sizeof(reply_buffer), "reply packet"); /* HDR out */ { struct isakmp_hdr r_hdr = md->hdr; r_hdr.isa_np = ISAKMP_NEXT_v2E; r_hdr.isa_xchg = ISAKMP_v2_AUTH; r_hdr.isa_flags = ISAKMP_FLAGS_I; r_hdr.isa_msgid = st->st_msgid; memcpy(r_hdr.isa_icookie, st->st_icookie, COOKIE_SIZE); memcpy(r_hdr.isa_rcookie, st->st_rcookie, COOKIE_SIZE); if (!out_struct(&r_hdr, &isakmp_hdr_desc, &reply_stream, &md->rbody)) return STF_INTERNAL_ERROR; } /* insert an Encryption payload header */ e.isag_np = ISAKMP_NEXT_v2IDi; e.isag_critical = ISAKMP_PAYLOAD_NONCRITICAL; if (DBGP(IMPAIR_SEND_BOGUS_ISAKMP_FLAG)) { libreswan_log( " setting bogus ISAKMP_PAYLOAD_LIBRESWAN_BOGUS flag in ISAKMP payload"); e.isag_critical |= ISAKMP_PAYLOAD_LIBRESWAN_BOGUS; } if (!out_struct(&e, &ikev2_e_desc, &md->rbody, &e_pbs)) return STF_INTERNAL_ERROR; /* insert IV */ iv = e_pbs.cur; ivsize = st->st_oakley.encrypter->iv_size; if (!out_zero(ivsize, &e_pbs, "iv")) return STF_INTERNAL_ERROR; get_rnd_bytes(iv, ivsize); /* note where cleartext starts */ init_pbs(&e_pbs_cipher, e_pbs.cur, e_pbs.roof - e_pbs.cur, "cleartext"); e_pbs_cipher.container = &e_pbs; e_pbs_cipher.desc = NULL; e_pbs_cipher.cur = e_pbs.cur; encstart = e_pbs_cipher.cur; /* send out the IDi payload */ { struct ikev2_id r_id; pb_stream r_id_pbs; chunk_t id_b; struct hmac_ctx id_ctx; unsigned char *id_start; unsigned int id_len; hmac_init_chunk(&id_ctx, pst->st_oakley.prf_hasher, pst->st_skey_pi); build_id_payload((struct isakmp_ipsec_id *)&r_id, &id_b, &c->spd.this); r_id.isai_critical = ISAKMP_PAYLOAD_NONCRITICAL; if (DBGP(IMPAIR_SEND_BOGUS_ISAKMP_FLAG)) { libreswan_log( " setting bogus ISAKMP_PAYLOAD_LIBRESWAN_BOGUS flag in ISAKMP payload"); r_id.isai_critical |= ISAKMP_PAYLOAD_LIBRESWAN_BOGUS; } { /* decide to send CERT payload */ send_cert = doi_send_ikev2_cert_thinking(st); if (send_cert) r_id.isai_np = ISAKMP_NEXT_v2CERT; else r_id.isai_np = ISAKMP_NEXT_v2AUTH; } id_start = e_pbs_cipher.cur; if (!out_struct(&r_id, &ikev2_id_desc, &e_pbs_cipher, &r_id_pbs) || !out_chunk(id_b, &r_id_pbs, "my identity")) return STF_INTERNAL_ERROR; /* HASH of ID is not done over common header */ id_start += 4; close_output_pbs(&r_id_pbs); /* calculate hash of IDi for AUTH below */ id_len = e_pbs_cipher.cur - id_start; DBG(DBG_CRYPT, DBG_dump_chunk("idhash calc pi", pst->st_skey_pi)); DBG(DBG_CRYPT, DBG_dump("idhash calc I2", id_start, id_len)); hmac_update(&id_ctx, id_start, id_len); idhash = alloca(pst->st_oakley.prf_hasher->hash_digest_len); hmac_final(idhash, &id_ctx); } /* send [CERT,] payload RFC 4306 3.6, 1.2) */ { if (send_cert) { stf_status certstat = ikev2_send_cert( st, md, INITIATOR, ISAKMP_NEXT_v2AUTH, &e_pbs_cipher); if (certstat != STF_OK) return certstat; } } /* send out the AUTH payload */ { lset_t policy; struct connection *c0 = first_pending(pst, &policy, &st->st_whack_sock); unsigned int np = (c0 ? ISAKMP_NEXT_v2SA : ISAKMP_NEXT_v2NONE); DBG(DBG_CONTROL, DBG_log(" payload after AUTH will be %s", (c0) ? "ISAKMP_NEXT_v2SA" : "ISAKMP_NEXT_v2NONE/NOTIFY")); stf_status authstat = ikev2_send_auth(c, st, INITIATOR, np, idhash, &e_pbs_cipher); if (authstat != STF_OK) return authstat; /* * now, find an eligible child SA from the pending list, and emit * SA2i, TSi and TSr and (v2N_USE_TRANSPORT_MODE notification in transport mode) for it . */ if (c0) { chunk_t child_spi, notify_data; st->st_connection = c0; ikev2_emit_ipsec_sa(md, &e_pbs_cipher, ISAKMP_NEXT_v2TSi, c0, policy); st->st_ts_this = ikev2_end_to_ts(&c0->spd.this); st->st_ts_that = ikev2_end_to_ts(&c0->spd.that); ikev2_calc_emit_ts(md, &e_pbs_cipher, INITIATOR, c0, policy); if ( !(st->st_connection->policy & POLICY_TUNNEL) ) { DBG_log( "Initiator child policy is transport mode, sending v2N_USE_TRANSPORT_MODE"); memset(&child_spi, 0, sizeof(child_spi)); memset(&notify_data, 0, sizeof(notify_data)); ship_v2N(ISAKMP_NEXT_v2NONE, ISAKMP_PAYLOAD_NONCRITICAL, 0, &child_spi, v2N_USE_TRANSPORT_MODE, &notify_data, &e_pbs_cipher); } } else { libreswan_log( "no pending SAs found, PARENT SA keyed only"); } } /* * need to extend the packet so that we will know how big it is * since the length is under the integrity check */ ikev2_padup_pre_encrypt(md, &e_pbs_cipher); close_output_pbs(&e_pbs_cipher); { unsigned char *authloc = ikev2_authloc(md, &e_pbs); if (authloc == NULL) return STF_INTERNAL_ERROR; close_output_pbs(&e_pbs); close_output_pbs(&md->rbody); close_output_pbs(&reply_stream); ret = ikev2_encrypt_msg(md, INITIATOR, authstart, iv, encstart, authloc, &e_pbs, &e_pbs_cipher); if (ret != STF_OK) return ret; } /* keep it for a retransmit if necessary, but on initiator * we never do that, but send_ike_msg() uses it. */ freeanychunk(pst->st_tpacket); clonetochunk(pst->st_tpacket, reply_stream.start, pbs_offset(&reply_stream), "reply packet for ikev2_parent_outI1"); /* * Delete previous retransmission event. */ delete_event(st); event_schedule(EVENT_v2_RETRANSMIT, EVENT_RETRANSMIT_DELAY_0, st); return STF_OK; } /* * *************************************************************** * PARENT_inI2 ***** *************************************************************** * - * * */ static void ikev2_parent_inI2outR2_continue(struct pluto_crypto_req_cont *pcrc, struct pluto_crypto_req *r, err_t ugh); static stf_status ikev2_parent_inI2outR2_tail( struct pluto_crypto_req_cont *pcrc, struct pluto_crypto_req *r); stf_status ikev2parent_inI2outR2(struct msg_digest *md) { struct state *st = md->st; /* struct connection *c = st->st_connection; */ /* * the initiator sent us an encrypted payload. We need to calculate * our g^xy, and skeyseed values, and then decrypt the payload. */ DBG(DBG_CONTROLMORE, DBG_log( "ikev2 parent inI2outR2: calculating g^{xy} in order to decrypt I2")); /* verify that there is in fact an encrypted payload */ if (!md->chain[ISAKMP_NEXT_v2E]) { libreswan_log("R2 state should receive an encrypted payload"); reset_globals(); /* XXX suspicious - why was this deemed neccessary? */ return STF_FATAL; } /* now. we need to go calculate the g^xy */ { struct dh_continuation *dh = alloc_thing( struct dh_continuation, "ikev2_inI2outR2 KE"); stf_status e; dh->md = md; set_suspended(st, dh->md); pcrc_init(&dh->dh_pcrc); dh->dh_pcrc.pcrc_func = ikev2_parent_inI2outR2_continue; e = start_dh_v2(&dh->dh_pcrc, st, st->st_import, RESPONDER, st->st_oakley.groupnum); if (e != STF_SUSPEND && e != STF_INLINE) { loglog(RC_CRYPTOFAILED, "system too busy"); delete_state(st); } reset_globals(); return e; } } static void ikev2_parent_inI2outR2_continue(struct pluto_crypto_req_cont *pcrc, struct pluto_crypto_req *r, err_t ugh) { struct dh_continuation *dh = (struct dh_continuation *)pcrc; struct msg_digest *md = dh->md; struct state *const st = md->st; stf_status e; DBG(DBG_CONTROLMORE, DBG_log("ikev2 parent inI2outR2: calculating g^{xy}, sending R2")); if (st == NULL) { loglog(RC_LOG_SERIOUS, "%s: Request was disconnected from state", __FUNCTION__); if (dh->md) release_md(dh->md); return; } /* XXX should check out ugh */ passert(ugh == NULL); passert(cur_state == NULL); passert(st != NULL); passert(st->st_suspended_md == dh->md); set_suspended(st, NULL); /* no longer connected or suspended */ set_cur_state(st); st->st_calculating = FALSE; e = ikev2_parent_inI2outR2_tail(pcrc, r); if ( e > STF_FAIL) { /* we do not send a notify because we are the initiator that could be responding to an error notification */ int v2_notify_num = e - STF_FAIL; DBG_log( "ikev2_parent_inI2outR2_tail returned STF_FAIL with %s", enum_name(&ikev2_notify_names, v2_notify_num)); } else if ( e != STF_OK) { DBG_log("ikev2_parent_inI2outR2_tail returned %s", enum_name(&stfstatus_name, e)); } if (dh->md != NULL) { complete_v2_state_transition(&dh->md, e); if (dh->md) release_md(dh->md); } reset_globals(); } static stf_status ikev2_parent_inI2outR2_tail( struct pluto_crypto_req_cont *pcrc, struct pluto_crypto_req *r) { struct dh_continuation *dh = (struct dh_continuation *)pcrc; struct msg_digest *md = dh->md; struct state *const st = md->st; struct connection *c = st->st_connection; unsigned char *idhash_in, *idhash_out; unsigned char *authstart; unsigned int np; int v2_notify_num = 0; /* extract calculated values from r */ finish_dh_v2(st, r); if (DBGP(DBG_PRIVATE) && DBGP(DBG_CRYPT)) ikev2_log_parentSA(st); /* decrypt things. */ { stf_status ret; ret = ikev2_decrypt_msg(md, RESPONDER); if (ret != STF_OK) return ret; } /*Once the message has been decrypted, then only we can check for auth payload*/ /*check the presense of auth payload now so that it does not crash in rehash_state if auth payload has not been received*/ if (!md->chain[ISAKMP_NEXT_v2AUTH]) { libreswan_log("no authentication payload found"); return STF_FAIL; } if (!ikev2_decode_peer_id(md, RESPONDER)) return STF_FAIL + v2N_AUTHENTICATION_FAILED; { struct hmac_ctx id_ctx; const pb_stream *id_pbs = &md->chain[ISAKMP_NEXT_v2IDi]->pbs; unsigned char *idstart = id_pbs->start + 4; unsigned int idlen = pbs_room(id_pbs) - 4; hmac_init_chunk(&id_ctx, st->st_oakley.prf_hasher, st->st_skey_pi); /* calculate hash of IDi for AUTH below */ DBG(DBG_CRYPT, DBG_dump_chunk("idhash verify pi", st->st_skey_pi)); DBG(DBG_CRYPT, DBG_dump("idhash verify I2", idstart, idlen)); hmac_update(&id_ctx, idstart, idlen); idhash_in = alloca(st->st_oakley.prf_hasher->hash_digest_len); hmac_final(idhash_in, &id_ctx); } /* process CERT payload */ { if (md->chain[ISAKMP_NEXT_v2CERT]) { /* should we check if we should accept a cert payload ? * has_preloaded_public_key(st) */ DBG(DBG_CONTROLMORE, DBG_log( "has a v2_CERT payload going to process it ")); ikev2_decode_cert(md); } } /* process CERTREQ payload */ if (md->chain[ISAKMP_NEXT_v2CERTREQ]) { DBG(DBG_CONTROLMORE, DBG_log("has a v2CERTREQ payload going to decode it")); ikev2_decode_cr(md, &st->st_connection->requested_ca); } /* process AUTH payload now */ /* now check signature from RSA key */ switch (md->chain[ISAKMP_NEXT_v2AUTH]->payload.v2a.isaa_type) { case v2_AUTH_RSA: { stf_status authstat = ikev2_verify_rsa_sha1(st, RESPONDER, idhash_in, NULL, /* keys from DNS */ NULL, /* gateways from DNS */ &md->chain[ ISAKMP_NEXT_v2AUTH]->pbs); if (authstat != STF_OK) { libreswan_log("RSA authentication failed"); SEND_NOTIFICATION(v2N_AUTHENTICATION_FAILED); return STF_FATAL; } break; } case v2_AUTH_SHARED: { stf_status authstat = ikev2_verify_psk_auth(st, RESPONDER, idhash_in, &md->chain[ ISAKMP_NEXT_v2AUTH]->pbs); if (authstat != STF_OK) { libreswan_log( "PSK authentication failed AUTH mismatch!"); SEND_NOTIFICATION(v2N_AUTHENTICATION_FAILED); return STF_FATAL; } break; } default: libreswan_log("authentication method: %s not supported", enum_name(&ikev2_auth_names, md->chain[ISAKMP_NEXT_v2AUTH]->payload. v2a.isaa_type)); return STF_FATAL; } /* Is there a notify about an error ? */ if (md->chain[ISAKMP_NEXT_v2N] != NULL) { DBG(DBG_CONTROL, DBG_log( " notify payload detected, should be processed....")); } /* good. now create child state */ /* note: as we will switch to child state, we force the parent to the * new state now */ change_state(st, STATE_PARENT_R2); c->newest_isakmp_sa = st->st_serialno; delete_event(st); event_schedule(EVENT_SA_REPLACE, c->sa_ike_life_seconds, st); authstart = reply_stream.cur; /* send response */ { unsigned char *encstart; unsigned char *iv; unsigned int ivsize; struct ikev2_generic e; pb_stream e_pbs, e_pbs_cipher; stf_status ret; bool send_cert = FALSE; /* make sure HDR is at start of a clean buffer */ zero(reply_buffer); init_pbs(&reply_stream, reply_buffer, sizeof(reply_buffer), "reply packet"); /* HDR out */ { struct isakmp_hdr r_hdr = md->hdr; r_hdr.isa_np = ISAKMP_NEXT_v2E; r_hdr.isa_xchg = ISAKMP_v2_AUTH; r_hdr.isa_flags = ISAKMP_FLAGS_R; memcpy(r_hdr.isa_icookie, st->st_icookie, COOKIE_SIZE); memcpy(r_hdr.isa_rcookie, st->st_rcookie, COOKIE_SIZE); if (!out_struct(&r_hdr, &isakmp_hdr_desc, &reply_stream, &md->rbody)) return STF_INTERNAL_ERROR; } /* insert an Encryption payload header */ e.isag_np = ISAKMP_NEXT_v2IDr; e.isag_critical = ISAKMP_PAYLOAD_NONCRITICAL; if (!out_struct(&e, &ikev2_e_desc, &md->rbody, &e_pbs)) return STF_INTERNAL_ERROR; /* insert IV */ iv = e_pbs.cur; ivsize = st->st_oakley.encrypter->iv_size; if (!out_zero(ivsize, &e_pbs, "iv")) return STF_INTERNAL_ERROR; get_rnd_bytes(iv, ivsize); /* note where cleartext starts */ init_pbs(&e_pbs_cipher, e_pbs.cur, e_pbs.roof - e_pbs.cur, "cleartext"); e_pbs_cipher.container = &e_pbs; e_pbs_cipher.desc = NULL; e_pbs_cipher.cur = e_pbs.cur; encstart = e_pbs_cipher.cur; /* decide to send CERT payload before we generate IDr */ send_cert = doi_send_ikev2_cert_thinking(st); /* send out the IDr payload */ { struct ikev2_id r_id; pb_stream r_id_pbs; chunk_t id_b; struct hmac_ctx id_ctx; unsigned char *id_start; unsigned int id_len; hmac_init_chunk(&id_ctx, st->st_oakley.prf_hasher, st->st_skey_pr); build_id_payload((struct isakmp_ipsec_id *)&r_id, &id_b, &c->spd.this); r_id.isai_critical = ISAKMP_PAYLOAD_NONCRITICAL; if (send_cert) r_id.isai_np = ISAKMP_NEXT_v2CERT; else r_id.isai_np = ISAKMP_NEXT_v2AUTH; id_start = e_pbs_cipher.cur; if (!out_struct(&r_id, &ikev2_id_desc, &e_pbs_cipher, &r_id_pbs) || !out_chunk(id_b, &r_id_pbs, "my identity")) return STF_INTERNAL_ERROR; close_output_pbs(&r_id_pbs); id_start += 4; /* calculate hash of IDi for AUTH below */ id_len = e_pbs_cipher.cur - id_start; DBG(DBG_CRYPT, DBG_dump_chunk("idhash calc pr", st->st_skey_pr)); DBG(DBG_CRYPT, DBG_dump("idhash calc R2", id_start, id_len)); hmac_update(&id_ctx, id_start, id_len); idhash_out = alloca( st->st_oakley.prf_hasher->hash_digest_len); hmac_final(idhash_out, &id_ctx); } DBG(DBG_CONTROLMORE, DBG_log("assembled IDr payload -- CERT next")); /* send CERT payload RFC 4306 3.6, 1.2:([CERT,] ) */ if (send_cert) { stf_status certstat = ikev2_send_cert(st, md, RESPONDER, ISAKMP_NEXT_v2AUTH, &e_pbs_cipher); if (certstat != STF_OK) return certstat; } /* authentication good, see if there is a child SA being proposed */ if (md->chain[ISAKMP_NEXT_v2SA] == NULL || md->chain[ISAKMP_NEXT_v2TSi] == NULL || md->chain[ISAKMP_NEXT_v2TSr] == NULL) { /* initiator didn't propose anything. Weird. Try unpending out end. */ /* UNPEND XXX */ libreswan_log("No CHILD SA proposals received."); np = ISAKMP_NEXT_v2NONE; } else { DBG_log("CHILD SA proposals received"); libreswan_log( "PAUL: this is where we have to check the TSi/TSr"); np = ISAKMP_NEXT_v2SA; } DBG(DBG_CONTROLMORE, DBG_log("going to assemble AUTH payload")); /* now send AUTH payload */ { stf_status authstat = ikev2_send_auth(c, st, RESPONDER, np, idhash_out, &e_pbs_cipher); if (authstat != STF_OK) return authstat; } if (np == ISAKMP_NEXT_v2SA) { /* must have enough to build an CHILD_SA */ ret = ikev2_child_sa_respond(md, RESPONDER, &e_pbs_cipher); if (ret > STF_FAIL) { v2_notify_num = ret - STF_FAIL; DBG(DBG_CONTROL, DBG_log( "ikev2_child_sa_respond returned STF_FAIL with %s", enum_name(&ikev2_notify_names, v2_notify_num))); np = ISAKMP_NEXT_v2NONE; } else if (ret != STF_OK) { DBG_log("ikev2_child_sa_respond returned %s", enum_name( &stfstatus_name, ret)); np = ISAKMP_NEXT_v2NONE; } } ikev2_padup_pre_encrypt(md, &e_pbs_cipher); close_output_pbs(&e_pbs_cipher); { unsigned char *authloc = ikev2_authloc(md, &e_pbs); if (authloc == NULL) return STF_INTERNAL_ERROR; close_output_pbs(&e_pbs); close_output_pbs(&md->rbody); close_output_pbs(&reply_stream); ret = ikev2_encrypt_msg(md, RESPONDER, authstart, iv, encstart, authloc, &e_pbs, &e_pbs_cipher); if (ret != STF_OK) return ret; } } /* keep it for a retransmit if necessary */ freeanychunk(st->st_tpacket); clonetochunk(st->st_tpacket, reply_stream.start, pbs_offset(&reply_stream), "reply packet for ikev2_parent_inI2outR2_tail"); /* note: retransimission is driven by initiator */ /* if the child failed, delete its state here - we sent the packet */ /* PAUL */ return STF_OK; } /* * *************************************************************** * PARENT_inR2 (I3 state) ***** *************************************************************** * - there are no cryptographic continuations, but be certain * that there will have to be DNS continuations, but they * just aren't implemented yet. * */ stf_status ikev2parent_inR2(struct msg_digest *md) { struct state *st = md->st; struct connection *c = st->st_connection; unsigned char *idhash_in; struct state *pst = st; if (st->st_clonedfrom != 0) pst = state_with_serialno(st->st_clonedfrom); /* * the initiator sent us an encrypted payload. We need to calculate * our g^xy, and skeyseed values, and then decrypt the payload. */ DBG(DBG_CONTROLMORE, DBG_log( "ikev2 parent inR2: calculating g^{xy} in order to decrypt I2")); /* verify that there is in fact an encrypted payload */ if (!md->chain[ISAKMP_NEXT_v2E]) { libreswan_log("R2 state should receive an encrypted payload"); return STF_FATAL; } /* decrypt things. */ { stf_status ret; ret = ikev2_decrypt_msg(md, INITIATOR); if (ret != STF_OK) return ret; } if (!ikev2_decode_peer_id(md, INITIATOR)) return STF_FAIL + v2N_AUTHENTICATION_FAILED; { struct hmac_ctx id_ctx; const pb_stream *id_pbs = &md->chain[ISAKMP_NEXT_v2IDr]->pbs; unsigned char *idstart = id_pbs->start + 4; unsigned int idlen = pbs_room(id_pbs) - 4; hmac_init_chunk(&id_ctx, pst->st_oakley.prf_hasher, pst->st_skey_pr); /* calculate hash of IDr for AUTH below */ DBG(DBG_CRYPT, DBG_dump_chunk("idhash verify pr", pst->st_skey_pr)); DBG(DBG_CRYPT, DBG_dump("idhash auth R2", idstart, idlen)); hmac_update(&id_ctx, idstart, idlen); idhash_in = alloca(pst->st_oakley.prf_hasher->hash_digest_len); hmac_final(idhash_in, &id_ctx); } if (md->chain[ISAKMP_NEXT_v2CERT]) { /* should we check if we should accept a cert payload ? * has_preloaded_public_key(st) */ /* in v1 code it is decode_cert(struct msg_digest *md) */ DBG(DBG_CONTROLMORE, DBG_log("has a v2_CERT payload going to decode it")); ikev2_decode_cert(md); } /* process AUTH payload */ if (!md->chain[ISAKMP_NEXT_v2AUTH]) { libreswan_log("no authentication payload found"); return STF_FAIL; } /* now check signature from RSA key */ switch (md->chain[ISAKMP_NEXT_v2AUTH]->payload.v2a.isaa_type) { case v2_AUTH_RSA: { stf_status authstat = ikev2_verify_rsa_sha1(pst, INITIATOR, idhash_in, NULL, /* keys from DNS */ NULL, /* gateways from DNS */ &md->chain[ ISAKMP_NEXT_v2AUTH]->pbs); if (authstat != STF_OK) { libreswan_log("authentication failed"); SEND_NOTIFICATION(v2N_AUTHENTICATION_FAILED); return STF_FAIL; } break; } case v2_AUTH_SHARED: { stf_status authstat = ikev2_verify_psk_auth(pst, INITIATOR, idhash_in, &md->chain[ ISAKMP_NEXT_v2AUTH]->pbs); if (authstat != STF_OK) { libreswan_log("PSK authentication failed"); SEND_NOTIFICATION(v2N_AUTHENTICATION_FAILED); return STF_FAIL; } break; } default: libreswan_log("authentication method: %s not supported", enum_name(&ikev2_auth_names, md->chain[ISAKMP_NEXT_v2AUTH]->payload. v2a.isaa_type)); return STF_FAIL; } /* * update the parent state to make sure that it knows we have * authenticated properly. */ change_state(pst, STATE_PARENT_I3); c->newest_isakmp_sa = pst->st_serialno; /* authentication good, see if there is a child SA available */ if (md->chain[ISAKMP_NEXT_v2SA] == NULL || md->chain[ISAKMP_NEXT_v2TSi] == NULL || md->chain[ISAKMP_NEXT_v2TSr] == NULL) { /* not really anything to here... but it would be worth unpending again */ DBG(DBG_CONTROLMORE, DBG_log( "no v2SA, v2TSi or v2TSr received, not attempting to setup child SA")); DBG(DBG_CONTROLMORE, DBG_log(" Should we check for some notify?")); /* * Delete previous retransmission event. */ delete_event(st); return STF_OK; } { int bestfit_n, bestfit_p, bestfit_pr; unsigned int best_tsi_i, best_tsr_i; bestfit_n = -1; bestfit_p = -1; bestfit_pr = -1; /* Check TSi/TSr http://tools.ietf.org/html/rfc5996#section-2.9 */ DBG(DBG_CONTROLMORE, DBG_log(" check narrowing - we are responding to I2")); struct payload_digest *const tsi_pd = md->chain[ISAKMP_NEXT_v2TSi]; struct payload_digest *const tsr_pd = md->chain[ISAKMP_NEXT_v2TSr]; struct traffic_selector tsi[16], tsr[16]; #if 0 bool instantiate = FALSE; ip_subnet tsi_subnet, tsr_subnet; const char *oops; #endif unsigned int tsi_n, tsr_n; tsi_n = ikev2_parse_ts(tsi_pd, tsi, 16); tsr_n = ikev2_parse_ts(tsr_pd, tsr, 16); DBG_log( "Checking TSi(%d)/TSr(%d) selectors, looking for exact match", tsi_n, tsr_n); { struct spd_route *sra; sra = &c->spd; int bfit_n = ikev2_evaluate_connection_fit(c, sra, INITIATOR, tsi, tsr, tsi_n, tsr_n); if (bfit_n > bestfit_n) { DBG(DBG_CONTROLMORE, DBG_log( "bfit_n=ikev2_evaluate_connection_fit found better fit c %s", c->name)); int bfit_p = ikev2_evaluate_connection_port_fit(c, sra, INITIATOR, tsi, tsr, tsi_n, tsr_n, &best_tsi_i, &best_tsr_i); if (bfit_p > bestfit_p) { DBG(DBG_CONTROLMORE, DBG_log( "ikev2_evaluate_connection_port_fit found better fit c %s, tsi[%d],tsr[%d]", c->name, best_tsi_i, best_tsr_i)); int bfit_pr = ikev2_evaluate_connection_protocol_fit( c, sra, INITIATOR, tsi, tsr, tsi_n, tsr_n, &best_tsi_i, &best_tsr_i); if (bfit_pr > bestfit_pr ) { DBG(DBG_CONTROLMORE, DBG_log( "ikev2_evaluate_connection_protocol_fit found better fit c %s, tsi[%d],tsr[%d]", c ->name, best_tsi_i, best_tsr_i)); bestfit_p = bfit_p; bestfit_n = bfit_n; } else { DBG(DBG_CONTROLMORE, DBG_log( "protocol range fit c %s c->name was rejected by protocol matching", c ->name)); } } } else { DBG(DBG_CONTROLMORE, DBG_log( "prefix range fit c %s c->name was rejected by port matching", c->name)); } } if ( ( bestfit_n > 0 ) && (bestfit_p > 0)) { DBG(DBG_CONTROLMORE, DBG_log( ( "found an acceptable TSi/TSr Traffic Selector"))); memcpy(&st->st_ts_this, &tsi[best_tsi_i], sizeof(struct traffic_selector)); memcpy(&st->st_ts_that, &tsr[best_tsr_i], sizeof(struct traffic_selector)); ikev2_print_ts(&st->st_ts_this); ikev2_print_ts(&st->st_ts_that); ip_subnet tmp_subnet_i; ip_subnet tmp_subnet_r; rangetosubnet(&st->st_ts_this.low, &st->st_ts_this.high, &tmp_subnet_i); rangetosubnet(&st->st_ts_that.low, &st->st_ts_that.high, &tmp_subnet_r); c->spd.this.client = tmp_subnet_i; c->spd.this.port = st->st_ts_this.startport; c->spd.this.protocol = st->st_ts_this.ipprotoid; setportof(htons( c->spd.this.port), &c->spd.this.host_addr); setportof(htons( c->spd.this.port), &c->spd.this.client.addr); if ( subnetishost(&c->spd.this.client) && addrinsubnet(&c->spd.this.host_addr, &c->spd.this.client)) c->spd.this.has_client = FALSE; else c->spd.this.has_client = TRUE; c->spd.that.client = tmp_subnet_r; c->spd.that.port = st->st_ts_that.startport; c->spd.that.protocol = st->st_ts_that.ipprotoid; setportof(htons( c->spd.that.port), &c->spd.that.host_addr); setportof(htons( c->spd.that.port), &c->spd.that.client.addr); if ( subnetishost(&c->spd.that.client) && addrinsubnet(&c->spd.that.host_addr, &c->spd.that.client)) c->spd.that.has_client = FALSE; else c->spd.that.has_client = TRUE; /* AAAA */ } else { DBG(DBG_CONTROLMORE, DBG_log(( "reject responder TSi/TSr Traffic Selector"))); /* prevents parent from going to I3 */ return STF_FAIL + v2N_TS_UNACCEPTABLE; } } /* end of TS check block */ { v2_notification_t rn; struct payload_digest *const sa_pd = md->chain[ISAKMP_NEXT_v2SA]; rn = ikev2_parse_child_sa_body(&sa_pd->pbs, &sa_pd->payload.v2sa, NULL, st, FALSE); if (rn != v2N_NOTHING_WRONG) return STF_FAIL + rn; } { struct payload_digest *p; for (p = md->chain[ISAKMP_NEXT_v2N]; p != NULL; p = p->next) { /* RFC 5996 */ /*Types in the range 0 - 16383 are intended for reporting errors. An * implementation receiving a Notify payload with one of these types * that it does not recognize in a response MUST assume that the * corresponding request has failed entirely. Unrecognized error types * in a request and status types in a request or response MUST be * ignored, and they should be logged.*/ if (enum_name(&ikev2_notify_names, p->payload.v2n.isan_type) == NULL) { if (p->payload.v2n.isan_type < v2N_INITIAL_CONTACT) return STF_FAIL + p->payload.v2n.isan_type; } if ( p->payload.v2n.isan_type == v2N_USE_TRANSPORT_MODE ) { if ( st->st_connection->policy & POLICY_TUNNEL) { /*This means we did not send v2N_USE_TRANSPORT, however responder is sending it in now (inR2), seems incorrect*/ DBG(DBG_CONTROLMORE, DBG_log( "Initiator policy is tunnel, responder sends v2N_USE_TRANSPORT_MODE notification in inR2, ignoring it")); } else { DBG(DBG_CONTROLMORE, DBG_log( "Initiator policy is transport, responder sends v2N_USE_TRANSPORT_MODE, setting CHILD SA to transport mode")); if (st->st_esp.present == TRUE) { /*libreswan supports only "esp" with ikev2 it seems, look at ikev2_parse_child_sa_body handling*/ st->st_esp.attrs.encapsulation = ENCAPSULATION_MODE_TRANSPORT; } } } } /* for */ } /* notification block */ ikev2_derive_child_keys(st, md->role); c->newest_ipsec_sa = st->st_serialno; /* now install child SAs */ if (!install_ipsec_sa(st, TRUE)) return STF_FATAL; /* * Delete previous retransmission event. */ delete_event(st); return STF_OK; } /* * Cookie = <VersionIDofSecret> | Hash(Ni | IPi | SPIi | <secret>) * where <secret> is a randomly generated secret known only to the * in LSW implementation <VersionIDofSecret> is not used. */ static bool ikev2_get_dcookie(u_char *dcookie, chunk_t st_ni, ip_address *addr, u_int8_t *spiI) { size_t addr_length; SHA1_CTX ctx_sha1; unsigned char addr_buff[ sizeof(union { struct in_addr A; struct in6_addr B; })]; addr_length = addrbytesof(addr, addr_buff, sizeof(addr_buff)); SHA1Init(&ctx_sha1); SHA1Update(&ctx_sha1, st_ni.ptr, st_ni.len); SHA1Update(&ctx_sha1, addr_buff, addr_length); SHA1Update(&ctx_sha1, spiI, sizeof(*spiI)); SHA1Update(&ctx_sha1, ikev2_secret_of_the_day, SHA1_DIGEST_SIZE); SHA1Final(dcookie, &ctx_sha1); DBG(DBG_PRIVATE, DBG_log("ikev2 secret_of_the_day used %s, length %d", ikev2_secret_of_the_day, SHA1_DIGEST_SIZE); ); DBG(DBG_CRYPT, DBG_dump("computed dcookie: HASH(Ni | IPi | SPIi | <secret>)", dcookie, SHA1_DIGEST_SIZE)); #if 0 ikev2_secrets_recycle++; if (ikev2_secrets_recycle >= 32768) { /* handed out too many cookies, cycle secrets */ ikev2_secrets_recycle = 0; /* can we call init_secrets() without adding an EVENT? */ init_secrets(); } #endif return TRUE; } /* * *************************************************************** * NOTIFICATION_OUT Complete packet ***** *************************************************************** * */ void send_v2_notification(struct state *p1st, u_int16_t type, struct state *encst, u_char *icookie, u_char *rcookie, chunk_t *n_data) { u_char buffer[1024]; pb_stream reply; pb_stream rbody; chunk_t child_spi, notify_data; /* this function is not generic enough yet just enough for 6msg * TBD accept HDR FLAGS as arg. default ISAKMP_FLAGS_R * TBD when there is a child SA use that SPI in the notify paylod. * TBD support encrypted notifications payloads. * TBD accept Critical bit as an argument. default is set. * TBD accept exchange type as an arg, default is ISAKMP_v2_SA_INIT * do we need to send a notify with empty data? * do we need to support more Protocol ID? more than PROTO_ISAKMP */ libreswan_log("sending %s notification %s to %s:%u", encst ? "encrypted " : "", enum_name(&ikev2_notify_names, type), ip_str(&p1st->st_remoteaddr), p1st->st_remoteport); #if 0 /* Empty notification data section should be fine? */ if (n_data == NULL) { DBG(DBG_CONTROLMORE, DBG_log("don't send packet when notification data empty")); return; } #endif memset(buffer, 0, sizeof(buffer)); init_pbs(&reply, buffer, sizeof(buffer), "notification msg"); /* HDR out */ { struct isakmp_hdr n_hdr; zero(&n_hdr); /* default to 0 */ /* AAA should we copy from MD? */ /* Impair function will raise major/minor by 1 for testing */ n_hdr.isa_version = build_ike_version(); memcpy(n_hdr.isa_rcookie, rcookie, COOKIE_SIZE); memcpy(n_hdr.isa_icookie, icookie, COOKIE_SIZE); n_hdr.isa_xchg = ISAKMP_v2_SA_INIT; n_hdr.isa_np = ISAKMP_NEXT_v2N; n_hdr.isa_flags &= ~ISAKMP_FLAGS_I; n_hdr.isa_flags |= ISAKMP_FLAGS_R; #warning check msgid code here /* PAUL: shouldn't we set n_hdr.isa_msgid = [htonl](p1st->st_msgid); */ if (!out_struct(&n_hdr, &isakmp_hdr_desc, &reply, &rbody)) { libreswan_log( "error initializing hdr for notify message"); return; } } child_spi.ptr = NULL; child_spi.len = 0; /* build and add v2N payload to the packet */ memset(&child_spi, 0, sizeof(child_spi)); memset(&notify_data, 0, sizeof(notify_data)); ship_v2N(ISAKMP_NEXT_v2NONE, DBGP( IMPAIR_SEND_BOGUS_ISAKMP_FLAG) ? (ISAKMP_PAYLOAD_NONCRITICAL | ISAKMP_PAYLOAD_LIBRESWAN_BOGUS) : ISAKMP_PAYLOAD_NONCRITICAL, PROTO_ISAKMP, &child_spi, type, n_data, &rbody); close_message(&rbody, p1st); close_output_pbs(&reply); clonetochunk(p1st->st_tpacket, reply.start, pbs_offset(&reply), "notification packet"); send_ike_msg(p1st, __FUNCTION__); } /* add notify payload to the rbody */ bool ship_v2N(unsigned int np, u_int8_t critical, u_int8_t protoid, chunk_t *spi, u_int16_t type, chunk_t *n_data, pb_stream *rbody) { struct ikev2_notify n; pb_stream n_pbs; DBG(DBG_CONTROLMORE, DBG_log("Adding a v2N Payload")); n.isan_np = np; n.isan_critical = critical; if (DBGP(IMPAIR_SEND_BOGUS_ISAKMP_FLAG)) { libreswan_log( " setting bogus ISAKMP_PAYLOAD_LIBRESWAN_BOGUS flag in ISAKMP payload"); n.isan_critical |= ISAKMP_PAYLOAD_LIBRESWAN_BOGUS; } n.isan_protoid = protoid; n.isan_spisize = spi->len; n.isan_type = type; if (!out_struct(&n, &ikev2_notify_desc, rbody, &n_pbs)) { libreswan_log( "error initializing notify payload for notify message"); return FALSE; } if (spi->len > 0) { if (!out_raw(spi->ptr, spi->len, &n_pbs, "SPI ")) { libreswan_log("error writing SPI to notify payload"); return FALSE; } } if (n_data != NULL) { if (!out_raw(n_data->ptr, n_data->len, &n_pbs, "Notify data")) { libreswan_log( "error writing notify payload for notify message"); return FALSE; } } close_output_pbs(&n_pbs); return TRUE; } /* * *************************************************************** * INFORMATIONAL ***** *************************************************************** * - * * */ stf_status process_informational_ikev2(struct msg_digest *md) { /* verify that there is in fact an encrypted payload */ if (!md->chain[ISAKMP_NEXT_v2E]) { libreswan_log( "Ignoring informational exchange outside encrypted payload (rfc5996 section 1.4)"); return STF_IGNORE; } /* decrypt things. */ { stf_status ret; if (md->hdr.isa_flags & ISAKMP_FLAGS_I) { DBG(DBG_CONTROLMORE, DBG_log( "received informational exchange request from INITIATOR")); ret = ikev2_decrypt_msg(md, RESPONDER); } else { DBG(DBG_CONTROLMORE, DBG_log( "received informational exchange request from RESPONDER")); ret = ikev2_decrypt_msg(md, INITIATOR); } if (ret != STF_OK) return ret; } { struct payload_digest *p; struct ikev2_delete *v2del = NULL; stf_status ret; struct state *const st = md->st; /* Only send response if it is request*/ if (!(md->hdr.isa_flags & ISAKMP_FLAGS_R)) { unsigned char *authstart; pb_stream e_pbs, e_pbs_cipher; struct ikev2_generic e; unsigned char *iv; int ivsize; unsigned char *encstart; /* beginning of data going out */ authstart = reply_stream.cur; /* make sure HDR is at start of a clean buffer */ zero(reply_buffer); init_pbs(&reply_stream, reply_buffer, sizeof(reply_buffer), "information exchange reply packet"); DBG(DBG_CONTROLMORE | DBG_DPD, DBG_log("Received an INFORMATIONAL request, " "updating liveness, no longer pending")); st->st_last_liveness = now(); st->st_pend_liveness = FALSE; /* HDR out */ { struct isakmp_hdr r_hdr; zero(&r_hdr); /* default to 0 */ /* AAA should we copy from MD? */ r_hdr.isa_version = build_ike_version(); memcpy(r_hdr.isa_rcookie, st->st_rcookie, COOKIE_SIZE); memcpy(r_hdr.isa_icookie, st->st_icookie, COOKIE_SIZE); r_hdr.isa_xchg = ISAKMP_v2_INFORMATIONAL; r_hdr.isa_np = ISAKMP_NEXT_v2E; r_hdr.isa_msgid = htonl(md->msgid_received); /*set initiator bit if we are initiator*/ if (md->role == INITIATOR) r_hdr.isa_flags |= ISAKMP_FLAGS_I; r_hdr.isa_flags |= ISAKMP_FLAGS_R; if (!out_struct(&r_hdr, &isakmp_hdr_desc, &reply_stream, &md->rbody)) { libreswan_log( "error initializing hdr for informational message"); return STF_INTERNAL_ERROR; } } /*HDR Done*/ /* insert an Encryption payload header */ if (md->chain[ISAKMP_NEXT_v2D]) { bool ikesa_flag = FALSE; /* Search if there is a IKE SA delete payload*/ for (p = md->chain[ISAKMP_NEXT_v2D]; p != NULL; p = p->next) { if (p->payload.v2delete.isad_protoid == PROTO_ISAKMP) { e.isag_np = ISAKMP_NEXT_v2NONE; ikesa_flag = TRUE; break; } } /* if there is no IKE SA DELETE PAYLOAD*/ /* That means, there are AH OR ESP*/ if (!ikesa_flag) e.isag_np = ISAKMP_NEXT_v2D; } else { e.isag_np = ISAKMP_NEXT_v2NONE; } e.isag_critical = ISAKMP_PAYLOAD_NONCRITICAL; if (!out_struct(&e, &ikev2_e_desc, &md->rbody, &e_pbs)) return STF_INTERNAL_ERROR; /* insert IV */ iv = e_pbs.cur; ivsize = st->st_oakley.encrypter->iv_size; if (!out_zero(ivsize, &e_pbs, "iv")) return STF_INTERNAL_ERROR; get_rnd_bytes(iv, ivsize); /* note where cleartext starts */ init_pbs(&e_pbs_cipher, e_pbs.cur, e_pbs.roof - e_pbs.cur, "cleartext"); e_pbs_cipher.container = &e_pbs; e_pbs_cipher.desc = NULL; e_pbs_cipher.cur = e_pbs.cur; encstart = e_pbs_cipher.cur; if (md->chain[ISAKMP_NEXT_v2D]) { for (p = md->chain[ISAKMP_NEXT_v2D]; p != NULL; p = p->next) { v2del = &p->payload.v2delete; switch (v2del->isad_protoid) { case PROTO_ISAKMP: /* My understanding is that delete payload for IKE SA * should be the only payload in the informational exchange */ break; case PROTO_IPSEC_AH: case PROTO_IPSEC_ESP: { char spi_buf[1024]; pb_stream del_pbs; struct ikev2_delete v2del_tmp; u_int16_t i, j = 0; u_char *spi; for (i = 0; i < v2del->isad_nrspi; i++ ) { spi = p->pbs.cur + (i * v2del-> isad_spisize); DBG(DBG_CONTROLMORE, DBG_log( "received delete request for %s SA(0x%08lx)", enum_show( & protocol_names, v2del -> isad_protoid), ( unsigned long) ntohl(( unsigned long) *( ipsec_spi_t *) spi))); struct state *dst = find_state_ikev2_child_to_delete( st->st_icookie, st->st_rcookie, v2del->isad_protoid, *( ipsec_spi_t *)spi); if (dst != NULL) { struct ipsec_proto_info *pr = v2del-> isad_protoid == PROTO_IPSEC_AH ? &dst ->st_ah : &dst -> st_esp; DBG( DBG_CONTROLMORE, DBG_log( "our side spi that needs to be sent: %s SA(0x%08lx)", enum_show( & protocol_names, v2del -> isad_protoid), ( unsigned long) ntohl( pr -> our_spi))); memcpy( spi_buf + (j * v2del -> isad_spisize), (u_char *)&pr->our_spi, v2del->isad_spisize); j++; } else { DBG( DBG_CONTROLMORE, DBG_log( "received delete request for %s SA(0x%08lx) but local state is not found", enum_show( & protocol_names, v2del -> isad_protoid), ( unsigned long) ntohl(( unsigned long) *( ipsec_spi_t *) spi))); } } if ( !j ) { DBG(DBG_CONTROLMORE, DBG_log( "This delete payload does not contain a single spi that has any local state, ignoring")); return STF_IGNORE; } else { DBG(DBG_CONTROLMORE, DBG_log( "No. of SPIs to be sent %d", j); DBG_dump( " Emit SPIs", spi_buf, j * v2del-> isad_spisize)); } zero(&v2del_tmp); if (p->next != NULL) v2del_tmp.isad_np = ISAKMP_NEXT_v2D; else v2del_tmp.isad_np = ISAKMP_NEXT_v2NONE; v2del_tmp.isad_protoid = v2del->isad_protoid; v2del_tmp.isad_spisize = v2del->isad_spisize; v2del_tmp.isad_nrspi = j; /* Emit delete payload header out*/ if (!out_struct(&v2del_tmp, & ikev2_delete_desc, &e_pbs_cipher, &del_pbs)) { libreswan_log( "error initializing hdr for delete payload"); return STF_INTERNAL_ERROR; } /* Emit values of spi to be sent to the peer*/ if (!out_raw(spi_buf, j * v2del-> isad_spisize, &del_pbs, "local spis")) { libreswan_log( "error sending spi values in delete payload"); return STF_INTERNAL_ERROR; } close_output_pbs(&del_pbs); } break; default: /*Unrecongnized protocol */ return STF_IGNORE; } /* this will break from for loop*/ if (v2del->isad_protoid == PROTO_ISAKMP) break; } } /*If there are no payloads or in other words empty payload in request * that means it is check for liveliness, so send an empty payload message * this will end up sending an empty payload */ ikev2_padup_pre_encrypt(md, &e_pbs_cipher); close_output_pbs(&e_pbs_cipher); { unsigned char *authloc = ikev2_authloc(md, &e_pbs); if (authloc == NULL) return STF_INTERNAL_ERROR; close_output_pbs(&e_pbs); close_output_pbs(&md->rbody); close_output_pbs(&reply_stream); ret = ikev2_encrypt_msg(md, md->role, authstart, iv, encstart, authloc, &e_pbs, &e_pbs_cipher); if (ret != STF_OK) return ret; } /* keep it for a retransmit if necessary */ freeanychunk(st->st_tpacket); clonetochunk(st->st_tpacket, reply_stream.start, pbs_offset( &reply_stream), "reply packet for informational exchange"); send_ike_msg(st, __FUNCTION__); } /* Now carry out the actualy task, we can not carry the actual task since * we need to send informational responde using existig SAs */ { if (md->chain[ISAKMP_NEXT_v2D] && st->st_state != STATE_IKESA_DEL) { for (p = md->chain[ISAKMP_NEXT_v2D]; p != NULL; p = p->next) { v2del = &p->payload.v2delete; switch (v2del->isad_protoid) { case PROTO_ISAKMP: { /* My understanding is that delete payload for IKE SA * should be the only payload in the informational * Now delete the IKE SA state and all its child states */ struct state *current_st = st; struct state *next_st = NULL; struct state *first_st = NULL; /* Find the first state in the hash chain*/ while (current_st != (struct state *) NULL) { first_st = current_st; current_st = first_st-> st_hashchain_prev; } current_st = first_st; while (current_st != (struct state *) NULL) { next_st = current_st-> st_hashchain_next; if (current_st-> st_clonedfrom != 0 ) { change_state( current_st, STATE_CHILDSA_DEL); } else { change_state( current_st, STATE_IKESA_DEL); } delete_state(current_st); current_st = next_st; } } break; case PROTO_IPSEC_AH: case PROTO_IPSEC_ESP: { /* pb_stream del_pbs; */ struct ikev2_delete; u_int16_t i; u_char *spi; for (i = 0; i < v2del->isad_nrspi; i++ ) { spi = p->pbs.cur + (i * v2del-> isad_spisize); DBG(DBG_CONTROLMORE, DBG_log( "Now doing actual deletion for request: %s SA(0x%08lx)", enum_show( & protocol_names, v2del -> isad_protoid), ( unsigned long) ntohl(( unsigned long) *( ipsec_spi_t *) spi))); struct state *dst = find_state_ikev2_child_to_delete( st->st_icookie, st->st_rcookie, v2del->isad_protoid, *( ipsec_spi_t *)spi); if (dst != NULL) { struct ipsec_proto_info *pr = v2del-> isad_protoid == PROTO_IPSEC_AH ? &dst ->st_ah : &dst -> st_esp; DBG( DBG_CONTROLMORE, DBG_log( "our side spi that needs to be deleted: %s SA(0x%08lx)", enum_show( & protocol_names, v2del -> isad_protoid), ( unsigned long) ntohl( pr -> our_spi))); /* now delete the state*/ change_state( dst, STATE_CHILDSA_DEL); delete_state( dst); } else { DBG( DBG_CONTROLMORE, DBG_log( "received delete request for %s SA(0x%08lx) but local state is not found", enum_show( & protocol_names, v2del -> isad_protoid), ( unsigned long) ntohl(( unsigned long) *( ipsec_spi_t *) spi))); } } } break; default: /*Unrecongnized protocol */ return STF_IGNORE; } /* this will break from for loop*/ if (v2del->isad_protoid == PROTO_ISAKMP) break; } /* for */ } /* if*/ else { /* empty response to our IKESA delete request*/ if ((md->hdr.isa_flags & ISAKMP_FLAGS_R) && st->st_state == STATE_IKESA_DEL) { /* My understanding is that delete payload for IKE SA * should be the only payload in the informational * Now delete the IKE SA state and all its child states */ struct state *current_st = st; struct state *next_st = NULL; struct state *first_st = NULL; /* Find the first state in the hash chain*/ while (current_st != (struct state *) NULL) { first_st = current_st; current_st = first_st-> st_hashchain_prev; } current_st = first_st; while (current_st != (struct state *) NULL) { next_st = current_st-> st_hashchain_next; if (current_st->st_clonedfrom != 0 ) { change_state( current_st, STATE_CHILDSA_DEL); } else { change_state( current_st, STATE_IKESA_DEL); } delete_state(current_st); current_st = next_st; } /* empty response to our empty INFORMATIONAL * We don't send anything back */ } else if ((md->hdr.isa_flags & ISAKMP_FLAGS_R) && st->st_state != STATE_IKESA_DEL) { DBG(DBG_CONTROLMORE, DBG_log( "Received an INFORMATIONAL response, " "updating liveness, no longer pending.")); st->st_last_liveness = now(); st->st_pend_liveness = FALSE; st->st_msgid_lastrecv = md->msgid_received; } } } } return STF_OK; } stf_status ikev2_send_informational(struct state *st) { struct state *pst = NULL; if (st->st_clonedfrom != SOS_NOBODY) { pst = state_with_serialno(st->st_clonedfrom); if (!pst) { DBG(DBG_CONTROL, DBG_log( "IKE SA does not exist for this child SA - should not happen")); DBG(DBG_CONTROL, DBG_log("INFORMATIONAL exchange can not be sent")); return STF_IGNORE; } } else { pst = st; } { unsigned char *authstart; unsigned char *encstart; unsigned char *iv; int ivsize; struct msg_digest md; struct ikev2_generic e; enum phase1_role role; pb_stream e_pbs, e_pbs_cipher; pb_stream rbody; pb_stream request; u_char buffer[1024]; md.st = st; md.pst = pst; memset(buffer, 0, sizeof(buffer)); init_pbs(&request, buffer, sizeof(buffer), "informational exchange request packet"); authstart = request.cur; /* HDR out */ { struct isakmp_hdr r_hdr; zero(&r_hdr); r_hdr.isa_version = build_ike_version(); memcpy(r_hdr.isa_rcookie, pst->st_rcookie, COOKIE_SIZE); memcpy(r_hdr.isa_icookie, pst->st_icookie, COOKIE_SIZE); r_hdr.isa_xchg = ISAKMP_v2_INFORMATIONAL; r_hdr.isa_np = ISAKMP_NEXT_v2E; if (pst->st_state == STATE_PARENT_I2 || pst->st_state == STATE_PARENT_I3) { r_hdr.isa_flags |= ISAKMP_FLAGS_I; role = INITIATOR; r_hdr.isa_msgid = htonl(pst->st_msgid_nextuse); } else { role = RESPONDER; r_hdr.isa_msgid = htonl( pst->st_msgid_lastrecv + 1); } if (!out_struct(&r_hdr, &isakmp_hdr_desc, &request, &rbody)) { libreswan_log( "error initializing hdr for informational message"); return STF_FATAL; } } /* HDR done*/ /* insert an Encryption payload header */ e.isag_np = ISAKMP_NEXT_v2NONE; e.isag_critical = ISAKMP_PAYLOAD_NONCRITICAL; if (!out_struct(&e, &ikev2_e_desc, &rbody, &e_pbs)) return STF_FATAL; /* IV */ iv = e_pbs.cur; ivsize = pst->st_oakley.encrypter->iv_size; if (!out_zero(ivsize, &e_pbs, "iv")) return STF_FATAL; get_rnd_bytes(iv, ivsize); /* note where cleartext starts */ init_pbs(&e_pbs_cipher, e_pbs.cur, e_pbs.roof - e_pbs.cur, "cleartext"); e_pbs_cipher.container = &e_pbs; e_pbs_cipher.desc = NULL; e_pbs_cipher.cur = e_pbs.cur; encstart = e_pbs_cipher.cur; /* This is an empty informational exchange (A.K.A liveness check) */ ikev2_padup_pre_encrypt(&md, &e_pbs_cipher); close_output_pbs(&e_pbs_cipher); { stf_status ret; unsigned char *authloc = ikev2_authloc(&md, &e_pbs); if (!authloc) return STF_FATAL; close_output_pbs(&e_pbs); close_output_pbs(&rbody); close_output_pbs(&request); ret = ikev2_encrypt_msg(&md, role, authstart, iv, encstart, authloc, &e_pbs, &e_pbs_cipher); if (ret != STF_OK) return STF_FATAL; } /* keep it for a retransmit if necessary */ freeanychunk(pst->st_tpacket); clonetochunk(pst->st_tpacket, request.start, pbs_offset(&request), "reply packet for informational exchange"); pst->st_pend_liveness = TRUE; /* we should only do this when dpd/liveness is active? */ send_ike_msg(pst, __FUNCTION__); ikev2_update_counters(&md); } return STF_OK; } /* * *************************************************************** * DELETE_OUT ***** *************************************************************** * */ void ikev2_delete_out(struct state *st) { struct state *pst = NULL; if (st->st_clonedfrom != 0) { /*child SA*/ pst = state_with_serialno(st->st_clonedfrom); if (!pst) { DBG(DBG_CONTROL, DBG_log("IKE SA does not exist for this child SA")); DBG(DBG_CONTROL, DBG_log( "INFORMATIONAL exchange can not be sent, deleting state")); goto end; } } else { /* Parent SA*/ pst = st; } { unsigned char *authstart; pb_stream e_pbs, e_pbs_cipher; pb_stream rbody; struct ikev2_generic e; unsigned char *iv; int ivsize; unsigned char *encstart; struct msg_digest md; enum phase1_role role; md.st = st; md.pst = pst; /* beginning of data going out */ authstart = reply_stream.cur; /* make sure HDR is at start of a clean buffer */ zero(reply_buffer); init_pbs(&reply_stream, reply_buffer, sizeof(reply_buffer), "information exchange request packet"); /* HDR out */ { struct isakmp_hdr r_hdr; zero(&r_hdr); /* default to 0 */ /* AAA should we copy from MD? */ r_hdr.isa_version = build_ike_version(); memcpy(r_hdr.isa_rcookie, pst->st_rcookie, COOKIE_SIZE); memcpy(r_hdr.isa_icookie, pst->st_icookie, COOKIE_SIZE); r_hdr.isa_xchg = ISAKMP_v2_INFORMATIONAL; r_hdr.isa_np = ISAKMP_NEXT_v2E; r_hdr.isa_msgid = htonl(pst->st_msgid_nextuse); /*set initiator bit if we are initiator*/ if (pst->st_state == STATE_PARENT_I2 || pst->st_state == STATE_PARENT_I3) { r_hdr.isa_flags |= ISAKMP_FLAGS_I; role = INITIATOR; } else { role = RESPONDER; } /* r_hdr.isa_flags |= ISAKMP_FLAGS_R; */ if (!out_struct(&r_hdr, &isakmp_hdr_desc, &reply_stream, &rbody)) { libreswan_log( "error initializing hdr for informational message"); goto end; } } /*HDR Done*/ /* insert an Encryption payload header */ e.isag_np = ISAKMP_NEXT_v2D; e.isag_critical = ISAKMP_PAYLOAD_NONCRITICAL; if (!out_struct(&e, &ikev2_e_desc, &rbody, &e_pbs)) goto end; /* insert IV */ iv = e_pbs.cur; ivsize = pst->st_oakley.encrypter->iv_size; if (!out_zero(ivsize, &e_pbs, "iv")) goto end; get_rnd_bytes(iv, ivsize); /* note where cleartext starts */ init_pbs(&e_pbs_cipher, e_pbs.cur, e_pbs.roof - e_pbs.cur, "cleartext"); e_pbs_cipher.container = &e_pbs; e_pbs_cipher.desc = NULL; e_pbs_cipher.cur = e_pbs.cur; encstart = e_pbs_cipher.cur; { pb_stream del_pbs; struct ikev2_delete v2del_tmp; /* * u_int16_t i, j=0; * u_char *spi; * char spi_buf[1024]; */ zero(&v2del_tmp); v2del_tmp.isad_np = ISAKMP_NEXT_v2NONE; if (st->st_clonedfrom != 0 ) { v2del_tmp.isad_protoid = PROTO_IPSEC_ESP; v2del_tmp.isad_spisize = sizeof(ipsec_spi_t); v2del_tmp.isad_nrspi = 1; } else { v2del_tmp.isad_protoid = PROTO_ISAKMP; v2del_tmp.isad_spisize = 0; v2del_tmp.isad_nrspi = 0; } /* Emit delete payload header out*/ if (!out_struct(&v2del_tmp, &ikev2_delete_desc, &e_pbs_cipher, &del_pbs)) { libreswan_log( "error initializing hdr for delete payload"); goto end; } /* Emit values of spi to be sent to the peer*/ if (st->st_clonedfrom != 0) { if (!out_raw( (u_char *)&st->st_esp.our_spi, sizeof(ipsec_spi_t), &del_pbs, "local spis")) { libreswan_log( "error sending spi values in delete payload"); goto end; } } close_output_pbs(&del_pbs); } ikev2_padup_pre_encrypt(&md, &e_pbs_cipher); close_output_pbs(&e_pbs_cipher); { stf_status ret; unsigned char *authloc = ikev2_authloc(&md, &e_pbs); if (authloc == NULL) goto end; close_output_pbs(&e_pbs); close_output_pbs(&rbody); close_output_pbs(&reply_stream); ret = ikev2_encrypt_msg(&md, role, authstart, iv, encstart, authloc, &e_pbs, &e_pbs_cipher); if (ret != STF_OK) goto end; } /* keep it for a retransmit if necessary */ freeanychunk(pst->st_tpacket); clonetochunk(pst->st_tpacket, reply_stream.start, pbs_offset(&reply_stream), "request packet for informational exchange"); send_ike_msg(pst, __FUNCTION__); /* update state */ ikev2_update_counters(&md); } /* If everything is fine, and we sent packet, goto real_end*/ goto real_end; end: /* If some error occurs above that prevents us sending a request packet*/ /* delete the states right now*/ if (st->st_clonedfrom != SOS_NOBODY) { change_state(st, STATE_CHILDSA_DEL); delete_state(st); } else { struct state *current_st = pst; struct state *next_st = NULL; struct state *first_st = NULL; /* Find the first state in the hash chain*/ while (current_st != (struct state *) NULL) { first_st = current_st; current_st = first_st->st_hashchain_prev; } current_st = first_st; while (current_st != (struct state *) NULL) { next_st = current_st->st_hashchain_next; if (current_st->st_clonedfrom != 0 ) change_state(current_st, STATE_CHILDSA_DEL); else change_state(current_st, STATE_IKESA_DEL); delete_state(current_st); current_st = next_st; } } real_end:; } /* * Determine the IKE version we will use for the IKE packet * Normally, this is "2.0", but in the future we might need to * change that. Version used is the minimum 2.x version both * sides support. So if we support 2.1, and they support 2.0, * we should sent 2.0 (not implemented until we hit 2.1 ourselves) * We also have some impair functions that modify the major/minor * version on purpose - for testing * * rcv_version: the received IKE version, 0 if we don't know * * top 4 bits are major version, lower 4 bits are minor version */ static int build_ike_version() { return ((IKEv2_MAJOR_VERSION + (DBGP(IMPAIR_MAJOR_VERSION_BUMP) ? 1 : 0)) << ISA_MAJ_SHIFT) | (IKEv2_MINOR_VERSION + (DBGP(IMPAIR_MINOR_VERSION_BUMP) ? 1 : 0)); }
./CrossVul/dataset_final_sorted/CWE-20/c/good_5849_0
crossvul-cpp_data_bad_5544_2
/* * Back-end of the driver for virtual network devices. This portion of the * driver exports a 'unified' network-device interface that can be accessed * by any operating system that implements a compatible front end. A * reference front-end implementation can be found in: * drivers/net/xen-netfront.c * * Copyright (c) 2002-2005, K A Fraser * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version 2 * as published by the Free Software Foundation; or, when distributed * separately from the Linux kernel or incorporated into other * software packages, subject to the following license: * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this source file (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, modify, * merge, publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #include "common.h" #include <linux/kthread.h> #include <linux/if_vlan.h> #include <linux/udp.h> #include <net/tcp.h> #include <xen/xen.h> #include <xen/events.h> #include <xen/interface/memory.h> #include <asm/xen/hypercall.h> #include <asm/xen/page.h> struct pending_tx_info { struct xen_netif_tx_request req; struct xenvif *vif; }; typedef unsigned int pending_ring_idx_t; struct netbk_rx_meta { int id; int size; int gso_size; }; #define MAX_PENDING_REQS 256 /* Discriminate from any valid pending_idx value. */ #define INVALID_PENDING_IDX 0xFFFF #define MAX_BUFFER_OFFSET PAGE_SIZE /* extra field used in struct page */ union page_ext { struct { #if BITS_PER_LONG < 64 #define IDX_WIDTH 8 #define GROUP_WIDTH (BITS_PER_LONG - IDX_WIDTH) unsigned int group:GROUP_WIDTH; unsigned int idx:IDX_WIDTH; #else unsigned int group, idx; #endif } e; void *mapping; }; struct xen_netbk { wait_queue_head_t wq; struct task_struct *task; struct sk_buff_head rx_queue; struct sk_buff_head tx_queue; struct timer_list net_timer; struct page *mmap_pages[MAX_PENDING_REQS]; pending_ring_idx_t pending_prod; pending_ring_idx_t pending_cons; struct list_head net_schedule_list; /* Protect the net_schedule_list in netif. */ spinlock_t net_schedule_list_lock; atomic_t netfront_count; struct pending_tx_info pending_tx_info[MAX_PENDING_REQS]; struct gnttab_copy tx_copy_ops[MAX_PENDING_REQS]; u16 pending_ring[MAX_PENDING_REQS]; /* * Given MAX_BUFFER_OFFSET of 4096 the worst case is that each * head/fragment page uses 2 copy operations because it * straddles two buffers in the frontend. */ struct gnttab_copy grant_copy_op[2*XEN_NETIF_RX_RING_SIZE]; struct netbk_rx_meta meta[2*XEN_NETIF_RX_RING_SIZE]; }; static struct xen_netbk *xen_netbk; static int xen_netbk_group_nr; void xen_netbk_add_xenvif(struct xenvif *vif) { int i; int min_netfront_count; int min_group = 0; struct xen_netbk *netbk; min_netfront_count = atomic_read(&xen_netbk[0].netfront_count); for (i = 0; i < xen_netbk_group_nr; i++) { int netfront_count = atomic_read(&xen_netbk[i].netfront_count); if (netfront_count < min_netfront_count) { min_group = i; min_netfront_count = netfront_count; } } netbk = &xen_netbk[min_group]; vif->netbk = netbk; atomic_inc(&netbk->netfront_count); } void xen_netbk_remove_xenvif(struct xenvif *vif) { struct xen_netbk *netbk = vif->netbk; vif->netbk = NULL; atomic_dec(&netbk->netfront_count); } static void xen_netbk_idx_release(struct xen_netbk *netbk, u16 pending_idx); static void make_tx_response(struct xenvif *vif, struct xen_netif_tx_request *txp, s8 st); static struct xen_netif_rx_response *make_rx_response(struct xenvif *vif, u16 id, s8 st, u16 offset, u16 size, u16 flags); static inline unsigned long idx_to_pfn(struct xen_netbk *netbk, u16 idx) { return page_to_pfn(netbk->mmap_pages[idx]); } static inline unsigned long idx_to_kaddr(struct xen_netbk *netbk, u16 idx) { return (unsigned long)pfn_to_kaddr(idx_to_pfn(netbk, idx)); } /* extra field used in struct page */ static inline void set_page_ext(struct page *pg, struct xen_netbk *netbk, unsigned int idx) { unsigned int group = netbk - xen_netbk; union page_ext ext = { .e = { .group = group + 1, .idx = idx } }; BUILD_BUG_ON(sizeof(ext) > sizeof(ext.mapping)); pg->mapping = ext.mapping; } static int get_page_ext(struct page *pg, unsigned int *pgroup, unsigned int *pidx) { union page_ext ext = { .mapping = pg->mapping }; struct xen_netbk *netbk; unsigned int group, idx; group = ext.e.group - 1; if (group < 0 || group >= xen_netbk_group_nr) return 0; netbk = &xen_netbk[group]; idx = ext.e.idx; if ((idx < 0) || (idx >= MAX_PENDING_REQS)) return 0; if (netbk->mmap_pages[idx] != pg) return 0; *pgroup = group; *pidx = idx; return 1; } /* * This is the amount of packet we copy rather than map, so that the * guest can't fiddle with the contents of the headers while we do * packet processing on them (netfilter, routing, etc). */ #define PKT_PROT_LEN (ETH_HLEN + \ VLAN_HLEN + \ sizeof(struct iphdr) + MAX_IPOPTLEN + \ sizeof(struct tcphdr) + MAX_TCP_OPTION_SPACE) static u16 frag_get_pending_idx(skb_frag_t *frag) { return (u16)frag->page_offset; } static void frag_set_pending_idx(skb_frag_t *frag, u16 pending_idx) { frag->page_offset = pending_idx; } static inline pending_ring_idx_t pending_index(unsigned i) { return i & (MAX_PENDING_REQS-1); } static inline pending_ring_idx_t nr_pending_reqs(struct xen_netbk *netbk) { return MAX_PENDING_REQS - netbk->pending_prod + netbk->pending_cons; } static void xen_netbk_kick_thread(struct xen_netbk *netbk) { wake_up(&netbk->wq); } static int max_required_rx_slots(struct xenvif *vif) { int max = DIV_ROUND_UP(vif->dev->mtu, PAGE_SIZE); if (vif->can_sg || vif->gso || vif->gso_prefix) max += MAX_SKB_FRAGS + 1; /* extra_info + frags */ return max; } int xen_netbk_rx_ring_full(struct xenvif *vif) { RING_IDX peek = vif->rx_req_cons_peek; RING_IDX needed = max_required_rx_slots(vif); return ((vif->rx.sring->req_prod - peek) < needed) || ((vif->rx.rsp_prod_pvt + XEN_NETIF_RX_RING_SIZE - peek) < needed); } int xen_netbk_must_stop_queue(struct xenvif *vif) { if (!xen_netbk_rx_ring_full(vif)) return 0; vif->rx.sring->req_event = vif->rx_req_cons_peek + max_required_rx_slots(vif); mb(); /* request notification /then/ check the queue */ return xen_netbk_rx_ring_full(vif); } /* * Returns true if we should start a new receive buffer instead of * adding 'size' bytes to a buffer which currently contains 'offset' * bytes. */ static bool start_new_rx_buffer(int offset, unsigned long size, int head) { /* simple case: we have completely filled the current buffer. */ if (offset == MAX_BUFFER_OFFSET) return true; /* * complex case: start a fresh buffer if the current frag * would overflow the current buffer but only if: * (i) this frag would fit completely in the next buffer * and (ii) there is already some data in the current buffer * and (iii) this is not the head buffer. * * Where: * - (i) stops us splitting a frag into two copies * unless the frag is too large for a single buffer. * - (ii) stops us from leaving a buffer pointlessly empty. * - (iii) stops us leaving the first buffer * empty. Strictly speaking this is already covered * by (ii) but is explicitly checked because * netfront relies on the first buffer being * non-empty and can crash otherwise. * * This means we will effectively linearise small * frags but do not needlessly split large buffers * into multiple copies tend to give large frags their * own buffers as before. */ if ((offset + size > MAX_BUFFER_OFFSET) && (size <= MAX_BUFFER_OFFSET) && offset && !head) return true; return false; } /* * Figure out how many ring slots we're going to need to send @skb to * the guest. This function is essentially a dry run of * netbk_gop_frag_copy. */ unsigned int xen_netbk_count_skb_slots(struct xenvif *vif, struct sk_buff *skb) { unsigned int count; int i, copy_off; count = DIV_ROUND_UP(skb_headlen(skb), PAGE_SIZE); copy_off = skb_headlen(skb) % PAGE_SIZE; if (skb_shinfo(skb)->gso_size) count++; for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) { unsigned long size = skb_frag_size(&skb_shinfo(skb)->frags[i]); unsigned long offset = skb_shinfo(skb)->frags[i].page_offset; unsigned long bytes; offset &= ~PAGE_MASK; while (size > 0) { BUG_ON(offset >= PAGE_SIZE); BUG_ON(copy_off > MAX_BUFFER_OFFSET); bytes = PAGE_SIZE - offset; if (bytes > size) bytes = size; if (start_new_rx_buffer(copy_off, bytes, 0)) { count++; copy_off = 0; } if (copy_off + bytes > MAX_BUFFER_OFFSET) bytes = MAX_BUFFER_OFFSET - copy_off; copy_off += bytes; offset += bytes; size -= bytes; if (offset == PAGE_SIZE) offset = 0; } } return count; } struct netrx_pending_operations { unsigned copy_prod, copy_cons; unsigned meta_prod, meta_cons; struct gnttab_copy *copy; struct netbk_rx_meta *meta; int copy_off; grant_ref_t copy_gref; }; static struct netbk_rx_meta *get_next_rx_buffer(struct xenvif *vif, struct netrx_pending_operations *npo) { struct netbk_rx_meta *meta; struct xen_netif_rx_request *req; req = RING_GET_REQUEST(&vif->rx, vif->rx.req_cons++); meta = npo->meta + npo->meta_prod++; meta->gso_size = 0; meta->size = 0; meta->id = req->id; npo->copy_off = 0; npo->copy_gref = req->gref; return meta; } /* * Set up the grant operations for this fragment. If it's a flipping * interface, we also set up the unmap request from here. */ static void netbk_gop_frag_copy(struct xenvif *vif, struct sk_buff *skb, struct netrx_pending_operations *npo, struct page *page, unsigned long size, unsigned long offset, int *head) { struct gnttab_copy *copy_gop; struct netbk_rx_meta *meta; /* * These variables are used iff get_page_ext returns true, * in which case they are guaranteed to be initialized. */ unsigned int uninitialized_var(group), uninitialized_var(idx); int foreign = get_page_ext(page, &group, &idx); unsigned long bytes; /* Data must not cross a page boundary. */ BUG_ON(size + offset > PAGE_SIZE<<compound_order(page)); meta = npo->meta + npo->meta_prod - 1; /* Skip unused frames from start of page */ page += offset >> PAGE_SHIFT; offset &= ~PAGE_MASK; while (size > 0) { BUG_ON(offset >= PAGE_SIZE); BUG_ON(npo->copy_off > MAX_BUFFER_OFFSET); bytes = PAGE_SIZE - offset; if (bytes > size) bytes = size; if (start_new_rx_buffer(npo->copy_off, bytes, *head)) { /* * Netfront requires there to be some data in the head * buffer. */ BUG_ON(*head); meta = get_next_rx_buffer(vif, npo); } if (npo->copy_off + bytes > MAX_BUFFER_OFFSET) bytes = MAX_BUFFER_OFFSET - npo->copy_off; copy_gop = npo->copy + npo->copy_prod++; copy_gop->flags = GNTCOPY_dest_gref; if (foreign) { struct xen_netbk *netbk = &xen_netbk[group]; struct pending_tx_info *src_pend; src_pend = &netbk->pending_tx_info[idx]; copy_gop->source.domid = src_pend->vif->domid; copy_gop->source.u.ref = src_pend->req.gref; copy_gop->flags |= GNTCOPY_source_gref; } else { void *vaddr = page_address(page); copy_gop->source.domid = DOMID_SELF; copy_gop->source.u.gmfn = virt_to_mfn(vaddr); } copy_gop->source.offset = offset; copy_gop->dest.domid = vif->domid; copy_gop->dest.offset = npo->copy_off; copy_gop->dest.u.ref = npo->copy_gref; copy_gop->len = bytes; npo->copy_off += bytes; meta->size += bytes; offset += bytes; size -= bytes; /* Next frame */ if (offset == PAGE_SIZE && size) { BUG_ON(!PageCompound(page)); page++; offset = 0; } /* Leave a gap for the GSO descriptor. */ if (*head && skb_shinfo(skb)->gso_size && !vif->gso_prefix) vif->rx.req_cons++; *head = 0; /* There must be something in this buffer now. */ } } /* * Prepare an SKB to be transmitted to the frontend. * * This function is responsible for allocating grant operations, meta * structures, etc. * * It returns the number of meta structures consumed. The number of * ring slots used is always equal to the number of meta slots used * plus the number of GSO descriptors used. Currently, we use either * zero GSO descriptors (for non-GSO packets) or one descriptor (for * frontend-side LRO). */ static int netbk_gop_skb(struct sk_buff *skb, struct netrx_pending_operations *npo) { struct xenvif *vif = netdev_priv(skb->dev); int nr_frags = skb_shinfo(skb)->nr_frags; int i; struct xen_netif_rx_request *req; struct netbk_rx_meta *meta; unsigned char *data; int head = 1; int old_meta_prod; old_meta_prod = npo->meta_prod; /* Set up a GSO prefix descriptor, if necessary */ if (skb_shinfo(skb)->gso_size && vif->gso_prefix) { req = RING_GET_REQUEST(&vif->rx, vif->rx.req_cons++); meta = npo->meta + npo->meta_prod++; meta->gso_size = skb_shinfo(skb)->gso_size; meta->size = 0; meta->id = req->id; } req = RING_GET_REQUEST(&vif->rx, vif->rx.req_cons++); meta = npo->meta + npo->meta_prod++; if (!vif->gso_prefix) meta->gso_size = skb_shinfo(skb)->gso_size; else meta->gso_size = 0; meta->size = 0; meta->id = req->id; npo->copy_off = 0; npo->copy_gref = req->gref; data = skb->data; while (data < skb_tail_pointer(skb)) { unsigned int offset = offset_in_page(data); unsigned int len = PAGE_SIZE - offset; if (data + len > skb_tail_pointer(skb)) len = skb_tail_pointer(skb) - data; netbk_gop_frag_copy(vif, skb, npo, virt_to_page(data), len, offset, &head); data += len; } for (i = 0; i < nr_frags; i++) { netbk_gop_frag_copy(vif, skb, npo, skb_frag_page(&skb_shinfo(skb)->frags[i]), skb_frag_size(&skb_shinfo(skb)->frags[i]), skb_shinfo(skb)->frags[i].page_offset, &head); } return npo->meta_prod - old_meta_prod; } /* * This is a twin to netbk_gop_skb. Assume that netbk_gop_skb was * used to set up the operations on the top of * netrx_pending_operations, which have since been done. Check that * they didn't give any errors and advance over them. */ static int netbk_check_gop(struct xenvif *vif, int nr_meta_slots, struct netrx_pending_operations *npo) { struct gnttab_copy *copy_op; int status = XEN_NETIF_RSP_OKAY; int i; for (i = 0; i < nr_meta_slots; i++) { copy_op = npo->copy + npo->copy_cons++; if (copy_op->status != GNTST_okay) { netdev_dbg(vif->dev, "Bad status %d from copy to DOM%d.\n", copy_op->status, vif->domid); status = XEN_NETIF_RSP_ERROR; } } return status; } static void netbk_add_frag_responses(struct xenvif *vif, int status, struct netbk_rx_meta *meta, int nr_meta_slots) { int i; unsigned long offset; /* No fragments used */ if (nr_meta_slots <= 1) return; nr_meta_slots--; for (i = 0; i < nr_meta_slots; i++) { int flags; if (i == nr_meta_slots - 1) flags = 0; else flags = XEN_NETRXF_more_data; offset = 0; make_rx_response(vif, meta[i].id, status, offset, meta[i].size, flags); } } struct skb_cb_overlay { int meta_slots_used; }; static void xen_netbk_rx_action(struct xen_netbk *netbk) { struct xenvif *vif = NULL, *tmp; s8 status; u16 irq, flags; struct xen_netif_rx_response *resp; struct sk_buff_head rxq; struct sk_buff *skb; LIST_HEAD(notify); int ret; int nr_frags; int count; unsigned long offset; struct skb_cb_overlay *sco; struct netrx_pending_operations npo = { .copy = netbk->grant_copy_op, .meta = netbk->meta, }; skb_queue_head_init(&rxq); count = 0; while ((skb = skb_dequeue(&netbk->rx_queue)) != NULL) { vif = netdev_priv(skb->dev); nr_frags = skb_shinfo(skb)->nr_frags; sco = (struct skb_cb_overlay *)skb->cb; sco->meta_slots_used = netbk_gop_skb(skb, &npo); count += nr_frags + 1; __skb_queue_tail(&rxq, skb); /* Filled the batch queue? */ if (count + MAX_SKB_FRAGS >= XEN_NETIF_RX_RING_SIZE) break; } BUG_ON(npo.meta_prod > ARRAY_SIZE(netbk->meta)); if (!npo.copy_prod) return; BUG_ON(npo.copy_prod > ARRAY_SIZE(netbk->grant_copy_op)); gnttab_batch_copy(netbk->grant_copy_op, npo.copy_prod); while ((skb = __skb_dequeue(&rxq)) != NULL) { sco = (struct skb_cb_overlay *)skb->cb; vif = netdev_priv(skb->dev); if (netbk->meta[npo.meta_cons].gso_size && vif->gso_prefix) { resp = RING_GET_RESPONSE(&vif->rx, vif->rx.rsp_prod_pvt++); resp->flags = XEN_NETRXF_gso_prefix | XEN_NETRXF_more_data; resp->offset = netbk->meta[npo.meta_cons].gso_size; resp->id = netbk->meta[npo.meta_cons].id; resp->status = sco->meta_slots_used; npo.meta_cons++; sco->meta_slots_used--; } vif->dev->stats.tx_bytes += skb->len; vif->dev->stats.tx_packets++; status = netbk_check_gop(vif, sco->meta_slots_used, &npo); if (sco->meta_slots_used == 1) flags = 0; else flags = XEN_NETRXF_more_data; if (skb->ip_summed == CHECKSUM_PARTIAL) /* local packet? */ flags |= XEN_NETRXF_csum_blank | XEN_NETRXF_data_validated; else if (skb->ip_summed == CHECKSUM_UNNECESSARY) /* remote but checksummed. */ flags |= XEN_NETRXF_data_validated; offset = 0; resp = make_rx_response(vif, netbk->meta[npo.meta_cons].id, status, offset, netbk->meta[npo.meta_cons].size, flags); if (netbk->meta[npo.meta_cons].gso_size && !vif->gso_prefix) { struct xen_netif_extra_info *gso = (struct xen_netif_extra_info *) RING_GET_RESPONSE(&vif->rx, vif->rx.rsp_prod_pvt++); resp->flags |= XEN_NETRXF_extra_info; gso->u.gso.size = netbk->meta[npo.meta_cons].gso_size; gso->u.gso.type = XEN_NETIF_GSO_TYPE_TCPV4; gso->u.gso.pad = 0; gso->u.gso.features = 0; gso->type = XEN_NETIF_EXTRA_TYPE_GSO; gso->flags = 0; } netbk_add_frag_responses(vif, status, netbk->meta + npo.meta_cons + 1, sco->meta_slots_used); RING_PUSH_RESPONSES_AND_CHECK_NOTIFY(&vif->rx, ret); irq = vif->irq; if (ret && list_empty(&vif->notify_list)) list_add_tail(&vif->notify_list, &notify); xenvif_notify_tx_completion(vif); xenvif_put(vif); npo.meta_cons += sco->meta_slots_used; dev_kfree_skb(skb); } list_for_each_entry_safe(vif, tmp, &notify, notify_list) { notify_remote_via_irq(vif->irq); list_del_init(&vif->notify_list); } /* More work to do? */ if (!skb_queue_empty(&netbk->rx_queue) && !timer_pending(&netbk->net_timer)) xen_netbk_kick_thread(netbk); } void xen_netbk_queue_tx_skb(struct xenvif *vif, struct sk_buff *skb) { struct xen_netbk *netbk = vif->netbk; skb_queue_tail(&netbk->rx_queue, skb); xen_netbk_kick_thread(netbk); } static void xen_netbk_alarm(unsigned long data) { struct xen_netbk *netbk = (struct xen_netbk *)data; xen_netbk_kick_thread(netbk); } static int __on_net_schedule_list(struct xenvif *vif) { return !list_empty(&vif->schedule_list); } /* Must be called with net_schedule_list_lock held */ static void remove_from_net_schedule_list(struct xenvif *vif) { if (likely(__on_net_schedule_list(vif))) { list_del_init(&vif->schedule_list); xenvif_put(vif); } } static struct xenvif *poll_net_schedule_list(struct xen_netbk *netbk) { struct xenvif *vif = NULL; spin_lock_irq(&netbk->net_schedule_list_lock); if (list_empty(&netbk->net_schedule_list)) goto out; vif = list_first_entry(&netbk->net_schedule_list, struct xenvif, schedule_list); if (!vif) goto out; xenvif_get(vif); remove_from_net_schedule_list(vif); out: spin_unlock_irq(&netbk->net_schedule_list_lock); return vif; } void xen_netbk_schedule_xenvif(struct xenvif *vif) { unsigned long flags; struct xen_netbk *netbk = vif->netbk; if (__on_net_schedule_list(vif)) goto kick; spin_lock_irqsave(&netbk->net_schedule_list_lock, flags); if (!__on_net_schedule_list(vif) && likely(xenvif_schedulable(vif))) { list_add_tail(&vif->schedule_list, &netbk->net_schedule_list); xenvif_get(vif); } spin_unlock_irqrestore(&netbk->net_schedule_list_lock, flags); kick: smp_mb(); if ((nr_pending_reqs(netbk) < (MAX_PENDING_REQS/2)) && !list_empty(&netbk->net_schedule_list)) xen_netbk_kick_thread(netbk); } void xen_netbk_deschedule_xenvif(struct xenvif *vif) { struct xen_netbk *netbk = vif->netbk; spin_lock_irq(&netbk->net_schedule_list_lock); remove_from_net_schedule_list(vif); spin_unlock_irq(&netbk->net_schedule_list_lock); } void xen_netbk_check_rx_xenvif(struct xenvif *vif) { int more_to_do; RING_FINAL_CHECK_FOR_REQUESTS(&vif->tx, more_to_do); if (more_to_do) xen_netbk_schedule_xenvif(vif); } static void tx_add_credit(struct xenvif *vif) { unsigned long max_burst, max_credit; /* * Allow a burst big enough to transmit a jumbo packet of up to 128kB. * Otherwise the interface can seize up due to insufficient credit. */ max_burst = RING_GET_REQUEST(&vif->tx, vif->tx.req_cons)->size; max_burst = min(max_burst, 131072UL); max_burst = max(max_burst, vif->credit_bytes); /* Take care that adding a new chunk of credit doesn't wrap to zero. */ max_credit = vif->remaining_credit + vif->credit_bytes; if (max_credit < vif->remaining_credit) max_credit = ULONG_MAX; /* wrapped: clamp to ULONG_MAX */ vif->remaining_credit = min(max_credit, max_burst); } static void tx_credit_callback(unsigned long data) { struct xenvif *vif = (struct xenvif *)data; tx_add_credit(vif); xen_netbk_check_rx_xenvif(vif); } static void netbk_tx_err(struct xenvif *vif, struct xen_netif_tx_request *txp, RING_IDX end) { RING_IDX cons = vif->tx.req_cons; do { make_tx_response(vif, txp, XEN_NETIF_RSP_ERROR); if (cons >= end) break; txp = RING_GET_REQUEST(&vif->tx, cons++); } while (1); vif->tx.req_cons = cons; xen_netbk_check_rx_xenvif(vif); xenvif_put(vif); } static int netbk_count_requests(struct xenvif *vif, struct xen_netif_tx_request *first, struct xen_netif_tx_request *txp, int work_to_do) { RING_IDX cons = vif->tx.req_cons; int frags = 0; if (!(first->flags & XEN_NETTXF_more_data)) return 0; do { if (frags >= work_to_do) { netdev_dbg(vif->dev, "Need more frags\n"); return -frags; } if (unlikely(frags >= MAX_SKB_FRAGS)) { netdev_dbg(vif->dev, "Too many frags\n"); return -frags; } memcpy(txp, RING_GET_REQUEST(&vif->tx, cons + frags), sizeof(*txp)); if (txp->size > first->size) { netdev_dbg(vif->dev, "Frags galore\n"); return -frags; } first->size -= txp->size; frags++; if (unlikely((txp->offset + txp->size) > PAGE_SIZE)) { netdev_dbg(vif->dev, "txp->offset: %x, size: %u\n", txp->offset, txp->size); return -frags; } } while ((txp++)->flags & XEN_NETTXF_more_data); return frags; } static struct page *xen_netbk_alloc_page(struct xen_netbk *netbk, struct sk_buff *skb, u16 pending_idx) { struct page *page; page = alloc_page(GFP_KERNEL|__GFP_COLD); if (!page) return NULL; set_page_ext(page, netbk, pending_idx); netbk->mmap_pages[pending_idx] = page; return page; } static struct gnttab_copy *xen_netbk_get_requests(struct xen_netbk *netbk, struct xenvif *vif, struct sk_buff *skb, struct xen_netif_tx_request *txp, struct gnttab_copy *gop) { struct skb_shared_info *shinfo = skb_shinfo(skb); skb_frag_t *frags = shinfo->frags; u16 pending_idx = *((u16 *)skb->data); int i, start; /* Skip first skb fragment if it is on same page as header fragment. */ start = (frag_get_pending_idx(&shinfo->frags[0]) == pending_idx); for (i = start; i < shinfo->nr_frags; i++, txp++) { struct page *page; pending_ring_idx_t index; struct pending_tx_info *pending_tx_info = netbk->pending_tx_info; index = pending_index(netbk->pending_cons++); pending_idx = netbk->pending_ring[index]; page = xen_netbk_alloc_page(netbk, skb, pending_idx); if (!page) return NULL; gop->source.u.ref = txp->gref; gop->source.domid = vif->domid; gop->source.offset = txp->offset; gop->dest.u.gmfn = virt_to_mfn(page_address(page)); gop->dest.domid = DOMID_SELF; gop->dest.offset = txp->offset; gop->len = txp->size; gop->flags = GNTCOPY_source_gref; gop++; memcpy(&pending_tx_info[pending_idx].req, txp, sizeof(*txp)); xenvif_get(vif); pending_tx_info[pending_idx].vif = vif; frag_set_pending_idx(&frags[i], pending_idx); } return gop; } static int xen_netbk_tx_check_gop(struct xen_netbk *netbk, struct sk_buff *skb, struct gnttab_copy **gopp) { struct gnttab_copy *gop = *gopp; u16 pending_idx = *((u16 *)skb->data); struct pending_tx_info *pending_tx_info = netbk->pending_tx_info; struct xenvif *vif = pending_tx_info[pending_idx].vif; struct xen_netif_tx_request *txp; struct skb_shared_info *shinfo = skb_shinfo(skb); int nr_frags = shinfo->nr_frags; int i, err, start; /* Check status of header. */ err = gop->status; if (unlikely(err)) { pending_ring_idx_t index; index = pending_index(netbk->pending_prod++); txp = &pending_tx_info[pending_idx].req; make_tx_response(vif, txp, XEN_NETIF_RSP_ERROR); netbk->pending_ring[index] = pending_idx; xenvif_put(vif); } /* Skip first skb fragment if it is on same page as header fragment. */ start = (frag_get_pending_idx(&shinfo->frags[0]) == pending_idx); for (i = start; i < nr_frags; i++) { int j, newerr; pending_ring_idx_t index; pending_idx = frag_get_pending_idx(&shinfo->frags[i]); /* Check error status: if okay then remember grant handle. */ newerr = (++gop)->status; if (likely(!newerr)) { /* Had a previous error? Invalidate this fragment. */ if (unlikely(err)) xen_netbk_idx_release(netbk, pending_idx); continue; } /* Error on this fragment: respond to client with an error. */ txp = &netbk->pending_tx_info[pending_idx].req; make_tx_response(vif, txp, XEN_NETIF_RSP_ERROR); index = pending_index(netbk->pending_prod++); netbk->pending_ring[index] = pending_idx; xenvif_put(vif); /* Not the first error? Preceding frags already invalidated. */ if (err) continue; /* First error: invalidate header and preceding fragments. */ pending_idx = *((u16 *)skb->data); xen_netbk_idx_release(netbk, pending_idx); for (j = start; j < i; j++) { pending_idx = frag_get_pending_idx(&shinfo->frags[j]); xen_netbk_idx_release(netbk, pending_idx); } /* Remember the error: invalidate all subsequent fragments. */ err = newerr; } *gopp = gop + 1; return err; } static void xen_netbk_fill_frags(struct xen_netbk *netbk, struct sk_buff *skb) { struct skb_shared_info *shinfo = skb_shinfo(skb); int nr_frags = shinfo->nr_frags; int i; for (i = 0; i < nr_frags; i++) { skb_frag_t *frag = shinfo->frags + i; struct xen_netif_tx_request *txp; struct page *page; u16 pending_idx; pending_idx = frag_get_pending_idx(frag); txp = &netbk->pending_tx_info[pending_idx].req; page = virt_to_page(idx_to_kaddr(netbk, pending_idx)); __skb_fill_page_desc(skb, i, page, txp->offset, txp->size); skb->len += txp->size; skb->data_len += txp->size; skb->truesize += txp->size; /* Take an extra reference to offset xen_netbk_idx_release */ get_page(netbk->mmap_pages[pending_idx]); xen_netbk_idx_release(netbk, pending_idx); } } static int xen_netbk_get_extras(struct xenvif *vif, struct xen_netif_extra_info *extras, int work_to_do) { struct xen_netif_extra_info extra; RING_IDX cons = vif->tx.req_cons; do { if (unlikely(work_to_do-- <= 0)) { netdev_dbg(vif->dev, "Missing extra info\n"); return -EBADR; } memcpy(&extra, RING_GET_REQUEST(&vif->tx, cons), sizeof(extra)); if (unlikely(!extra.type || extra.type >= XEN_NETIF_EXTRA_TYPE_MAX)) { vif->tx.req_cons = ++cons; netdev_dbg(vif->dev, "Invalid extra type: %d\n", extra.type); return -EINVAL; } memcpy(&extras[extra.type - 1], &extra, sizeof(extra)); vif->tx.req_cons = ++cons; } while (extra.flags & XEN_NETIF_EXTRA_FLAG_MORE); return work_to_do; } static int netbk_set_skb_gso(struct xenvif *vif, struct sk_buff *skb, struct xen_netif_extra_info *gso) { if (!gso->u.gso.size) { netdev_dbg(vif->dev, "GSO size must not be zero.\n"); return -EINVAL; } /* Currently only TCPv4 S.O. is supported. */ if (gso->u.gso.type != XEN_NETIF_GSO_TYPE_TCPV4) { netdev_dbg(vif->dev, "Bad GSO type %d.\n", gso->u.gso.type); return -EINVAL; } skb_shinfo(skb)->gso_size = gso->u.gso.size; skb_shinfo(skb)->gso_type = SKB_GSO_TCPV4; /* Header must be checked, and gso_segs computed. */ skb_shinfo(skb)->gso_type |= SKB_GSO_DODGY; skb_shinfo(skb)->gso_segs = 0; return 0; } static int checksum_setup(struct xenvif *vif, struct sk_buff *skb) { struct iphdr *iph; unsigned char *th; int err = -EPROTO; int recalculate_partial_csum = 0; /* * A GSO SKB must be CHECKSUM_PARTIAL. However some buggy * peers can fail to set NETRXF_csum_blank when sending a GSO * frame. In this case force the SKB to CHECKSUM_PARTIAL and * recalculate the partial checksum. */ if (skb->ip_summed != CHECKSUM_PARTIAL && skb_is_gso(skb)) { vif->rx_gso_checksum_fixup++; skb->ip_summed = CHECKSUM_PARTIAL; recalculate_partial_csum = 1; } /* A non-CHECKSUM_PARTIAL SKB does not require setup. */ if (skb->ip_summed != CHECKSUM_PARTIAL) return 0; if (skb->protocol != htons(ETH_P_IP)) goto out; iph = (void *)skb->data; th = skb->data + 4 * iph->ihl; if (th >= skb_tail_pointer(skb)) goto out; skb->csum_start = th - skb->head; switch (iph->protocol) { case IPPROTO_TCP: skb->csum_offset = offsetof(struct tcphdr, check); if (recalculate_partial_csum) { struct tcphdr *tcph = (struct tcphdr *)th; tcph->check = ~csum_tcpudp_magic(iph->saddr, iph->daddr, skb->len - iph->ihl*4, IPPROTO_TCP, 0); } break; case IPPROTO_UDP: skb->csum_offset = offsetof(struct udphdr, check); if (recalculate_partial_csum) { struct udphdr *udph = (struct udphdr *)th; udph->check = ~csum_tcpudp_magic(iph->saddr, iph->daddr, skb->len - iph->ihl*4, IPPROTO_UDP, 0); } break; default: if (net_ratelimit()) netdev_err(vif->dev, "Attempting to checksum a non-TCP/UDP packet, dropping a protocol %d packet\n", iph->protocol); goto out; } if ((th + skb->csum_offset + 2) > skb_tail_pointer(skb)) goto out; err = 0; out: return err; } static bool tx_credit_exceeded(struct xenvif *vif, unsigned size) { unsigned long now = jiffies; unsigned long next_credit = vif->credit_timeout.expires + msecs_to_jiffies(vif->credit_usec / 1000); /* Timer could already be pending in rare cases. */ if (timer_pending(&vif->credit_timeout)) return true; /* Passed the point where we can replenish credit? */ if (time_after_eq(now, next_credit)) { vif->credit_timeout.expires = now; tx_add_credit(vif); } /* Still too big to send right now? Set a callback. */ if (size > vif->remaining_credit) { vif->credit_timeout.data = (unsigned long)vif; vif->credit_timeout.function = tx_credit_callback; mod_timer(&vif->credit_timeout, next_credit); return true; } return false; } static unsigned xen_netbk_tx_build_gops(struct xen_netbk *netbk) { struct gnttab_copy *gop = netbk->tx_copy_ops, *request_gop; struct sk_buff *skb; int ret; while (((nr_pending_reqs(netbk) + MAX_SKB_FRAGS) < MAX_PENDING_REQS) && !list_empty(&netbk->net_schedule_list)) { struct xenvif *vif; struct xen_netif_tx_request txreq; struct xen_netif_tx_request txfrags[MAX_SKB_FRAGS]; struct page *page; struct xen_netif_extra_info extras[XEN_NETIF_EXTRA_TYPE_MAX-1]; u16 pending_idx; RING_IDX idx; int work_to_do; unsigned int data_len; pending_ring_idx_t index; /* Get a netif from the list with work to do. */ vif = poll_net_schedule_list(netbk); if (!vif) continue; RING_FINAL_CHECK_FOR_REQUESTS(&vif->tx, work_to_do); if (!work_to_do) { xenvif_put(vif); continue; } idx = vif->tx.req_cons; rmb(); /* Ensure that we see the request before we copy it. */ memcpy(&txreq, RING_GET_REQUEST(&vif->tx, idx), sizeof(txreq)); /* Credit-based scheduling. */ if (txreq.size > vif->remaining_credit && tx_credit_exceeded(vif, txreq.size)) { xenvif_put(vif); continue; } vif->remaining_credit -= txreq.size; work_to_do--; vif->tx.req_cons = ++idx; memset(extras, 0, sizeof(extras)); if (txreq.flags & XEN_NETTXF_extra_info) { work_to_do = xen_netbk_get_extras(vif, extras, work_to_do); idx = vif->tx.req_cons; if (unlikely(work_to_do < 0)) { netbk_tx_err(vif, &txreq, idx); continue; } } ret = netbk_count_requests(vif, &txreq, txfrags, work_to_do); if (unlikely(ret < 0)) { netbk_tx_err(vif, &txreq, idx - ret); continue; } idx += ret; if (unlikely(txreq.size < ETH_HLEN)) { netdev_dbg(vif->dev, "Bad packet size: %d\n", txreq.size); netbk_tx_err(vif, &txreq, idx); continue; } /* No crossing a page as the payload mustn't fragment. */ if (unlikely((txreq.offset + txreq.size) > PAGE_SIZE)) { netdev_dbg(vif->dev, "txreq.offset: %x, size: %u, end: %lu\n", txreq.offset, txreq.size, (txreq.offset&~PAGE_MASK) + txreq.size); netbk_tx_err(vif, &txreq, idx); continue; } index = pending_index(netbk->pending_cons); pending_idx = netbk->pending_ring[index]; data_len = (txreq.size > PKT_PROT_LEN && ret < MAX_SKB_FRAGS) ? PKT_PROT_LEN : txreq.size; skb = alloc_skb(data_len + NET_SKB_PAD + NET_IP_ALIGN, GFP_ATOMIC | __GFP_NOWARN); if (unlikely(skb == NULL)) { netdev_dbg(vif->dev, "Can't allocate a skb in start_xmit.\n"); netbk_tx_err(vif, &txreq, idx); break; } /* Packets passed to netif_rx() must have some headroom. */ skb_reserve(skb, NET_SKB_PAD + NET_IP_ALIGN); if (extras[XEN_NETIF_EXTRA_TYPE_GSO - 1].type) { struct xen_netif_extra_info *gso; gso = &extras[XEN_NETIF_EXTRA_TYPE_GSO - 1]; if (netbk_set_skb_gso(vif, skb, gso)) { kfree_skb(skb); netbk_tx_err(vif, &txreq, idx); continue; } } /* XXX could copy straight to head */ page = xen_netbk_alloc_page(netbk, skb, pending_idx); if (!page) { kfree_skb(skb); netbk_tx_err(vif, &txreq, idx); continue; } gop->source.u.ref = txreq.gref; gop->source.domid = vif->domid; gop->source.offset = txreq.offset; gop->dest.u.gmfn = virt_to_mfn(page_address(page)); gop->dest.domid = DOMID_SELF; gop->dest.offset = txreq.offset; gop->len = txreq.size; gop->flags = GNTCOPY_source_gref; gop++; memcpy(&netbk->pending_tx_info[pending_idx].req, &txreq, sizeof(txreq)); netbk->pending_tx_info[pending_idx].vif = vif; *((u16 *)skb->data) = pending_idx; __skb_put(skb, data_len); skb_shinfo(skb)->nr_frags = ret; if (data_len < txreq.size) { skb_shinfo(skb)->nr_frags++; frag_set_pending_idx(&skb_shinfo(skb)->frags[0], pending_idx); } else { frag_set_pending_idx(&skb_shinfo(skb)->frags[0], INVALID_PENDING_IDX); } netbk->pending_cons++; request_gop = xen_netbk_get_requests(netbk, vif, skb, txfrags, gop); if (request_gop == NULL) { kfree_skb(skb); netbk_tx_err(vif, &txreq, idx); continue; } gop = request_gop; __skb_queue_tail(&netbk->tx_queue, skb); vif->tx.req_cons = idx; xen_netbk_check_rx_xenvif(vif); if ((gop-netbk->tx_copy_ops) >= ARRAY_SIZE(netbk->tx_copy_ops)) break; } return gop - netbk->tx_copy_ops; } static void xen_netbk_tx_submit(struct xen_netbk *netbk) { struct gnttab_copy *gop = netbk->tx_copy_ops; struct sk_buff *skb; while ((skb = __skb_dequeue(&netbk->tx_queue)) != NULL) { struct xen_netif_tx_request *txp; struct xenvif *vif; u16 pending_idx; unsigned data_len; pending_idx = *((u16 *)skb->data); vif = netbk->pending_tx_info[pending_idx].vif; txp = &netbk->pending_tx_info[pending_idx].req; /* Check the remap error code. */ if (unlikely(xen_netbk_tx_check_gop(netbk, skb, &gop))) { netdev_dbg(vif->dev, "netback grant failed.\n"); skb_shinfo(skb)->nr_frags = 0; kfree_skb(skb); continue; } data_len = skb->len; memcpy(skb->data, (void *)(idx_to_kaddr(netbk, pending_idx)|txp->offset), data_len); if (data_len < txp->size) { /* Append the packet payload as a fragment. */ txp->offset += data_len; txp->size -= data_len; } else { /* Schedule a response immediately. */ xen_netbk_idx_release(netbk, pending_idx); } if (txp->flags & XEN_NETTXF_csum_blank) skb->ip_summed = CHECKSUM_PARTIAL; else if (txp->flags & XEN_NETTXF_data_validated) skb->ip_summed = CHECKSUM_UNNECESSARY; xen_netbk_fill_frags(netbk, skb); /* * If the initial fragment was < PKT_PROT_LEN then * pull through some bytes from the other fragments to * increase the linear region to PKT_PROT_LEN bytes. */ if (skb_headlen(skb) < PKT_PROT_LEN && skb_is_nonlinear(skb)) { int target = min_t(int, skb->len, PKT_PROT_LEN); __pskb_pull_tail(skb, target - skb_headlen(skb)); } skb->dev = vif->dev; skb->protocol = eth_type_trans(skb, skb->dev); if (checksum_setup(vif, skb)) { netdev_dbg(vif->dev, "Can't setup checksum in net_tx_action\n"); kfree_skb(skb); continue; } vif->dev->stats.rx_bytes += skb->len; vif->dev->stats.rx_packets++; xenvif_receive_skb(vif, skb); } } /* Called after netfront has transmitted */ static void xen_netbk_tx_action(struct xen_netbk *netbk) { unsigned nr_gops; nr_gops = xen_netbk_tx_build_gops(netbk); if (nr_gops == 0) return; gnttab_batch_copy(netbk->tx_copy_ops, nr_gops); xen_netbk_tx_submit(netbk); } static void xen_netbk_idx_release(struct xen_netbk *netbk, u16 pending_idx) { struct xenvif *vif; struct pending_tx_info *pending_tx_info; pending_ring_idx_t index; /* Already complete? */ if (netbk->mmap_pages[pending_idx] == NULL) return; pending_tx_info = &netbk->pending_tx_info[pending_idx]; vif = pending_tx_info->vif; make_tx_response(vif, &pending_tx_info->req, XEN_NETIF_RSP_OKAY); index = pending_index(netbk->pending_prod++); netbk->pending_ring[index] = pending_idx; xenvif_put(vif); netbk->mmap_pages[pending_idx]->mapping = 0; put_page(netbk->mmap_pages[pending_idx]); netbk->mmap_pages[pending_idx] = NULL; } static void make_tx_response(struct xenvif *vif, struct xen_netif_tx_request *txp, s8 st) { RING_IDX i = vif->tx.rsp_prod_pvt; struct xen_netif_tx_response *resp; int notify; resp = RING_GET_RESPONSE(&vif->tx, i); resp->id = txp->id; resp->status = st; if (txp->flags & XEN_NETTXF_extra_info) RING_GET_RESPONSE(&vif->tx, ++i)->status = XEN_NETIF_RSP_NULL; vif->tx.rsp_prod_pvt = ++i; RING_PUSH_RESPONSES_AND_CHECK_NOTIFY(&vif->tx, notify); if (notify) notify_remote_via_irq(vif->irq); } static struct xen_netif_rx_response *make_rx_response(struct xenvif *vif, u16 id, s8 st, u16 offset, u16 size, u16 flags) { RING_IDX i = vif->rx.rsp_prod_pvt; struct xen_netif_rx_response *resp; resp = RING_GET_RESPONSE(&vif->rx, i); resp->offset = offset; resp->flags = flags; resp->id = id; resp->status = (s16)size; if (st < 0) resp->status = (s16)st; vif->rx.rsp_prod_pvt = ++i; return resp; } static inline int rx_work_todo(struct xen_netbk *netbk) { return !skb_queue_empty(&netbk->rx_queue); } static inline int tx_work_todo(struct xen_netbk *netbk) { if (((nr_pending_reqs(netbk) + MAX_SKB_FRAGS) < MAX_PENDING_REQS) && !list_empty(&netbk->net_schedule_list)) return 1; return 0; } static int xen_netbk_kthread(void *data) { struct xen_netbk *netbk = data; while (!kthread_should_stop()) { wait_event_interruptible(netbk->wq, rx_work_todo(netbk) || tx_work_todo(netbk) || kthread_should_stop()); cond_resched(); if (kthread_should_stop()) break; if (rx_work_todo(netbk)) xen_netbk_rx_action(netbk); if (tx_work_todo(netbk)) xen_netbk_tx_action(netbk); } return 0; } void xen_netbk_unmap_frontend_rings(struct xenvif *vif) { if (vif->tx.sring) xenbus_unmap_ring_vfree(xenvif_to_xenbus_device(vif), vif->tx.sring); if (vif->rx.sring) xenbus_unmap_ring_vfree(xenvif_to_xenbus_device(vif), vif->rx.sring); } int xen_netbk_map_frontend_rings(struct xenvif *vif, grant_ref_t tx_ring_ref, grant_ref_t rx_ring_ref) { void *addr; struct xen_netif_tx_sring *txs; struct xen_netif_rx_sring *rxs; int err = -ENOMEM; err = xenbus_map_ring_valloc(xenvif_to_xenbus_device(vif), tx_ring_ref, &addr); if (err) goto err; txs = (struct xen_netif_tx_sring *)addr; BACK_RING_INIT(&vif->tx, txs, PAGE_SIZE); err = xenbus_map_ring_valloc(xenvif_to_xenbus_device(vif), rx_ring_ref, &addr); if (err) goto err; rxs = (struct xen_netif_rx_sring *)addr; BACK_RING_INIT(&vif->rx, rxs, PAGE_SIZE); vif->rx_req_cons_peek = 0; return 0; err: xen_netbk_unmap_frontend_rings(vif); return err; } static int __init netback_init(void) { int i; int rc = 0; int group; if (!xen_domain()) return -ENODEV; xen_netbk_group_nr = num_online_cpus(); xen_netbk = vzalloc(sizeof(struct xen_netbk) * xen_netbk_group_nr); if (!xen_netbk) return -ENOMEM; for (group = 0; group < xen_netbk_group_nr; group++) { struct xen_netbk *netbk = &xen_netbk[group]; skb_queue_head_init(&netbk->rx_queue); skb_queue_head_init(&netbk->tx_queue); init_timer(&netbk->net_timer); netbk->net_timer.data = (unsigned long)netbk; netbk->net_timer.function = xen_netbk_alarm; netbk->pending_cons = 0; netbk->pending_prod = MAX_PENDING_REQS; for (i = 0; i < MAX_PENDING_REQS; i++) netbk->pending_ring[i] = i; init_waitqueue_head(&netbk->wq); netbk->task = kthread_create(xen_netbk_kthread, (void *)netbk, "netback/%u", group); if (IS_ERR(netbk->task)) { printk(KERN_ALERT "kthread_create() fails at netback\n"); del_timer(&netbk->net_timer); rc = PTR_ERR(netbk->task); goto failed_init; } kthread_bind(netbk->task, group); INIT_LIST_HEAD(&netbk->net_schedule_list); spin_lock_init(&netbk->net_schedule_list_lock); atomic_set(&netbk->netfront_count, 0); wake_up_process(netbk->task); } rc = xenvif_xenbus_init(); if (rc) goto failed_init; return 0; failed_init: while (--group >= 0) { struct xen_netbk *netbk = &xen_netbk[group]; for (i = 0; i < MAX_PENDING_REQS; i++) { if (netbk->mmap_pages[i]) __free_page(netbk->mmap_pages[i]); } del_timer(&netbk->net_timer); kthread_stop(netbk->task); } vfree(xen_netbk); return rc; } module_init(netback_init); MODULE_LICENSE("Dual BSD/GPL"); MODULE_ALIAS("xen-backend:vif");
./CrossVul/dataset_final_sorted/CWE-20/c/bad_5544_2
crossvul-cpp_data_good_2589_0
/* * RTMP input format * Copyright (c) 2009 Konstantin Shishkov * * 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 "libavcodec/bytestream.h" #include "libavutil/avstring.h" #include "libavutil/intfloat.h" #include "avformat.h" #include "rtmppkt.h" #include "flv.h" #include "url.h" void ff_amf_write_bool(uint8_t **dst, int val) { bytestream_put_byte(dst, AMF_DATA_TYPE_BOOL); bytestream_put_byte(dst, val); } void ff_amf_write_number(uint8_t **dst, double val) { bytestream_put_byte(dst, AMF_DATA_TYPE_NUMBER); bytestream_put_be64(dst, av_double2int(val)); } void ff_amf_write_string(uint8_t **dst, const char *str) { bytestream_put_byte(dst, AMF_DATA_TYPE_STRING); bytestream_put_be16(dst, strlen(str)); bytestream_put_buffer(dst, str, strlen(str)); } void ff_amf_write_string2(uint8_t **dst, const char *str1, const char *str2) { int len1 = 0, len2 = 0; if (str1) len1 = strlen(str1); if (str2) len2 = strlen(str2); bytestream_put_byte(dst, AMF_DATA_TYPE_STRING); bytestream_put_be16(dst, len1 + len2); bytestream_put_buffer(dst, str1, len1); bytestream_put_buffer(dst, str2, len2); } void ff_amf_write_null(uint8_t **dst) { bytestream_put_byte(dst, AMF_DATA_TYPE_NULL); } void ff_amf_write_object_start(uint8_t **dst) { bytestream_put_byte(dst, AMF_DATA_TYPE_OBJECT); } void ff_amf_write_field_name(uint8_t **dst, const char *str) { bytestream_put_be16(dst, strlen(str)); bytestream_put_buffer(dst, str, strlen(str)); } void ff_amf_write_object_end(uint8_t **dst) { /* first two bytes are field name length = 0, * AMF object should end with it and end marker */ bytestream_put_be24(dst, AMF_DATA_TYPE_OBJECT_END); } int ff_amf_read_bool(GetByteContext *bc, int *val) { if (bytestream2_get_byte(bc) != AMF_DATA_TYPE_BOOL) return AVERROR_INVALIDDATA; *val = bytestream2_get_byte(bc); return 0; } int ff_amf_read_number(GetByteContext *bc, double *val) { uint64_t read; if (bytestream2_get_byte(bc) != AMF_DATA_TYPE_NUMBER) return AVERROR_INVALIDDATA; read = bytestream2_get_be64(bc); *val = av_int2double(read); return 0; } int ff_amf_get_string(GetByteContext *bc, uint8_t *str, int strsize, int *length) { int stringlen = 0; int readsize; stringlen = bytestream2_get_be16(bc); if (stringlen + 1 > strsize) return AVERROR(EINVAL); readsize = bytestream2_get_buffer(bc, str, stringlen); if (readsize != stringlen) { av_log(NULL, AV_LOG_WARNING, "Unable to read as many bytes as AMF string signaled\n"); } str[readsize] = '\0'; *length = FFMIN(stringlen, readsize); return 0; } int ff_amf_read_string(GetByteContext *bc, uint8_t *str, int strsize, int *length) { if (bytestream2_get_byte(bc) != AMF_DATA_TYPE_STRING) return AVERROR_INVALIDDATA; return ff_amf_get_string(bc, str, strsize, length); } int ff_amf_read_null(GetByteContext *bc) { if (bytestream2_get_byte(bc) != AMF_DATA_TYPE_NULL) return AVERROR_INVALIDDATA; return 0; } int ff_rtmp_check_alloc_array(RTMPPacket **prev_pkt, int *nb_prev_pkt, int channel) { int nb_alloc; RTMPPacket *ptr; if (channel < *nb_prev_pkt) return 0; nb_alloc = channel + 16; // This can't use the av_reallocp family of functions, since we // would need to free each element in the array before the array // itself is freed. ptr = av_realloc_array(*prev_pkt, nb_alloc, sizeof(**prev_pkt)); if (!ptr) return AVERROR(ENOMEM); memset(ptr + *nb_prev_pkt, 0, (nb_alloc - *nb_prev_pkt) * sizeof(*ptr)); *prev_pkt = ptr; *nb_prev_pkt = nb_alloc; return 0; } int ff_rtmp_packet_read(URLContext *h, RTMPPacket *p, int chunk_size, RTMPPacket **prev_pkt, int *nb_prev_pkt) { uint8_t hdr; if (ffurl_read(h, &hdr, 1) != 1) return AVERROR(EIO); return ff_rtmp_packet_read_internal(h, p, chunk_size, prev_pkt, nb_prev_pkt, hdr); } static int rtmp_packet_read_one_chunk(URLContext *h, RTMPPacket *p, int chunk_size, RTMPPacket **prev_pkt_ptr, int *nb_prev_pkt, uint8_t hdr) { uint8_t buf[16]; int channel_id, timestamp, size; uint32_t ts_field; // non-extended timestamp or delta field uint32_t extra = 0; enum RTMPPacketType type; int written = 0; int ret, toread; RTMPPacket *prev_pkt; written++; channel_id = hdr & 0x3F; if (channel_id < 2) { //special case for channel number >= 64 buf[1] = 0; if (ffurl_read_complete(h, buf, channel_id + 1) != channel_id + 1) return AVERROR(EIO); written += channel_id + 1; channel_id = AV_RL16(buf) + 64; } if ((ret = ff_rtmp_check_alloc_array(prev_pkt_ptr, nb_prev_pkt, channel_id)) < 0) return ret; prev_pkt = *prev_pkt_ptr; size = prev_pkt[channel_id].size; type = prev_pkt[channel_id].type; extra = prev_pkt[channel_id].extra; hdr >>= 6; // header size indicator if (hdr == RTMP_PS_ONEBYTE) { ts_field = prev_pkt[channel_id].ts_field; } else { if (ffurl_read_complete(h, buf, 3) != 3) return AVERROR(EIO); written += 3; ts_field = AV_RB24(buf); if (hdr != RTMP_PS_FOURBYTES) { if (ffurl_read_complete(h, buf, 3) != 3) return AVERROR(EIO); written += 3; size = AV_RB24(buf); if (ffurl_read_complete(h, buf, 1) != 1) return AVERROR(EIO); written++; type = buf[0]; if (hdr == RTMP_PS_TWELVEBYTES) { if (ffurl_read_complete(h, buf, 4) != 4) return AVERROR(EIO); written += 4; extra = AV_RL32(buf); } } } if (ts_field == 0xFFFFFF) { if (ffurl_read_complete(h, buf, 4) != 4) return AVERROR(EIO); timestamp = AV_RB32(buf); } else { timestamp = ts_field; } if (hdr != RTMP_PS_TWELVEBYTES) timestamp += prev_pkt[channel_id].timestamp; if (prev_pkt[channel_id].read && size != prev_pkt[channel_id].size) { av_log(h, AV_LOG_ERROR, "RTMP packet size mismatch %d != %d\n", size, prev_pkt[channel_id].size); ff_rtmp_packet_destroy(&prev_pkt[channel_id]); prev_pkt[channel_id].read = 0; return AVERROR_INVALIDDATA; } if (!prev_pkt[channel_id].read) { if ((ret = ff_rtmp_packet_create(p, channel_id, type, timestamp, size)) < 0) return ret; p->read = written; p->offset = 0; prev_pkt[channel_id].ts_field = ts_field; prev_pkt[channel_id].timestamp = timestamp; } else { // previous packet in this channel hasn't completed reading RTMPPacket *prev = &prev_pkt[channel_id]; p->data = prev->data; p->size = prev->size; p->channel_id = prev->channel_id; p->type = prev->type; p->ts_field = prev->ts_field; p->extra = prev->extra; p->offset = prev->offset; p->read = prev->read + written; p->timestamp = prev->timestamp; prev->data = NULL; } p->extra = extra; // save history prev_pkt[channel_id].channel_id = channel_id; prev_pkt[channel_id].type = type; prev_pkt[channel_id].size = size; prev_pkt[channel_id].extra = extra; size = size - p->offset; toread = FFMIN(size, chunk_size); if (ffurl_read_complete(h, p->data + p->offset, toread) != toread) { ff_rtmp_packet_destroy(p); return AVERROR(EIO); } size -= toread; p->read += toread; p->offset += toread; if (size > 0) { RTMPPacket *prev = &prev_pkt[channel_id]; prev->data = p->data; prev->read = p->read; prev->offset = p->offset; p->data = NULL; return AVERROR(EAGAIN); } prev_pkt[channel_id].read = 0; // read complete; reset if needed return p->read; } int ff_rtmp_packet_read_internal(URLContext *h, RTMPPacket *p, int chunk_size, RTMPPacket **prev_pkt, int *nb_prev_pkt, uint8_t hdr) { while (1) { int ret = rtmp_packet_read_one_chunk(h, p, chunk_size, prev_pkt, nb_prev_pkt, hdr); if (ret > 0 || ret != AVERROR(EAGAIN)) return ret; if (ffurl_read(h, &hdr, 1) != 1) return AVERROR(EIO); } } int ff_rtmp_packet_write(URLContext *h, RTMPPacket *pkt, int chunk_size, RTMPPacket **prev_pkt_ptr, int *nb_prev_pkt) { uint8_t pkt_hdr[16], *p = pkt_hdr; int mode = RTMP_PS_TWELVEBYTES; int off = 0; int written = 0; int ret; RTMPPacket *prev_pkt; int use_delta; // flag if using timestamp delta, not RTMP_PS_TWELVEBYTES uint32_t timestamp; // full 32-bit timestamp or delta value if ((ret = ff_rtmp_check_alloc_array(prev_pkt_ptr, nb_prev_pkt, pkt->channel_id)) < 0) return ret; prev_pkt = *prev_pkt_ptr; //if channel_id = 0, this is first presentation of prev_pkt, send full hdr. use_delta = prev_pkt[pkt->channel_id].channel_id && pkt->extra == prev_pkt[pkt->channel_id].extra && pkt->timestamp >= prev_pkt[pkt->channel_id].timestamp; timestamp = pkt->timestamp; if (use_delta) { timestamp -= prev_pkt[pkt->channel_id].timestamp; } if (timestamp >= 0xFFFFFF) { pkt->ts_field = 0xFFFFFF; } else { pkt->ts_field = timestamp; } if (use_delta) { if (pkt->type == prev_pkt[pkt->channel_id].type && pkt->size == prev_pkt[pkt->channel_id].size) { mode = RTMP_PS_FOURBYTES; if (pkt->ts_field == prev_pkt[pkt->channel_id].ts_field) mode = RTMP_PS_ONEBYTE; } else { mode = RTMP_PS_EIGHTBYTES; } } if (pkt->channel_id < 64) { bytestream_put_byte(&p, pkt->channel_id | (mode << 6)); } else if (pkt->channel_id < 64 + 256) { bytestream_put_byte(&p, 0 | (mode << 6)); bytestream_put_byte(&p, pkt->channel_id - 64); } else { bytestream_put_byte(&p, 1 | (mode << 6)); bytestream_put_le16(&p, pkt->channel_id - 64); } if (mode != RTMP_PS_ONEBYTE) { bytestream_put_be24(&p, pkt->ts_field); if (mode != RTMP_PS_FOURBYTES) { bytestream_put_be24(&p, pkt->size); bytestream_put_byte(&p, pkt->type); if (mode == RTMP_PS_TWELVEBYTES) bytestream_put_le32(&p, pkt->extra); } } if (pkt->ts_field == 0xFFFFFF) bytestream_put_be32(&p, timestamp); // save history prev_pkt[pkt->channel_id].channel_id = pkt->channel_id; prev_pkt[pkt->channel_id].type = pkt->type; prev_pkt[pkt->channel_id].size = pkt->size; prev_pkt[pkt->channel_id].timestamp = pkt->timestamp; prev_pkt[pkt->channel_id].ts_field = pkt->ts_field; prev_pkt[pkt->channel_id].extra = pkt->extra; if ((ret = ffurl_write(h, pkt_hdr, p - pkt_hdr)) < 0) return ret; written = p - pkt_hdr + pkt->size; while (off < pkt->size) { int towrite = FFMIN(chunk_size, pkt->size - off); if ((ret = ffurl_write(h, pkt->data + off, towrite)) < 0) return ret; off += towrite; if (off < pkt->size) { uint8_t marker = 0xC0 | pkt->channel_id; if ((ret = ffurl_write(h, &marker, 1)) < 0) return ret; written++; if (pkt->ts_field == 0xFFFFFF) { uint8_t ts_header[4]; AV_WB32(ts_header, timestamp); if ((ret = ffurl_write(h, ts_header, 4)) < 0) return ret; written += 4; } } } return written; } int ff_rtmp_packet_create(RTMPPacket *pkt, int channel_id, RTMPPacketType type, int timestamp, int size) { if (size) { pkt->data = av_realloc(NULL, size); if (!pkt->data) return AVERROR(ENOMEM); } pkt->size = size; pkt->channel_id = channel_id; pkt->type = type; pkt->timestamp = timestamp; pkt->extra = 0; pkt->ts_field = 0; return 0; } void ff_rtmp_packet_destroy(RTMPPacket *pkt) { if (!pkt) return; av_freep(&pkt->data); pkt->size = 0; } static int amf_tag_skip(GetByteContext *gb) { AMFDataType type; unsigned nb = -1; int parse_key = 1; if (bytestream2_get_bytes_left(gb) < 1) return -1; type = bytestream2_get_byte(gb); switch (type) { case AMF_DATA_TYPE_NUMBER: bytestream2_get_be64(gb); return 0; case AMF_DATA_TYPE_BOOL: bytestream2_get_byte(gb); return 0; case AMF_DATA_TYPE_STRING: bytestream2_skip(gb, bytestream2_get_be16(gb)); return 0; case AMF_DATA_TYPE_LONG_STRING: bytestream2_skip(gb, bytestream2_get_be32(gb)); return 0; case AMF_DATA_TYPE_NULL: return 0; case AMF_DATA_TYPE_DATE: bytestream2_skip(gb, 10); return 0; case AMF_DATA_TYPE_ARRAY: parse_key = 0; case AMF_DATA_TYPE_MIXEDARRAY: nb = bytestream2_get_be32(gb); case AMF_DATA_TYPE_OBJECT: while (nb-- > 0 || type != AMF_DATA_TYPE_ARRAY) { int t; if (parse_key) { int size = bytestream2_get_be16(gb); if (!size) { bytestream2_get_byte(gb); break; } if (size < 0 || size >= bytestream2_get_bytes_left(gb)) return -1; bytestream2_skip(gb, size); } t = amf_tag_skip(gb); if (t < 0 || bytestream2_get_bytes_left(gb) <= 0) return -1; } return 0; case AMF_DATA_TYPE_OBJECT_END: return 0; default: return -1; } } int ff_amf_tag_size(const uint8_t *data, const uint8_t *data_end) { GetByteContext gb; int ret; if (data >= data_end) return -1; bytestream2_init(&gb, data, data_end - data); ret = amf_tag_skip(&gb); if (ret < 0 || bytestream2_get_bytes_left(&gb) <= 0) return -1; av_assert0(bytestream2_tell(&gb) >= 0 && bytestream2_tell(&gb) <= data_end - data); return bytestream2_tell(&gb); } static int amf_get_field_value2(GetByteContext *gb, const uint8_t *name, uint8_t *dst, int dst_size) { int namelen = strlen(name); int len; while (bytestream2_peek_byte(gb) != AMF_DATA_TYPE_OBJECT && bytestream2_get_bytes_left(gb) > 0) { int ret = amf_tag_skip(gb); if (ret < 0) return -1; } if (bytestream2_get_bytes_left(gb) < 3) return -1; bytestream2_get_byte(gb); for (;;) { int size = bytestream2_get_be16(gb); if (!size) break; if (size < 0 || size >= bytestream2_get_bytes_left(gb)) return -1; bytestream2_skip(gb, size); if (size == namelen && !memcmp(gb->buffer-size, name, namelen)) { switch (bytestream2_get_byte(gb)) { case AMF_DATA_TYPE_NUMBER: snprintf(dst, dst_size, "%g", av_int2double(bytestream2_get_be64(gb))); break; case AMF_DATA_TYPE_BOOL: snprintf(dst, dst_size, "%s", bytestream2_get_byte(gb) ? "true" : "false"); break; case AMF_DATA_TYPE_STRING: len = bytestream2_get_be16(gb); if (dst_size < 1) return -1; if (dst_size < len + 1) len = dst_size - 1; bytestream2_get_buffer(gb, dst, len); dst[len] = 0; break; default: return -1; } return 0; } len = amf_tag_skip(gb); if (len < 0 || bytestream2_get_bytes_left(gb) <= 0) return -1; } return -1; } int ff_amf_get_field_value(const uint8_t *data, const uint8_t *data_end, const uint8_t *name, uint8_t *dst, int dst_size) { GetByteContext gb; if (data >= data_end) return -1; bytestream2_init(&gb, data, data_end - data); return amf_get_field_value2(&gb, name, dst, dst_size); } static const char* rtmp_packet_type(int type) { switch (type) { case RTMP_PT_CHUNK_SIZE: return "chunk size"; case RTMP_PT_BYTES_READ: return "bytes read"; case RTMP_PT_PING: return "ping"; case RTMP_PT_SERVER_BW: return "server bandwidth"; case RTMP_PT_CLIENT_BW: return "client bandwidth"; case RTMP_PT_AUDIO: return "audio packet"; case RTMP_PT_VIDEO: return "video packet"; case RTMP_PT_FLEX_STREAM: return "Flex shared stream"; case RTMP_PT_FLEX_OBJECT: return "Flex shared object"; case RTMP_PT_FLEX_MESSAGE: return "Flex shared message"; case RTMP_PT_NOTIFY: return "notification"; case RTMP_PT_SHARED_OBJ: return "shared object"; case RTMP_PT_INVOKE: return "invoke"; case RTMP_PT_METADATA: return "metadata"; default: return "unknown"; } } static void amf_tag_contents(void *ctx, const uint8_t *data, const uint8_t *data_end) { unsigned int size, nb = -1; char buf[1024]; AMFDataType type; int parse_key = 1; if (data >= data_end) return; switch ((type = *data++)) { case AMF_DATA_TYPE_NUMBER: av_log(ctx, AV_LOG_DEBUG, " number %g\n", av_int2double(AV_RB64(data))); return; case AMF_DATA_TYPE_BOOL: av_log(ctx, AV_LOG_DEBUG, " bool %d\n", *data); return; case AMF_DATA_TYPE_STRING: case AMF_DATA_TYPE_LONG_STRING: if (type == AMF_DATA_TYPE_STRING) { size = bytestream_get_be16(&data); } else { size = bytestream_get_be32(&data); } size = FFMIN(size, sizeof(buf) - 1); memcpy(buf, data, size); buf[size] = 0; av_log(ctx, AV_LOG_DEBUG, " string '%s'\n", buf); return; case AMF_DATA_TYPE_NULL: av_log(ctx, AV_LOG_DEBUG, " NULL\n"); return; case AMF_DATA_TYPE_ARRAY: parse_key = 0; case AMF_DATA_TYPE_MIXEDARRAY: nb = bytestream_get_be32(&data); case AMF_DATA_TYPE_OBJECT: av_log(ctx, AV_LOG_DEBUG, " {\n"); while (nb-- > 0 || type != AMF_DATA_TYPE_ARRAY) { int t; if (parse_key) { size = bytestream_get_be16(&data); size = FFMIN(size, sizeof(buf) - 1); if (!size) { av_log(ctx, AV_LOG_DEBUG, " }\n"); data++; break; } memcpy(buf, data, size); buf[size] = 0; if (size >= data_end - data) return; data += size; av_log(ctx, AV_LOG_DEBUG, " %s: ", buf); } amf_tag_contents(ctx, data, data_end); t = ff_amf_tag_size(data, data_end); if (t < 0 || t >= data_end - data) return; data += t; } return; case AMF_DATA_TYPE_OBJECT_END: av_log(ctx, AV_LOG_DEBUG, " }\n"); return; default: return; } } void ff_rtmp_packet_dump(void *ctx, RTMPPacket *p) { av_log(ctx, AV_LOG_DEBUG, "RTMP packet type '%s'(%d) for channel %d, timestamp %d, extra field %d size %d\n", rtmp_packet_type(p->type), p->type, p->channel_id, p->timestamp, p->extra, p->size); if (p->type == RTMP_PT_INVOKE || p->type == RTMP_PT_NOTIFY) { uint8_t *src = p->data, *src_end = p->data + p->size; while (src < src_end) { int sz; amf_tag_contents(ctx, src, src_end); sz = ff_amf_tag_size(src, src_end); if (sz < 0) break; src += sz; } } else if (p->type == RTMP_PT_SERVER_BW){ av_log(ctx, AV_LOG_DEBUG, "Server BW = %d\n", AV_RB32(p->data)); } else if (p->type == RTMP_PT_CLIENT_BW){ av_log(ctx, AV_LOG_DEBUG, "Client BW = %d\n", AV_RB32(p->data)); } else if (p->type != RTMP_PT_AUDIO && p->type != RTMP_PT_VIDEO && p->type != RTMP_PT_METADATA) { int i; for (i = 0; i < p->size; i++) av_log(ctx, AV_LOG_DEBUG, " %02X", p->data[i]); av_log(ctx, AV_LOG_DEBUG, "\n"); } } int ff_amf_match_string(const uint8_t *data, int size, const char *str) { int len = strlen(str); int amf_len, type; if (size < 1) return 0; type = *data++; if (type != AMF_DATA_TYPE_LONG_STRING && type != AMF_DATA_TYPE_STRING) return 0; if (type == AMF_DATA_TYPE_LONG_STRING) { if ((size -= 4 + 1) < 0) return 0; amf_len = bytestream_get_be32(&data); } else { if ((size -= 2 + 1) < 0) return 0; amf_len = bytestream_get_be16(&data); } if (amf_len > size) return 0; if (amf_len != len) return 0; return !memcmp(data, str, len); }
./CrossVul/dataset_final_sorted/CWE-20/c/good_2589_0
crossvul-cpp_data_good_3038_0
/* * Linux IPv6 multicast routing support for BSD pim6sd * Based on net/ipv4/ipmr.c. * * (c) 2004 Mickael Hoerdt, <hoerdt@clarinet.u-strasbg.fr> * LSIIT Laboratory, Strasbourg, France * (c) 2004 Jean-Philippe Andriot, <jean-philippe.andriot@6WIND.com> * 6WIND, Paris, France * Copyright (C)2007,2008 USAGI/WIDE Project * YOSHIFUJI Hideaki <yoshfuji@linux-ipv6.org> * * 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/uaccess.h> #include <linux/types.h> #include <linux/sched.h> #include <linux/errno.h> #include <linux/timer.h> #include <linux/mm.h> #include <linux/kernel.h> #include <linux/fcntl.h> #include <linux/stat.h> #include <linux/socket.h> #include <linux/inet.h> #include <linux/netdevice.h> #include <linux/inetdevice.h> #include <linux/proc_fs.h> #include <linux/seq_file.h> #include <linux/init.h> #include <linux/slab.h> #include <linux/compat.h> #include <net/protocol.h> #include <linux/skbuff.h> #include <net/sock.h> #include <net/raw.h> #include <linux/notifier.h> #include <linux/if_arp.h> #include <net/checksum.h> #include <net/netlink.h> #include <net/fib_rules.h> #include <net/ipv6.h> #include <net/ip6_route.h> #include <linux/mroute6.h> #include <linux/pim.h> #include <net/addrconf.h> #include <linux/netfilter_ipv6.h> #include <linux/export.h> #include <net/ip6_checksum.h> #include <linux/netconf.h> struct mr6_table { struct list_head list; possible_net_t net; u32 id; struct sock *mroute6_sk; struct timer_list ipmr_expire_timer; struct list_head mfc6_unres_queue; struct list_head mfc6_cache_array[MFC6_LINES]; struct mif_device vif6_table[MAXMIFS]; int maxvif; atomic_t cache_resolve_queue_len; bool mroute_do_assert; bool mroute_do_pim; #ifdef CONFIG_IPV6_PIMSM_V2 int mroute_reg_vif_num; #endif }; struct ip6mr_rule { struct fib_rule common; }; struct ip6mr_result { struct mr6_table *mrt; }; /* Big lock, protecting vif table, mrt cache and mroute socket state. Note that the changes are semaphored via rtnl_lock. */ static DEFINE_RWLOCK(mrt_lock); /* * Multicast router control variables */ #define MIF_EXISTS(_mrt, _idx) ((_mrt)->vif6_table[_idx].dev != NULL) /* Special spinlock for queue of unresolved entries */ static DEFINE_SPINLOCK(mfc_unres_lock); /* We return to original Alan's scheme. Hash table of resolved entries is changed only in process context and protected with weak lock mrt_lock. Queue of unresolved entries is protected with strong spinlock mfc_unres_lock. In this case data path is free of exclusive locks at all. */ static struct kmem_cache *mrt_cachep __read_mostly; static struct mr6_table *ip6mr_new_table(struct net *net, u32 id); static void ip6mr_free_table(struct mr6_table *mrt); static void ip6_mr_forward(struct net *net, struct mr6_table *mrt, struct sk_buff *skb, struct mfc6_cache *cache); static int ip6mr_cache_report(struct mr6_table *mrt, struct sk_buff *pkt, mifi_t mifi, int assert); static int __ip6mr_fill_mroute(struct mr6_table *mrt, struct sk_buff *skb, struct mfc6_cache *c, struct rtmsg *rtm); static void mr6_netlink_event(struct mr6_table *mrt, struct mfc6_cache *mfc, int cmd); static int ip6mr_rtm_dumproute(struct sk_buff *skb, struct netlink_callback *cb); static void mroute_clean_tables(struct mr6_table *mrt, bool all); static void ipmr_expire_process(unsigned long arg); #ifdef CONFIG_IPV6_MROUTE_MULTIPLE_TABLES #define ip6mr_for_each_table(mrt, net) \ list_for_each_entry_rcu(mrt, &net->ipv6.mr6_tables, list) static struct mr6_table *ip6mr_get_table(struct net *net, u32 id) { struct mr6_table *mrt; ip6mr_for_each_table(mrt, net) { if (mrt->id == id) return mrt; } return NULL; } static int ip6mr_fib_lookup(struct net *net, struct flowi6 *flp6, struct mr6_table **mrt) { int err; struct ip6mr_result res; struct fib_lookup_arg arg = { .result = &res, .flags = FIB_LOOKUP_NOREF, }; err = fib_rules_lookup(net->ipv6.mr6_rules_ops, flowi6_to_flowi(flp6), 0, &arg); if (err < 0) return err; *mrt = res.mrt; return 0; } static int ip6mr_rule_action(struct fib_rule *rule, struct flowi *flp, int flags, struct fib_lookup_arg *arg) { struct ip6mr_result *res = arg->result; struct mr6_table *mrt; switch (rule->action) { case FR_ACT_TO_TBL: break; case FR_ACT_UNREACHABLE: return -ENETUNREACH; case FR_ACT_PROHIBIT: return -EACCES; case FR_ACT_BLACKHOLE: default: return -EINVAL; } mrt = ip6mr_get_table(rule->fr_net, rule->table); if (!mrt) return -EAGAIN; res->mrt = mrt; return 0; } static int ip6mr_rule_match(struct fib_rule *rule, struct flowi *flp, int flags) { return 1; } static const struct nla_policy ip6mr_rule_policy[FRA_MAX + 1] = { FRA_GENERIC_POLICY, }; static int ip6mr_rule_configure(struct fib_rule *rule, struct sk_buff *skb, struct fib_rule_hdr *frh, struct nlattr **tb) { return 0; } static int ip6mr_rule_compare(struct fib_rule *rule, struct fib_rule_hdr *frh, struct nlattr **tb) { return 1; } static int ip6mr_rule_fill(struct fib_rule *rule, struct sk_buff *skb, struct fib_rule_hdr *frh) { frh->dst_len = 0; frh->src_len = 0; frh->tos = 0; return 0; } static const struct fib_rules_ops __net_initconst ip6mr_rules_ops_template = { .family = RTNL_FAMILY_IP6MR, .rule_size = sizeof(struct ip6mr_rule), .addr_size = sizeof(struct in6_addr), .action = ip6mr_rule_action, .match = ip6mr_rule_match, .configure = ip6mr_rule_configure, .compare = ip6mr_rule_compare, .fill = ip6mr_rule_fill, .nlgroup = RTNLGRP_IPV6_RULE, .policy = ip6mr_rule_policy, .owner = THIS_MODULE, }; static int __net_init ip6mr_rules_init(struct net *net) { struct fib_rules_ops *ops; struct mr6_table *mrt; int err; ops = fib_rules_register(&ip6mr_rules_ops_template, net); if (IS_ERR(ops)) return PTR_ERR(ops); INIT_LIST_HEAD(&net->ipv6.mr6_tables); mrt = ip6mr_new_table(net, RT6_TABLE_DFLT); if (!mrt) { err = -ENOMEM; goto err1; } err = fib_default_rule_add(ops, 0x7fff, RT6_TABLE_DFLT, 0); if (err < 0) goto err2; net->ipv6.mr6_rules_ops = ops; return 0; err2: ip6mr_free_table(mrt); err1: fib_rules_unregister(ops); return err; } static void __net_exit ip6mr_rules_exit(struct net *net) { struct mr6_table *mrt, *next; rtnl_lock(); list_for_each_entry_safe(mrt, next, &net->ipv6.mr6_tables, list) { list_del(&mrt->list); ip6mr_free_table(mrt); } fib_rules_unregister(net->ipv6.mr6_rules_ops); rtnl_unlock(); } #else #define ip6mr_for_each_table(mrt, net) \ for (mrt = net->ipv6.mrt6; mrt; mrt = NULL) static struct mr6_table *ip6mr_get_table(struct net *net, u32 id) { return net->ipv6.mrt6; } static int ip6mr_fib_lookup(struct net *net, struct flowi6 *flp6, struct mr6_table **mrt) { *mrt = net->ipv6.mrt6; return 0; } static int __net_init ip6mr_rules_init(struct net *net) { net->ipv6.mrt6 = ip6mr_new_table(net, RT6_TABLE_DFLT); return net->ipv6.mrt6 ? 0 : -ENOMEM; } static void __net_exit ip6mr_rules_exit(struct net *net) { rtnl_lock(); ip6mr_free_table(net->ipv6.mrt6); net->ipv6.mrt6 = NULL; rtnl_unlock(); } #endif static struct mr6_table *ip6mr_new_table(struct net *net, u32 id) { struct mr6_table *mrt; unsigned int i; mrt = ip6mr_get_table(net, id); if (mrt) return mrt; mrt = kzalloc(sizeof(*mrt), GFP_KERNEL); if (!mrt) return NULL; mrt->id = id; write_pnet(&mrt->net, net); /* Forwarding cache */ for (i = 0; i < MFC6_LINES; i++) INIT_LIST_HEAD(&mrt->mfc6_cache_array[i]); INIT_LIST_HEAD(&mrt->mfc6_unres_queue); setup_timer(&mrt->ipmr_expire_timer, ipmr_expire_process, (unsigned long)mrt); #ifdef CONFIG_IPV6_PIMSM_V2 mrt->mroute_reg_vif_num = -1; #endif #ifdef CONFIG_IPV6_MROUTE_MULTIPLE_TABLES list_add_tail_rcu(&mrt->list, &net->ipv6.mr6_tables); #endif return mrt; } static void ip6mr_free_table(struct mr6_table *mrt) { del_timer_sync(&mrt->ipmr_expire_timer); mroute_clean_tables(mrt, true); kfree(mrt); } #ifdef CONFIG_PROC_FS struct ipmr_mfc_iter { struct seq_net_private p; struct mr6_table *mrt; struct list_head *cache; int ct; }; static struct mfc6_cache *ipmr_mfc_seq_idx(struct net *net, struct ipmr_mfc_iter *it, loff_t pos) { struct mr6_table *mrt = it->mrt; struct mfc6_cache *mfc; read_lock(&mrt_lock); for (it->ct = 0; it->ct < MFC6_LINES; it->ct++) { it->cache = &mrt->mfc6_cache_array[it->ct]; list_for_each_entry(mfc, it->cache, list) if (pos-- == 0) return mfc; } read_unlock(&mrt_lock); spin_lock_bh(&mfc_unres_lock); it->cache = &mrt->mfc6_unres_queue; list_for_each_entry(mfc, it->cache, list) if (pos-- == 0) return mfc; spin_unlock_bh(&mfc_unres_lock); it->cache = NULL; return NULL; } /* * The /proc interfaces to multicast routing /proc/ip6_mr_cache /proc/ip6_mr_vif */ struct ipmr_vif_iter { struct seq_net_private p; struct mr6_table *mrt; int ct; }; static struct mif_device *ip6mr_vif_seq_idx(struct net *net, struct ipmr_vif_iter *iter, loff_t pos) { struct mr6_table *mrt = iter->mrt; for (iter->ct = 0; iter->ct < mrt->maxvif; ++iter->ct) { if (!MIF_EXISTS(mrt, iter->ct)) continue; if (pos-- == 0) return &mrt->vif6_table[iter->ct]; } return NULL; } static void *ip6mr_vif_seq_start(struct seq_file *seq, loff_t *pos) __acquires(mrt_lock) { struct ipmr_vif_iter *iter = seq->private; struct net *net = seq_file_net(seq); struct mr6_table *mrt; mrt = ip6mr_get_table(net, RT6_TABLE_DFLT); if (!mrt) return ERR_PTR(-ENOENT); iter->mrt = mrt; read_lock(&mrt_lock); return *pos ? ip6mr_vif_seq_idx(net, seq->private, *pos - 1) : SEQ_START_TOKEN; } static void *ip6mr_vif_seq_next(struct seq_file *seq, void *v, loff_t *pos) { struct ipmr_vif_iter *iter = seq->private; struct net *net = seq_file_net(seq); struct mr6_table *mrt = iter->mrt; ++*pos; if (v == SEQ_START_TOKEN) return ip6mr_vif_seq_idx(net, iter, 0); while (++iter->ct < mrt->maxvif) { if (!MIF_EXISTS(mrt, iter->ct)) continue; return &mrt->vif6_table[iter->ct]; } return NULL; } static void ip6mr_vif_seq_stop(struct seq_file *seq, void *v) __releases(mrt_lock) { read_unlock(&mrt_lock); } static int ip6mr_vif_seq_show(struct seq_file *seq, void *v) { struct ipmr_vif_iter *iter = seq->private; struct mr6_table *mrt = iter->mrt; if (v == SEQ_START_TOKEN) { seq_puts(seq, "Interface BytesIn PktsIn BytesOut PktsOut Flags\n"); } else { const struct mif_device *vif = v; const char *name = vif->dev ? vif->dev->name : "none"; seq_printf(seq, "%2td %-10s %8ld %7ld %8ld %7ld %05X\n", vif - mrt->vif6_table, name, vif->bytes_in, vif->pkt_in, vif->bytes_out, vif->pkt_out, vif->flags); } return 0; } static const struct seq_operations ip6mr_vif_seq_ops = { .start = ip6mr_vif_seq_start, .next = ip6mr_vif_seq_next, .stop = ip6mr_vif_seq_stop, .show = ip6mr_vif_seq_show, }; static int ip6mr_vif_open(struct inode *inode, struct file *file) { return seq_open_net(inode, file, &ip6mr_vif_seq_ops, sizeof(struct ipmr_vif_iter)); } static const struct file_operations ip6mr_vif_fops = { .owner = THIS_MODULE, .open = ip6mr_vif_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release_net, }; static void *ipmr_mfc_seq_start(struct seq_file *seq, loff_t *pos) { struct ipmr_mfc_iter *it = seq->private; struct net *net = seq_file_net(seq); struct mr6_table *mrt; mrt = ip6mr_get_table(net, RT6_TABLE_DFLT); if (!mrt) return ERR_PTR(-ENOENT); it->mrt = mrt; return *pos ? ipmr_mfc_seq_idx(net, seq->private, *pos - 1) : SEQ_START_TOKEN; } static void *ipmr_mfc_seq_next(struct seq_file *seq, void *v, loff_t *pos) { struct mfc6_cache *mfc = v; struct ipmr_mfc_iter *it = seq->private; struct net *net = seq_file_net(seq); struct mr6_table *mrt = it->mrt; ++*pos; if (v == SEQ_START_TOKEN) return ipmr_mfc_seq_idx(net, seq->private, 0); if (mfc->list.next != it->cache) return list_entry(mfc->list.next, struct mfc6_cache, list); if (it->cache == &mrt->mfc6_unres_queue) goto end_of_list; BUG_ON(it->cache != &mrt->mfc6_cache_array[it->ct]); while (++it->ct < MFC6_LINES) { it->cache = &mrt->mfc6_cache_array[it->ct]; if (list_empty(it->cache)) continue; return list_first_entry(it->cache, struct mfc6_cache, list); } /* exhausted cache_array, show unresolved */ read_unlock(&mrt_lock); it->cache = &mrt->mfc6_unres_queue; it->ct = 0; spin_lock_bh(&mfc_unres_lock); if (!list_empty(it->cache)) return list_first_entry(it->cache, struct mfc6_cache, list); end_of_list: spin_unlock_bh(&mfc_unres_lock); it->cache = NULL; return NULL; } static void ipmr_mfc_seq_stop(struct seq_file *seq, void *v) { struct ipmr_mfc_iter *it = seq->private; struct mr6_table *mrt = it->mrt; if (it->cache == &mrt->mfc6_unres_queue) spin_unlock_bh(&mfc_unres_lock); else if (it->cache == &mrt->mfc6_cache_array[it->ct]) read_unlock(&mrt_lock); } static int ipmr_mfc_seq_show(struct seq_file *seq, void *v) { int n; if (v == SEQ_START_TOKEN) { seq_puts(seq, "Group " "Origin " "Iif Pkts Bytes Wrong Oifs\n"); } else { const struct mfc6_cache *mfc = v; const struct ipmr_mfc_iter *it = seq->private; struct mr6_table *mrt = it->mrt; seq_printf(seq, "%pI6 %pI6 %-3hd", &mfc->mf6c_mcastgrp, &mfc->mf6c_origin, mfc->mf6c_parent); if (it->cache != &mrt->mfc6_unres_queue) { seq_printf(seq, " %8lu %8lu %8lu", mfc->mfc_un.res.pkt, mfc->mfc_un.res.bytes, mfc->mfc_un.res.wrong_if); for (n = mfc->mfc_un.res.minvif; n < mfc->mfc_un.res.maxvif; n++) { if (MIF_EXISTS(mrt, n) && mfc->mfc_un.res.ttls[n] < 255) seq_printf(seq, " %2d:%-3d", n, mfc->mfc_un.res.ttls[n]); } } else { /* unresolved mfc_caches don't contain * pkt, bytes and wrong_if values */ seq_printf(seq, " %8lu %8lu %8lu", 0ul, 0ul, 0ul); } seq_putc(seq, '\n'); } return 0; } static const struct seq_operations ipmr_mfc_seq_ops = { .start = ipmr_mfc_seq_start, .next = ipmr_mfc_seq_next, .stop = ipmr_mfc_seq_stop, .show = ipmr_mfc_seq_show, }; static int ipmr_mfc_open(struct inode *inode, struct file *file) { return seq_open_net(inode, file, &ipmr_mfc_seq_ops, sizeof(struct ipmr_mfc_iter)); } static const struct file_operations ip6mr_mfc_fops = { .owner = THIS_MODULE, .open = ipmr_mfc_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release_net, }; #endif #ifdef CONFIG_IPV6_PIMSM_V2 static int pim6_rcv(struct sk_buff *skb) { struct pimreghdr *pim; struct ipv6hdr *encap; struct net_device *reg_dev = NULL; struct net *net = dev_net(skb->dev); struct mr6_table *mrt; struct flowi6 fl6 = { .flowi6_iif = skb->dev->ifindex, .flowi6_mark = skb->mark, }; int reg_vif_num; if (!pskb_may_pull(skb, sizeof(*pim) + sizeof(*encap))) goto drop; pim = (struct pimreghdr *)skb_transport_header(skb); if (pim->type != ((PIM_VERSION << 4) | PIM_TYPE_REGISTER) || (pim->flags & PIM_NULL_REGISTER) || (csum_ipv6_magic(&ipv6_hdr(skb)->saddr, &ipv6_hdr(skb)->daddr, sizeof(*pim), IPPROTO_PIM, csum_partial((void *)pim, sizeof(*pim), 0)) && csum_fold(skb_checksum(skb, 0, skb->len, 0)))) goto drop; /* check if the inner packet is destined to mcast group */ encap = (struct ipv6hdr *)(skb_transport_header(skb) + sizeof(*pim)); if (!ipv6_addr_is_multicast(&encap->daddr) || encap->payload_len == 0 || ntohs(encap->payload_len) + sizeof(*pim) > skb->len) goto drop; if (ip6mr_fib_lookup(net, &fl6, &mrt) < 0) goto drop; reg_vif_num = mrt->mroute_reg_vif_num; read_lock(&mrt_lock); if (reg_vif_num >= 0) reg_dev = mrt->vif6_table[reg_vif_num].dev; if (reg_dev) dev_hold(reg_dev); read_unlock(&mrt_lock); if (!reg_dev) goto drop; skb->mac_header = skb->network_header; skb_pull(skb, (u8 *)encap - skb->data); skb_reset_network_header(skb); skb->protocol = htons(ETH_P_IPV6); skb->ip_summed = CHECKSUM_NONE; skb_tunnel_rx(skb, reg_dev, dev_net(reg_dev)); netif_rx(skb); dev_put(reg_dev); return 0; drop: kfree_skb(skb); return 0; } static const struct inet6_protocol pim6_protocol = { .handler = pim6_rcv, }; /* Service routines creating virtual interfaces: PIMREG */ static netdev_tx_t reg_vif_xmit(struct sk_buff *skb, struct net_device *dev) { struct net *net = dev_net(dev); struct mr6_table *mrt; struct flowi6 fl6 = { .flowi6_oif = dev->ifindex, .flowi6_iif = skb->skb_iif ? : LOOPBACK_IFINDEX, .flowi6_mark = skb->mark, }; int err; err = ip6mr_fib_lookup(net, &fl6, &mrt); if (err < 0) { kfree_skb(skb); return err; } read_lock(&mrt_lock); dev->stats.tx_bytes += skb->len; dev->stats.tx_packets++; ip6mr_cache_report(mrt, skb, mrt->mroute_reg_vif_num, MRT6MSG_WHOLEPKT); read_unlock(&mrt_lock); kfree_skb(skb); return NETDEV_TX_OK; } static int reg_vif_get_iflink(const struct net_device *dev) { return 0; } static const struct net_device_ops reg_vif_netdev_ops = { .ndo_start_xmit = reg_vif_xmit, .ndo_get_iflink = reg_vif_get_iflink, }; static void reg_vif_setup(struct net_device *dev) { dev->type = ARPHRD_PIMREG; dev->mtu = 1500 - sizeof(struct ipv6hdr) - 8; dev->flags = IFF_NOARP; dev->netdev_ops = &reg_vif_netdev_ops; dev->destructor = free_netdev; dev->features |= NETIF_F_NETNS_LOCAL; } static struct net_device *ip6mr_reg_vif(struct net *net, struct mr6_table *mrt) { struct net_device *dev; char name[IFNAMSIZ]; if (mrt->id == RT6_TABLE_DFLT) sprintf(name, "pim6reg"); else sprintf(name, "pim6reg%u", mrt->id); dev = alloc_netdev(0, name, NET_NAME_UNKNOWN, reg_vif_setup); if (!dev) return NULL; dev_net_set(dev, net); if (register_netdevice(dev)) { free_netdev(dev); return NULL; } if (dev_open(dev)) goto failure; dev_hold(dev); return dev; failure: unregister_netdevice(dev); return NULL; } #endif /* * Delete a VIF entry */ static int mif6_delete(struct mr6_table *mrt, int vifi, struct list_head *head) { struct mif_device *v; struct net_device *dev; struct inet6_dev *in6_dev; if (vifi < 0 || vifi >= mrt->maxvif) return -EADDRNOTAVAIL; v = &mrt->vif6_table[vifi]; write_lock_bh(&mrt_lock); dev = v->dev; v->dev = NULL; if (!dev) { write_unlock_bh(&mrt_lock); return -EADDRNOTAVAIL; } #ifdef CONFIG_IPV6_PIMSM_V2 if (vifi == mrt->mroute_reg_vif_num) mrt->mroute_reg_vif_num = -1; #endif if (vifi + 1 == mrt->maxvif) { int tmp; for (tmp = vifi - 1; tmp >= 0; tmp--) { if (MIF_EXISTS(mrt, tmp)) break; } mrt->maxvif = tmp + 1; } write_unlock_bh(&mrt_lock); dev_set_allmulti(dev, -1); in6_dev = __in6_dev_get(dev); if (in6_dev) { in6_dev->cnf.mc_forwarding--; inet6_netconf_notify_devconf(dev_net(dev), NETCONFA_MC_FORWARDING, dev->ifindex, &in6_dev->cnf); } if (v->flags & MIFF_REGISTER) unregister_netdevice_queue(dev, head); dev_put(dev); return 0; } static inline void ip6mr_cache_free(struct mfc6_cache *c) { kmem_cache_free(mrt_cachep, c); } /* Destroy an unresolved cache entry, killing queued skbs and reporting error to netlink readers. */ static void ip6mr_destroy_unres(struct mr6_table *mrt, struct mfc6_cache *c) { struct net *net = read_pnet(&mrt->net); struct sk_buff *skb; atomic_dec(&mrt->cache_resolve_queue_len); while ((skb = skb_dequeue(&c->mfc_un.unres.unresolved)) != NULL) { if (ipv6_hdr(skb)->version == 0) { struct nlmsghdr *nlh = (struct nlmsghdr *)skb_pull(skb, sizeof(struct ipv6hdr)); nlh->nlmsg_type = NLMSG_ERROR; nlh->nlmsg_len = nlmsg_msg_size(sizeof(struct nlmsgerr)); skb_trim(skb, nlh->nlmsg_len); ((struct nlmsgerr *)nlmsg_data(nlh))->error = -ETIMEDOUT; rtnl_unicast(skb, net, NETLINK_CB(skb).portid); } else kfree_skb(skb); } ip6mr_cache_free(c); } /* Timer process for all the unresolved queue. */ static void ipmr_do_expire_process(struct mr6_table *mrt) { unsigned long now = jiffies; unsigned long expires = 10 * HZ; struct mfc6_cache *c, *next; list_for_each_entry_safe(c, next, &mrt->mfc6_unres_queue, list) { if (time_after(c->mfc_un.unres.expires, now)) { /* not yet... */ unsigned long interval = c->mfc_un.unres.expires - now; if (interval < expires) expires = interval; continue; } list_del(&c->list); mr6_netlink_event(mrt, c, RTM_DELROUTE); ip6mr_destroy_unres(mrt, c); } if (!list_empty(&mrt->mfc6_unres_queue)) mod_timer(&mrt->ipmr_expire_timer, jiffies + expires); } static void ipmr_expire_process(unsigned long arg) { struct mr6_table *mrt = (struct mr6_table *)arg; if (!spin_trylock(&mfc_unres_lock)) { mod_timer(&mrt->ipmr_expire_timer, jiffies + 1); return; } if (!list_empty(&mrt->mfc6_unres_queue)) ipmr_do_expire_process(mrt); spin_unlock(&mfc_unres_lock); } /* Fill oifs list. It is called under write locked mrt_lock. */ static void ip6mr_update_thresholds(struct mr6_table *mrt, struct mfc6_cache *cache, unsigned char *ttls) { int vifi; cache->mfc_un.res.minvif = MAXMIFS; cache->mfc_un.res.maxvif = 0; memset(cache->mfc_un.res.ttls, 255, MAXMIFS); for (vifi = 0; vifi < mrt->maxvif; vifi++) { if (MIF_EXISTS(mrt, vifi) && ttls[vifi] && ttls[vifi] < 255) { cache->mfc_un.res.ttls[vifi] = ttls[vifi]; if (cache->mfc_un.res.minvif > vifi) cache->mfc_un.res.minvif = vifi; if (cache->mfc_un.res.maxvif <= vifi) cache->mfc_un.res.maxvif = vifi + 1; } } cache->mfc_un.res.lastuse = jiffies; } static int mif6_add(struct net *net, struct mr6_table *mrt, struct mif6ctl *vifc, int mrtsock) { int vifi = vifc->mif6c_mifi; struct mif_device *v = &mrt->vif6_table[vifi]; struct net_device *dev; struct inet6_dev *in6_dev; int err; /* Is vif busy ? */ if (MIF_EXISTS(mrt, vifi)) return -EADDRINUSE; switch (vifc->mif6c_flags) { #ifdef CONFIG_IPV6_PIMSM_V2 case MIFF_REGISTER: /* * Special Purpose VIF in PIM * All the packets will be sent to the daemon */ if (mrt->mroute_reg_vif_num >= 0) return -EADDRINUSE; dev = ip6mr_reg_vif(net, mrt); if (!dev) return -ENOBUFS; err = dev_set_allmulti(dev, 1); if (err) { unregister_netdevice(dev); dev_put(dev); return err; } break; #endif case 0: dev = dev_get_by_index(net, vifc->mif6c_pifi); if (!dev) return -EADDRNOTAVAIL; err = dev_set_allmulti(dev, 1); if (err) { dev_put(dev); return err; } break; default: return -EINVAL; } in6_dev = __in6_dev_get(dev); if (in6_dev) { in6_dev->cnf.mc_forwarding++; inet6_netconf_notify_devconf(dev_net(dev), NETCONFA_MC_FORWARDING, dev->ifindex, &in6_dev->cnf); } /* * Fill in the VIF structures */ v->rate_limit = vifc->vifc_rate_limit; v->flags = vifc->mif6c_flags; if (!mrtsock) v->flags |= VIFF_STATIC; v->threshold = vifc->vifc_threshold; v->bytes_in = 0; v->bytes_out = 0; v->pkt_in = 0; v->pkt_out = 0; v->link = dev->ifindex; if (v->flags & MIFF_REGISTER) v->link = dev_get_iflink(dev); /* And finish update writing critical data */ write_lock_bh(&mrt_lock); v->dev = dev; #ifdef CONFIG_IPV6_PIMSM_V2 if (v->flags & MIFF_REGISTER) mrt->mroute_reg_vif_num = vifi; #endif if (vifi + 1 > mrt->maxvif) mrt->maxvif = vifi + 1; write_unlock_bh(&mrt_lock); return 0; } static struct mfc6_cache *ip6mr_cache_find(struct mr6_table *mrt, const struct in6_addr *origin, const struct in6_addr *mcastgrp) { int line = MFC6_HASH(mcastgrp, origin); struct mfc6_cache *c; list_for_each_entry(c, &mrt->mfc6_cache_array[line], list) { if (ipv6_addr_equal(&c->mf6c_origin, origin) && ipv6_addr_equal(&c->mf6c_mcastgrp, mcastgrp)) return c; } return NULL; } /* Look for a (*,*,oif) entry */ static struct mfc6_cache *ip6mr_cache_find_any_parent(struct mr6_table *mrt, mifi_t mifi) { int line = MFC6_HASH(&in6addr_any, &in6addr_any); struct mfc6_cache *c; list_for_each_entry(c, &mrt->mfc6_cache_array[line], list) if (ipv6_addr_any(&c->mf6c_origin) && ipv6_addr_any(&c->mf6c_mcastgrp) && (c->mfc_un.res.ttls[mifi] < 255)) return c; return NULL; } /* Look for a (*,G) entry */ static struct mfc6_cache *ip6mr_cache_find_any(struct mr6_table *mrt, struct in6_addr *mcastgrp, mifi_t mifi) { int line = MFC6_HASH(mcastgrp, &in6addr_any); struct mfc6_cache *c, *proxy; if (ipv6_addr_any(mcastgrp)) goto skip; list_for_each_entry(c, &mrt->mfc6_cache_array[line], list) if (ipv6_addr_any(&c->mf6c_origin) && ipv6_addr_equal(&c->mf6c_mcastgrp, mcastgrp)) { if (c->mfc_un.res.ttls[mifi] < 255) return c; /* It's ok if the mifi is part of the static tree */ proxy = ip6mr_cache_find_any_parent(mrt, c->mf6c_parent); if (proxy && proxy->mfc_un.res.ttls[mifi] < 255) return c; } skip: return ip6mr_cache_find_any_parent(mrt, mifi); } /* * Allocate a multicast cache entry */ static struct mfc6_cache *ip6mr_cache_alloc(void) { struct mfc6_cache *c = kmem_cache_zalloc(mrt_cachep, GFP_KERNEL); if (!c) return NULL; c->mfc_un.res.last_assert = jiffies - MFC_ASSERT_THRESH - 1; c->mfc_un.res.minvif = MAXMIFS; return c; } static struct mfc6_cache *ip6mr_cache_alloc_unres(void) { struct mfc6_cache *c = kmem_cache_zalloc(mrt_cachep, GFP_ATOMIC); if (!c) return NULL; skb_queue_head_init(&c->mfc_un.unres.unresolved); c->mfc_un.unres.expires = jiffies + 10 * HZ; return c; } /* * A cache entry has gone into a resolved state from queued */ static void ip6mr_cache_resolve(struct net *net, struct mr6_table *mrt, struct mfc6_cache *uc, struct mfc6_cache *c) { struct sk_buff *skb; /* * Play the pending entries through our router */ while ((skb = __skb_dequeue(&uc->mfc_un.unres.unresolved))) { if (ipv6_hdr(skb)->version == 0) { struct nlmsghdr *nlh = (struct nlmsghdr *)skb_pull(skb, sizeof(struct ipv6hdr)); if (__ip6mr_fill_mroute(mrt, skb, c, nlmsg_data(nlh)) > 0) { nlh->nlmsg_len = skb_tail_pointer(skb) - (u8 *)nlh; } else { nlh->nlmsg_type = NLMSG_ERROR; nlh->nlmsg_len = nlmsg_msg_size(sizeof(struct nlmsgerr)); skb_trim(skb, nlh->nlmsg_len); ((struct nlmsgerr *)nlmsg_data(nlh))->error = -EMSGSIZE; } rtnl_unicast(skb, net, NETLINK_CB(skb).portid); } else ip6_mr_forward(net, mrt, skb, c); } } /* * Bounce a cache query up to pim6sd. We could use netlink for this but pim6sd * expects the following bizarre scheme. * * Called under mrt_lock. */ static int ip6mr_cache_report(struct mr6_table *mrt, struct sk_buff *pkt, mifi_t mifi, int assert) { struct sk_buff *skb; struct mrt6msg *msg; int ret; #ifdef CONFIG_IPV6_PIMSM_V2 if (assert == MRT6MSG_WHOLEPKT) skb = skb_realloc_headroom(pkt, -skb_network_offset(pkt) +sizeof(*msg)); else #endif skb = alloc_skb(sizeof(struct ipv6hdr) + sizeof(*msg), GFP_ATOMIC); if (!skb) return -ENOBUFS; /* I suppose that internal messages * do not require checksums */ skb->ip_summed = CHECKSUM_UNNECESSARY; #ifdef CONFIG_IPV6_PIMSM_V2 if (assert == MRT6MSG_WHOLEPKT) { /* Ugly, but we have no choice with this interface. Duplicate old header, fix length etc. And all this only to mangle msg->im6_msgtype and to set msg->im6_mbz to "mbz" :-) */ skb_push(skb, -skb_network_offset(pkt)); skb_push(skb, sizeof(*msg)); skb_reset_transport_header(skb); msg = (struct mrt6msg *)skb_transport_header(skb); msg->im6_mbz = 0; msg->im6_msgtype = MRT6MSG_WHOLEPKT; msg->im6_mif = mrt->mroute_reg_vif_num; msg->im6_pad = 0; msg->im6_src = ipv6_hdr(pkt)->saddr; msg->im6_dst = ipv6_hdr(pkt)->daddr; skb->ip_summed = CHECKSUM_UNNECESSARY; } else #endif { /* * Copy the IP header */ skb_put(skb, sizeof(struct ipv6hdr)); skb_reset_network_header(skb); skb_copy_to_linear_data(skb, ipv6_hdr(pkt), sizeof(struct ipv6hdr)); /* * Add our header */ skb_put(skb, sizeof(*msg)); skb_reset_transport_header(skb); msg = (struct mrt6msg *)skb_transport_header(skb); msg->im6_mbz = 0; msg->im6_msgtype = assert; msg->im6_mif = mifi; msg->im6_pad = 0; msg->im6_src = ipv6_hdr(pkt)->saddr; msg->im6_dst = ipv6_hdr(pkt)->daddr; skb_dst_set(skb, dst_clone(skb_dst(pkt))); skb->ip_summed = CHECKSUM_UNNECESSARY; } if (!mrt->mroute6_sk) { kfree_skb(skb); return -EINVAL; } /* * Deliver to user space multicast routing algorithms */ ret = sock_queue_rcv_skb(mrt->mroute6_sk, skb); if (ret < 0) { net_warn_ratelimited("mroute6: pending queue full, dropping entries\n"); kfree_skb(skb); } return ret; } /* * Queue a packet for resolution. It gets locked cache entry! */ static int ip6mr_cache_unresolved(struct mr6_table *mrt, mifi_t mifi, struct sk_buff *skb) { bool found = false; int err; struct mfc6_cache *c; spin_lock_bh(&mfc_unres_lock); list_for_each_entry(c, &mrt->mfc6_unres_queue, list) { if (ipv6_addr_equal(&c->mf6c_mcastgrp, &ipv6_hdr(skb)->daddr) && ipv6_addr_equal(&c->mf6c_origin, &ipv6_hdr(skb)->saddr)) { found = true; break; } } if (!found) { /* * Create a new entry if allowable */ if (atomic_read(&mrt->cache_resolve_queue_len) >= 10 || (c = ip6mr_cache_alloc_unres()) == NULL) { spin_unlock_bh(&mfc_unres_lock); kfree_skb(skb); return -ENOBUFS; } /* * Fill in the new cache entry */ c->mf6c_parent = -1; c->mf6c_origin = ipv6_hdr(skb)->saddr; c->mf6c_mcastgrp = ipv6_hdr(skb)->daddr; /* * Reflect first query at pim6sd */ err = ip6mr_cache_report(mrt, skb, mifi, MRT6MSG_NOCACHE); if (err < 0) { /* If the report failed throw the cache entry out - Brad Parker */ spin_unlock_bh(&mfc_unres_lock); ip6mr_cache_free(c); kfree_skb(skb); return err; } atomic_inc(&mrt->cache_resolve_queue_len); list_add(&c->list, &mrt->mfc6_unres_queue); mr6_netlink_event(mrt, c, RTM_NEWROUTE); ipmr_do_expire_process(mrt); } /* * See if we can append the packet */ if (c->mfc_un.unres.unresolved.qlen > 3) { kfree_skb(skb); err = -ENOBUFS; } else { skb_queue_tail(&c->mfc_un.unres.unresolved, skb); err = 0; } spin_unlock_bh(&mfc_unres_lock); return err; } /* * MFC6 cache manipulation by user space */ static int ip6mr_mfc_delete(struct mr6_table *mrt, struct mf6cctl *mfc, int parent) { int line; struct mfc6_cache *c, *next; line = MFC6_HASH(&mfc->mf6cc_mcastgrp.sin6_addr, &mfc->mf6cc_origin.sin6_addr); list_for_each_entry_safe(c, next, &mrt->mfc6_cache_array[line], list) { if (ipv6_addr_equal(&c->mf6c_origin, &mfc->mf6cc_origin.sin6_addr) && ipv6_addr_equal(&c->mf6c_mcastgrp, &mfc->mf6cc_mcastgrp.sin6_addr) && (parent == -1 || parent == c->mf6c_parent)) { write_lock_bh(&mrt_lock); list_del(&c->list); write_unlock_bh(&mrt_lock); mr6_netlink_event(mrt, c, RTM_DELROUTE); ip6mr_cache_free(c); return 0; } } return -ENOENT; } static int ip6mr_device_event(struct notifier_block *this, unsigned long event, void *ptr) { struct net_device *dev = netdev_notifier_info_to_dev(ptr); struct net *net = dev_net(dev); struct mr6_table *mrt; struct mif_device *v; int ct; LIST_HEAD(list); if (event != NETDEV_UNREGISTER) return NOTIFY_DONE; ip6mr_for_each_table(mrt, net) { v = &mrt->vif6_table[0]; for (ct = 0; ct < mrt->maxvif; ct++, v++) { if (v->dev == dev) mif6_delete(mrt, ct, &list); } } unregister_netdevice_many(&list); return NOTIFY_DONE; } static struct notifier_block ip6_mr_notifier = { .notifier_call = ip6mr_device_event }; /* * Setup for IP multicast routing */ static int __net_init ip6mr_net_init(struct net *net) { int err; err = ip6mr_rules_init(net); if (err < 0) goto fail; #ifdef CONFIG_PROC_FS err = -ENOMEM; if (!proc_create("ip6_mr_vif", 0, net->proc_net, &ip6mr_vif_fops)) goto proc_vif_fail; if (!proc_create("ip6_mr_cache", 0, net->proc_net, &ip6mr_mfc_fops)) goto proc_cache_fail; #endif return 0; #ifdef CONFIG_PROC_FS proc_cache_fail: remove_proc_entry("ip6_mr_vif", net->proc_net); proc_vif_fail: ip6mr_rules_exit(net); #endif fail: return err; } static void __net_exit ip6mr_net_exit(struct net *net) { #ifdef CONFIG_PROC_FS remove_proc_entry("ip6_mr_cache", net->proc_net); remove_proc_entry("ip6_mr_vif", net->proc_net); #endif ip6mr_rules_exit(net); } static struct pernet_operations ip6mr_net_ops = { .init = ip6mr_net_init, .exit = ip6mr_net_exit, }; int __init ip6_mr_init(void) { int err; mrt_cachep = kmem_cache_create("ip6_mrt_cache", sizeof(struct mfc6_cache), 0, SLAB_HWCACHE_ALIGN, NULL); if (!mrt_cachep) return -ENOMEM; err = register_pernet_subsys(&ip6mr_net_ops); if (err) goto reg_pernet_fail; err = register_netdevice_notifier(&ip6_mr_notifier); if (err) goto reg_notif_fail; #ifdef CONFIG_IPV6_PIMSM_V2 if (inet6_add_protocol(&pim6_protocol, IPPROTO_PIM) < 0) { pr_err("%s: can't add PIM protocol\n", __func__); err = -EAGAIN; goto add_proto_fail; } #endif rtnl_register(RTNL_FAMILY_IP6MR, RTM_GETROUTE, NULL, ip6mr_rtm_dumproute, NULL); return 0; #ifdef CONFIG_IPV6_PIMSM_V2 add_proto_fail: unregister_netdevice_notifier(&ip6_mr_notifier); #endif reg_notif_fail: unregister_pernet_subsys(&ip6mr_net_ops); reg_pernet_fail: kmem_cache_destroy(mrt_cachep); return err; } void ip6_mr_cleanup(void) { rtnl_unregister(RTNL_FAMILY_IP6MR, RTM_GETROUTE); #ifdef CONFIG_IPV6_PIMSM_V2 inet6_del_protocol(&pim6_protocol, IPPROTO_PIM); #endif unregister_netdevice_notifier(&ip6_mr_notifier); unregister_pernet_subsys(&ip6mr_net_ops); kmem_cache_destroy(mrt_cachep); } static int ip6mr_mfc_add(struct net *net, struct mr6_table *mrt, struct mf6cctl *mfc, int mrtsock, int parent) { bool found = false; int line; struct mfc6_cache *uc, *c; unsigned char ttls[MAXMIFS]; int i; if (mfc->mf6cc_parent >= MAXMIFS) return -ENFILE; memset(ttls, 255, MAXMIFS); for (i = 0; i < MAXMIFS; i++) { if (IF_ISSET(i, &mfc->mf6cc_ifset)) ttls[i] = 1; } line = MFC6_HASH(&mfc->mf6cc_mcastgrp.sin6_addr, &mfc->mf6cc_origin.sin6_addr); list_for_each_entry(c, &mrt->mfc6_cache_array[line], list) { if (ipv6_addr_equal(&c->mf6c_origin, &mfc->mf6cc_origin.sin6_addr) && ipv6_addr_equal(&c->mf6c_mcastgrp, &mfc->mf6cc_mcastgrp.sin6_addr) && (parent == -1 || parent == mfc->mf6cc_parent)) { found = true; break; } } if (found) { write_lock_bh(&mrt_lock); c->mf6c_parent = mfc->mf6cc_parent; ip6mr_update_thresholds(mrt, c, ttls); if (!mrtsock) c->mfc_flags |= MFC_STATIC; write_unlock_bh(&mrt_lock); mr6_netlink_event(mrt, c, RTM_NEWROUTE); return 0; } if (!ipv6_addr_any(&mfc->mf6cc_mcastgrp.sin6_addr) && !ipv6_addr_is_multicast(&mfc->mf6cc_mcastgrp.sin6_addr)) return -EINVAL; c = ip6mr_cache_alloc(); if (!c) return -ENOMEM; c->mf6c_origin = mfc->mf6cc_origin.sin6_addr; c->mf6c_mcastgrp = mfc->mf6cc_mcastgrp.sin6_addr; c->mf6c_parent = mfc->mf6cc_parent; ip6mr_update_thresholds(mrt, c, ttls); if (!mrtsock) c->mfc_flags |= MFC_STATIC; write_lock_bh(&mrt_lock); list_add(&c->list, &mrt->mfc6_cache_array[line]); write_unlock_bh(&mrt_lock); /* * Check to see if we resolved a queued list. If so we * need to send on the frames and tidy up. */ found = false; spin_lock_bh(&mfc_unres_lock); list_for_each_entry(uc, &mrt->mfc6_unres_queue, list) { if (ipv6_addr_equal(&uc->mf6c_origin, &c->mf6c_origin) && ipv6_addr_equal(&uc->mf6c_mcastgrp, &c->mf6c_mcastgrp)) { list_del(&uc->list); atomic_dec(&mrt->cache_resolve_queue_len); found = true; break; } } if (list_empty(&mrt->mfc6_unres_queue)) del_timer(&mrt->ipmr_expire_timer); spin_unlock_bh(&mfc_unres_lock); if (found) { ip6mr_cache_resolve(net, mrt, uc, c); ip6mr_cache_free(uc); } mr6_netlink_event(mrt, c, RTM_NEWROUTE); return 0; } /* * Close the multicast socket, and clear the vif tables etc */ static void mroute_clean_tables(struct mr6_table *mrt, bool all) { int i; LIST_HEAD(list); struct mfc6_cache *c, *next; /* * Shut down all active vif entries */ for (i = 0; i < mrt->maxvif; i++) { if (!all && (mrt->vif6_table[i].flags & VIFF_STATIC)) continue; mif6_delete(mrt, i, &list); } unregister_netdevice_many(&list); /* * Wipe the cache */ for (i = 0; i < MFC6_LINES; i++) { list_for_each_entry_safe(c, next, &mrt->mfc6_cache_array[i], list) { if (!all && (c->mfc_flags & MFC_STATIC)) continue; write_lock_bh(&mrt_lock); list_del(&c->list); write_unlock_bh(&mrt_lock); mr6_netlink_event(mrt, c, RTM_DELROUTE); ip6mr_cache_free(c); } } if (atomic_read(&mrt->cache_resolve_queue_len) != 0) { spin_lock_bh(&mfc_unres_lock); list_for_each_entry_safe(c, next, &mrt->mfc6_unres_queue, list) { list_del(&c->list); mr6_netlink_event(mrt, c, RTM_DELROUTE); ip6mr_destroy_unres(mrt, c); } spin_unlock_bh(&mfc_unres_lock); } } static int ip6mr_sk_init(struct mr6_table *mrt, struct sock *sk) { int err = 0; struct net *net = sock_net(sk); rtnl_lock(); write_lock_bh(&mrt_lock); if (likely(mrt->mroute6_sk == NULL)) { mrt->mroute6_sk = sk; net->ipv6.devconf_all->mc_forwarding++; } else { err = -EADDRINUSE; } write_unlock_bh(&mrt_lock); if (!err) inet6_netconf_notify_devconf(net, NETCONFA_MC_FORWARDING, NETCONFA_IFINDEX_ALL, net->ipv6.devconf_all); rtnl_unlock(); return err; } int ip6mr_sk_done(struct sock *sk) { int err = -EACCES; struct net *net = sock_net(sk); struct mr6_table *mrt; rtnl_lock(); ip6mr_for_each_table(mrt, net) { if (sk == mrt->mroute6_sk) { write_lock_bh(&mrt_lock); mrt->mroute6_sk = NULL; net->ipv6.devconf_all->mc_forwarding--; write_unlock_bh(&mrt_lock); inet6_netconf_notify_devconf(net, NETCONFA_MC_FORWARDING, NETCONFA_IFINDEX_ALL, net->ipv6.devconf_all); mroute_clean_tables(mrt, false); err = 0; break; } } rtnl_unlock(); return err; } struct sock *mroute6_socket(struct net *net, struct sk_buff *skb) { struct mr6_table *mrt; struct flowi6 fl6 = { .flowi6_iif = skb->skb_iif ? : LOOPBACK_IFINDEX, .flowi6_oif = skb->dev->ifindex, .flowi6_mark = skb->mark, }; if (ip6mr_fib_lookup(net, &fl6, &mrt) < 0) return NULL; return mrt->mroute6_sk; } /* * Socket options and virtual interface manipulation. The whole * virtual interface system is a complete heap, but unfortunately * that's how BSD mrouted happens to think. Maybe one day with a proper * MOSPF/PIM router set up we can clean this up. */ int ip6_mroute_setsockopt(struct sock *sk, int optname, char __user *optval, unsigned int optlen) { int ret, parent = 0; struct mif6ctl vif; struct mf6cctl mfc; mifi_t mifi; struct net *net = sock_net(sk); struct mr6_table *mrt; if (sk->sk_type != SOCK_RAW || inet_sk(sk)->inet_num != IPPROTO_ICMPV6) return -EOPNOTSUPP; mrt = ip6mr_get_table(net, raw6_sk(sk)->ip6mr_table ? : RT6_TABLE_DFLT); if (!mrt) return -ENOENT; if (optname != MRT6_INIT) { if (sk != mrt->mroute6_sk && !ns_capable(net->user_ns, CAP_NET_ADMIN)) return -EACCES; } switch (optname) { case MRT6_INIT: if (optlen < sizeof(int)) return -EINVAL; return ip6mr_sk_init(mrt, sk); case MRT6_DONE: return ip6mr_sk_done(sk); case MRT6_ADD_MIF: if (optlen < sizeof(vif)) return -EINVAL; if (copy_from_user(&vif, optval, sizeof(vif))) return -EFAULT; if (vif.mif6c_mifi >= MAXMIFS) return -ENFILE; rtnl_lock(); ret = mif6_add(net, mrt, &vif, sk == mrt->mroute6_sk); rtnl_unlock(); return ret; case MRT6_DEL_MIF: if (optlen < sizeof(mifi_t)) return -EINVAL; if (copy_from_user(&mifi, optval, sizeof(mifi_t))) return -EFAULT; rtnl_lock(); ret = mif6_delete(mrt, mifi, NULL); rtnl_unlock(); return ret; /* * Manipulate the forwarding caches. These live * in a sort of kernel/user symbiosis. */ case MRT6_ADD_MFC: case MRT6_DEL_MFC: parent = -1; case MRT6_ADD_MFC_PROXY: case MRT6_DEL_MFC_PROXY: if (optlen < sizeof(mfc)) return -EINVAL; if (copy_from_user(&mfc, optval, sizeof(mfc))) return -EFAULT; if (parent == 0) parent = mfc.mf6cc_parent; rtnl_lock(); if (optname == MRT6_DEL_MFC || optname == MRT6_DEL_MFC_PROXY) ret = ip6mr_mfc_delete(mrt, &mfc, parent); else ret = ip6mr_mfc_add(net, mrt, &mfc, sk == mrt->mroute6_sk, parent); rtnl_unlock(); return ret; /* * Control PIM assert (to activate pim will activate assert) */ case MRT6_ASSERT: { int v; if (optlen != sizeof(v)) return -EINVAL; if (get_user(v, (int __user *)optval)) return -EFAULT; mrt->mroute_do_assert = v; return 0; } #ifdef CONFIG_IPV6_PIMSM_V2 case MRT6_PIM: { int v; if (optlen != sizeof(v)) return -EINVAL; if (get_user(v, (int __user *)optval)) return -EFAULT; v = !!v; rtnl_lock(); ret = 0; if (v != mrt->mroute_do_pim) { mrt->mroute_do_pim = v; mrt->mroute_do_assert = v; } rtnl_unlock(); return ret; } #endif #ifdef CONFIG_IPV6_MROUTE_MULTIPLE_TABLES case MRT6_TABLE: { u32 v; if (optlen != sizeof(u32)) return -EINVAL; if (get_user(v, (u32 __user *)optval)) return -EFAULT; /* "pim6reg%u" should not exceed 16 bytes (IFNAMSIZ) */ if (v != RT_TABLE_DEFAULT && v >= 100000000) return -EINVAL; if (sk == mrt->mroute6_sk) return -EBUSY; rtnl_lock(); ret = 0; if (!ip6mr_new_table(net, v)) ret = -ENOMEM; raw6_sk(sk)->ip6mr_table = v; rtnl_unlock(); return ret; } #endif /* * Spurious command, or MRT6_VERSION which you cannot * set. */ default: return -ENOPROTOOPT; } } /* * Getsock opt support for the multicast routing system. */ int ip6_mroute_getsockopt(struct sock *sk, int optname, char __user *optval, int __user *optlen) { int olr; int val; struct net *net = sock_net(sk); struct mr6_table *mrt; if (sk->sk_type != SOCK_RAW || inet_sk(sk)->inet_num != IPPROTO_ICMPV6) return -EOPNOTSUPP; mrt = ip6mr_get_table(net, raw6_sk(sk)->ip6mr_table ? : RT6_TABLE_DFLT); if (!mrt) return -ENOENT; switch (optname) { case MRT6_VERSION: val = 0x0305; break; #ifdef CONFIG_IPV6_PIMSM_V2 case MRT6_PIM: val = mrt->mroute_do_pim; break; #endif case MRT6_ASSERT: val = mrt->mroute_do_assert; break; default: return -ENOPROTOOPT; } if (get_user(olr, optlen)) return -EFAULT; olr = min_t(int, olr, sizeof(int)); if (olr < 0) return -EINVAL; if (put_user(olr, optlen)) return -EFAULT; if (copy_to_user(optval, &val, olr)) return -EFAULT; return 0; } /* * The IP multicast ioctl support routines. */ int ip6mr_ioctl(struct sock *sk, int cmd, void __user *arg) { struct sioc_sg_req6 sr; struct sioc_mif_req6 vr; struct mif_device *vif; struct mfc6_cache *c; struct net *net = sock_net(sk); struct mr6_table *mrt; mrt = ip6mr_get_table(net, raw6_sk(sk)->ip6mr_table ? : RT6_TABLE_DFLT); if (!mrt) return -ENOENT; switch (cmd) { case SIOCGETMIFCNT_IN6: if (copy_from_user(&vr, arg, sizeof(vr))) return -EFAULT; if (vr.mifi >= mrt->maxvif) return -EINVAL; read_lock(&mrt_lock); vif = &mrt->vif6_table[vr.mifi]; if (MIF_EXISTS(mrt, vr.mifi)) { vr.icount = vif->pkt_in; vr.ocount = vif->pkt_out; vr.ibytes = vif->bytes_in; vr.obytes = vif->bytes_out; read_unlock(&mrt_lock); if (copy_to_user(arg, &vr, sizeof(vr))) return -EFAULT; return 0; } read_unlock(&mrt_lock); return -EADDRNOTAVAIL; case SIOCGETSGCNT_IN6: if (copy_from_user(&sr, arg, sizeof(sr))) return -EFAULT; read_lock(&mrt_lock); c = ip6mr_cache_find(mrt, &sr.src.sin6_addr, &sr.grp.sin6_addr); if (c) { sr.pktcnt = c->mfc_un.res.pkt; sr.bytecnt = c->mfc_un.res.bytes; sr.wrong_if = c->mfc_un.res.wrong_if; read_unlock(&mrt_lock); if (copy_to_user(arg, &sr, sizeof(sr))) return -EFAULT; return 0; } read_unlock(&mrt_lock); return -EADDRNOTAVAIL; default: return -ENOIOCTLCMD; } } #ifdef CONFIG_COMPAT struct compat_sioc_sg_req6 { struct sockaddr_in6 src; struct sockaddr_in6 grp; compat_ulong_t pktcnt; compat_ulong_t bytecnt; compat_ulong_t wrong_if; }; struct compat_sioc_mif_req6 { mifi_t mifi; compat_ulong_t icount; compat_ulong_t ocount; compat_ulong_t ibytes; compat_ulong_t obytes; }; int ip6mr_compat_ioctl(struct sock *sk, unsigned int cmd, void __user *arg) { struct compat_sioc_sg_req6 sr; struct compat_sioc_mif_req6 vr; struct mif_device *vif; struct mfc6_cache *c; struct net *net = sock_net(sk); struct mr6_table *mrt; mrt = ip6mr_get_table(net, raw6_sk(sk)->ip6mr_table ? : RT6_TABLE_DFLT); if (!mrt) return -ENOENT; switch (cmd) { case SIOCGETMIFCNT_IN6: if (copy_from_user(&vr, arg, sizeof(vr))) return -EFAULT; if (vr.mifi >= mrt->maxvif) return -EINVAL; read_lock(&mrt_lock); vif = &mrt->vif6_table[vr.mifi]; if (MIF_EXISTS(mrt, vr.mifi)) { vr.icount = vif->pkt_in; vr.ocount = vif->pkt_out; vr.ibytes = vif->bytes_in; vr.obytes = vif->bytes_out; read_unlock(&mrt_lock); if (copy_to_user(arg, &vr, sizeof(vr))) return -EFAULT; return 0; } read_unlock(&mrt_lock); return -EADDRNOTAVAIL; case SIOCGETSGCNT_IN6: if (copy_from_user(&sr, arg, sizeof(sr))) return -EFAULT; read_lock(&mrt_lock); c = ip6mr_cache_find(mrt, &sr.src.sin6_addr, &sr.grp.sin6_addr); if (c) { sr.pktcnt = c->mfc_un.res.pkt; sr.bytecnt = c->mfc_un.res.bytes; sr.wrong_if = c->mfc_un.res.wrong_if; read_unlock(&mrt_lock); if (copy_to_user(arg, &sr, sizeof(sr))) return -EFAULT; return 0; } read_unlock(&mrt_lock); return -EADDRNOTAVAIL; default: return -ENOIOCTLCMD; } } #endif static inline int ip6mr_forward2_finish(struct net *net, struct sock *sk, struct sk_buff *skb) { __IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_OUTFORWDATAGRAMS); __IP6_ADD_STATS(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_OUTOCTETS, skb->len); return dst_output(net, sk, skb); } /* * Processing handlers for ip6mr_forward */ static int ip6mr_forward2(struct net *net, struct mr6_table *mrt, struct sk_buff *skb, struct mfc6_cache *c, int vifi) { struct ipv6hdr *ipv6h; struct mif_device *vif = &mrt->vif6_table[vifi]; struct net_device *dev; struct dst_entry *dst; struct flowi6 fl6; if (!vif->dev) goto out_free; #ifdef CONFIG_IPV6_PIMSM_V2 if (vif->flags & MIFF_REGISTER) { vif->pkt_out++; vif->bytes_out += skb->len; vif->dev->stats.tx_bytes += skb->len; vif->dev->stats.tx_packets++; ip6mr_cache_report(mrt, skb, vifi, MRT6MSG_WHOLEPKT); goto out_free; } #endif ipv6h = ipv6_hdr(skb); fl6 = (struct flowi6) { .flowi6_oif = vif->link, .daddr = ipv6h->daddr, }; dst = ip6_route_output(net, NULL, &fl6); if (dst->error) { dst_release(dst); goto out_free; } skb_dst_drop(skb); skb_dst_set(skb, dst); /* * RFC1584 teaches, that DVMRP/PIM router must deliver packets locally * not only before forwarding, but after forwarding on all output * interfaces. It is clear, if mrouter runs a multicasting * program, it should receive packets not depending to what interface * program is joined. * If we will not make it, the program will have to join on all * interfaces. On the other hand, multihoming host (or router, but * not mrouter) cannot join to more than one interface - it will * result in receiving multiple packets. */ dev = vif->dev; skb->dev = dev; vif->pkt_out++; vif->bytes_out += skb->len; /* We are about to write */ /* XXX: extension headers? */ if (skb_cow(skb, sizeof(*ipv6h) + LL_RESERVED_SPACE(dev))) goto out_free; ipv6h = ipv6_hdr(skb); ipv6h->hop_limit--; IP6CB(skb)->flags |= IP6SKB_FORWARDED; return NF_HOOK(NFPROTO_IPV6, NF_INET_FORWARD, net, NULL, skb, skb->dev, dev, ip6mr_forward2_finish); out_free: kfree_skb(skb); return 0; } static int ip6mr_find_vif(struct mr6_table *mrt, struct net_device *dev) { int ct; for (ct = mrt->maxvif - 1; ct >= 0; ct--) { if (mrt->vif6_table[ct].dev == dev) break; } return ct; } static void ip6_mr_forward(struct net *net, struct mr6_table *mrt, struct sk_buff *skb, struct mfc6_cache *cache) { int psend = -1; int vif, ct; int true_vifi = ip6mr_find_vif(mrt, skb->dev); vif = cache->mf6c_parent; cache->mfc_un.res.pkt++; cache->mfc_un.res.bytes += skb->len; cache->mfc_un.res.lastuse = jiffies; if (ipv6_addr_any(&cache->mf6c_origin) && true_vifi >= 0) { struct mfc6_cache *cache_proxy; /* For an (*,G) entry, we only check that the incoming * interface is part of the static tree. */ cache_proxy = ip6mr_cache_find_any_parent(mrt, vif); if (cache_proxy && cache_proxy->mfc_un.res.ttls[true_vifi] < 255) goto forward; } /* * Wrong interface: drop packet and (maybe) send PIM assert. */ if (mrt->vif6_table[vif].dev != skb->dev) { cache->mfc_un.res.wrong_if++; if (true_vifi >= 0 && mrt->mroute_do_assert && /* pimsm uses asserts, when switching from RPT to SPT, so that we cannot check that packet arrived on an oif. It is bad, but otherwise we would need to move pretty large chunk of pimd to kernel. Ough... --ANK */ (mrt->mroute_do_pim || cache->mfc_un.res.ttls[true_vifi] < 255) && time_after(jiffies, cache->mfc_un.res.last_assert + MFC_ASSERT_THRESH)) { cache->mfc_un.res.last_assert = jiffies; ip6mr_cache_report(mrt, skb, true_vifi, MRT6MSG_WRONGMIF); } goto dont_forward; } forward: mrt->vif6_table[vif].pkt_in++; mrt->vif6_table[vif].bytes_in += skb->len; /* * Forward the frame */ if (ipv6_addr_any(&cache->mf6c_origin) && ipv6_addr_any(&cache->mf6c_mcastgrp)) { if (true_vifi >= 0 && true_vifi != cache->mf6c_parent && ipv6_hdr(skb)->hop_limit > cache->mfc_un.res.ttls[cache->mf6c_parent]) { /* It's an (*,*) entry and the packet is not coming from * the upstream: forward the packet to the upstream * only. */ psend = cache->mf6c_parent; goto last_forward; } goto dont_forward; } for (ct = cache->mfc_un.res.maxvif - 1; ct >= cache->mfc_un.res.minvif; ct--) { /* For (*,G) entry, don't forward to the incoming interface */ if ((!ipv6_addr_any(&cache->mf6c_origin) || ct != true_vifi) && ipv6_hdr(skb)->hop_limit > cache->mfc_un.res.ttls[ct]) { if (psend != -1) { struct sk_buff *skb2 = skb_clone(skb, GFP_ATOMIC); if (skb2) ip6mr_forward2(net, mrt, skb2, cache, psend); } psend = ct; } } last_forward: if (psend != -1) { ip6mr_forward2(net, mrt, skb, cache, psend); return; } dont_forward: kfree_skb(skb); } /* * Multicast packets for forwarding arrive here */ int ip6_mr_input(struct sk_buff *skb) { struct mfc6_cache *cache; struct net *net = dev_net(skb->dev); struct mr6_table *mrt; struct flowi6 fl6 = { .flowi6_iif = skb->dev->ifindex, .flowi6_mark = skb->mark, }; int err; err = ip6mr_fib_lookup(net, &fl6, &mrt); if (err < 0) { kfree_skb(skb); return err; } read_lock(&mrt_lock); cache = ip6mr_cache_find(mrt, &ipv6_hdr(skb)->saddr, &ipv6_hdr(skb)->daddr); if (!cache) { int vif = ip6mr_find_vif(mrt, skb->dev); if (vif >= 0) cache = ip6mr_cache_find_any(mrt, &ipv6_hdr(skb)->daddr, vif); } /* * No usable cache entry */ if (!cache) { int vif; vif = ip6mr_find_vif(mrt, skb->dev); if (vif >= 0) { int err = ip6mr_cache_unresolved(mrt, vif, skb); read_unlock(&mrt_lock); return err; } read_unlock(&mrt_lock); kfree_skb(skb); return -ENODEV; } ip6_mr_forward(net, mrt, skb, cache); read_unlock(&mrt_lock); return 0; } static int __ip6mr_fill_mroute(struct mr6_table *mrt, struct sk_buff *skb, struct mfc6_cache *c, struct rtmsg *rtm) { struct rta_mfc_stats mfcs; struct nlattr *mp_attr; struct rtnexthop *nhp; unsigned long lastuse; int ct; /* If cache is unresolved, don't try to parse IIF and OIF */ if (c->mf6c_parent >= MAXMIFS) { rtm->rtm_flags |= RTNH_F_UNRESOLVED; return -ENOENT; } if (MIF_EXISTS(mrt, c->mf6c_parent) && nla_put_u32(skb, RTA_IIF, mrt->vif6_table[c->mf6c_parent].dev->ifindex) < 0) return -EMSGSIZE; mp_attr = nla_nest_start(skb, RTA_MULTIPATH); if (!mp_attr) return -EMSGSIZE; for (ct = c->mfc_un.res.minvif; ct < c->mfc_un.res.maxvif; ct++) { if (MIF_EXISTS(mrt, ct) && c->mfc_un.res.ttls[ct] < 255) { nhp = nla_reserve_nohdr(skb, sizeof(*nhp)); if (!nhp) { nla_nest_cancel(skb, mp_attr); return -EMSGSIZE; } nhp->rtnh_flags = 0; nhp->rtnh_hops = c->mfc_un.res.ttls[ct]; nhp->rtnh_ifindex = mrt->vif6_table[ct].dev->ifindex; nhp->rtnh_len = sizeof(*nhp); } } nla_nest_end(skb, mp_attr); lastuse = READ_ONCE(c->mfc_un.res.lastuse); lastuse = time_after_eq(jiffies, lastuse) ? jiffies - lastuse : 0; mfcs.mfcs_packets = c->mfc_un.res.pkt; mfcs.mfcs_bytes = c->mfc_un.res.bytes; mfcs.mfcs_wrong_if = c->mfc_un.res.wrong_if; if (nla_put_64bit(skb, RTA_MFC_STATS, sizeof(mfcs), &mfcs, RTA_PAD) || nla_put_u64_64bit(skb, RTA_EXPIRES, jiffies_to_clock_t(lastuse), RTA_PAD)) return -EMSGSIZE; rtm->rtm_type = RTN_MULTICAST; return 1; } int ip6mr_get_route(struct net *net, struct sk_buff *skb, struct rtmsg *rtm, u32 portid) { int err; struct mr6_table *mrt; struct mfc6_cache *cache; struct rt6_info *rt = (struct rt6_info *)skb_dst(skb); mrt = ip6mr_get_table(net, RT6_TABLE_DFLT); if (!mrt) return -ENOENT; read_lock(&mrt_lock); cache = ip6mr_cache_find(mrt, &rt->rt6i_src.addr, &rt->rt6i_dst.addr); if (!cache && skb->dev) { int vif = ip6mr_find_vif(mrt, skb->dev); if (vif >= 0) cache = ip6mr_cache_find_any(mrt, &rt->rt6i_dst.addr, vif); } if (!cache) { struct sk_buff *skb2; struct ipv6hdr *iph; struct net_device *dev; int vif; dev = skb->dev; if (!dev || (vif = ip6mr_find_vif(mrt, dev)) < 0) { read_unlock(&mrt_lock); return -ENODEV; } /* really correct? */ skb2 = alloc_skb(sizeof(struct ipv6hdr), GFP_ATOMIC); if (!skb2) { read_unlock(&mrt_lock); return -ENOMEM; } NETLINK_CB(skb2).portid = portid; skb_reset_transport_header(skb2); skb_put(skb2, sizeof(struct ipv6hdr)); skb_reset_network_header(skb2); iph = ipv6_hdr(skb2); iph->version = 0; iph->priority = 0; iph->flow_lbl[0] = 0; iph->flow_lbl[1] = 0; iph->flow_lbl[2] = 0; iph->payload_len = 0; iph->nexthdr = IPPROTO_NONE; iph->hop_limit = 0; iph->saddr = rt->rt6i_src.addr; iph->daddr = rt->rt6i_dst.addr; err = ip6mr_cache_unresolved(mrt, vif, skb2); read_unlock(&mrt_lock); return err; } if (rtm->rtm_flags & RTM_F_NOTIFY) cache->mfc_flags |= MFC_NOTIFY; err = __ip6mr_fill_mroute(mrt, skb, cache, rtm); read_unlock(&mrt_lock); return err; } static int ip6mr_fill_mroute(struct mr6_table *mrt, struct sk_buff *skb, u32 portid, u32 seq, struct mfc6_cache *c, int cmd, int flags) { struct nlmsghdr *nlh; struct rtmsg *rtm; int err; nlh = nlmsg_put(skb, portid, seq, cmd, sizeof(*rtm), flags); if (!nlh) return -EMSGSIZE; rtm = nlmsg_data(nlh); rtm->rtm_family = RTNL_FAMILY_IP6MR; rtm->rtm_dst_len = 128; rtm->rtm_src_len = 128; rtm->rtm_tos = 0; rtm->rtm_table = mrt->id; if (nla_put_u32(skb, RTA_TABLE, mrt->id)) goto nla_put_failure; rtm->rtm_type = RTN_MULTICAST; rtm->rtm_scope = RT_SCOPE_UNIVERSE; if (c->mfc_flags & MFC_STATIC) rtm->rtm_protocol = RTPROT_STATIC; else rtm->rtm_protocol = RTPROT_MROUTED; rtm->rtm_flags = 0; if (nla_put_in6_addr(skb, RTA_SRC, &c->mf6c_origin) || nla_put_in6_addr(skb, RTA_DST, &c->mf6c_mcastgrp)) goto nla_put_failure; err = __ip6mr_fill_mroute(mrt, skb, c, rtm); /* do not break the dump if cache is unresolved */ if (err < 0 && err != -ENOENT) goto nla_put_failure; nlmsg_end(skb, nlh); return 0; nla_put_failure: nlmsg_cancel(skb, nlh); return -EMSGSIZE; } static int mr6_msgsize(bool unresolved, int maxvif) { size_t len = NLMSG_ALIGN(sizeof(struct rtmsg)) + nla_total_size(4) /* RTA_TABLE */ + nla_total_size(sizeof(struct in6_addr)) /* RTA_SRC */ + nla_total_size(sizeof(struct in6_addr)) /* RTA_DST */ ; if (!unresolved) len = len + nla_total_size(4) /* RTA_IIF */ + nla_total_size(0) /* RTA_MULTIPATH */ + maxvif * NLA_ALIGN(sizeof(struct rtnexthop)) /* RTA_MFC_STATS */ + nla_total_size_64bit(sizeof(struct rta_mfc_stats)) ; return len; } static void mr6_netlink_event(struct mr6_table *mrt, struct mfc6_cache *mfc, int cmd) { struct net *net = read_pnet(&mrt->net); struct sk_buff *skb; int err = -ENOBUFS; skb = nlmsg_new(mr6_msgsize(mfc->mf6c_parent >= MAXMIFS, mrt->maxvif), GFP_ATOMIC); if (!skb) goto errout; err = ip6mr_fill_mroute(mrt, skb, 0, 0, mfc, cmd, 0); if (err < 0) goto errout; rtnl_notify(skb, net, 0, RTNLGRP_IPV6_MROUTE, NULL, GFP_ATOMIC); return; errout: kfree_skb(skb); if (err < 0) rtnl_set_sk_err(net, RTNLGRP_IPV6_MROUTE, err); } static int ip6mr_rtm_dumproute(struct sk_buff *skb, struct netlink_callback *cb) { struct net *net = sock_net(skb->sk); struct mr6_table *mrt; struct mfc6_cache *mfc; unsigned int t = 0, s_t; unsigned int h = 0, s_h; unsigned int e = 0, s_e; s_t = cb->args[0]; s_h = cb->args[1]; s_e = cb->args[2]; read_lock(&mrt_lock); ip6mr_for_each_table(mrt, net) { if (t < s_t) goto next_table; if (t > s_t) s_h = 0; for (h = s_h; h < MFC6_LINES; h++) { list_for_each_entry(mfc, &mrt->mfc6_cache_array[h], list) { if (e < s_e) goto next_entry; if (ip6mr_fill_mroute(mrt, skb, NETLINK_CB(cb->skb).portid, cb->nlh->nlmsg_seq, mfc, RTM_NEWROUTE, NLM_F_MULTI) < 0) goto done; next_entry: e++; } e = s_e = 0; } spin_lock_bh(&mfc_unres_lock); list_for_each_entry(mfc, &mrt->mfc6_unres_queue, list) { if (e < s_e) goto next_entry2; if (ip6mr_fill_mroute(mrt, skb, NETLINK_CB(cb->skb).portid, cb->nlh->nlmsg_seq, mfc, RTM_NEWROUTE, NLM_F_MULTI) < 0) { spin_unlock_bh(&mfc_unres_lock); goto done; } next_entry2: e++; } spin_unlock_bh(&mfc_unres_lock); e = s_e = 0; s_h = 0; next_table: t++; } done: read_unlock(&mrt_lock); cb->args[2] = e; cb->args[1] = h; cb->args[0] = t; return skb->len; }
./CrossVul/dataset_final_sorted/CWE-20/c/good_3038_0
crossvul-cpp_data_good_721_2
/* Copyright (C) 2007-2014 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * 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 * version 2 along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ /** * \defgroup decode Packet decoding * * \brief Code in charge of protocol decoding * * The task of decoding packets is made in different files and * as Suricata is supporting encapsulation there is a potential * recursivity in the call. * * For each protocol a DecodePROTO function is provided. For * example we have DecodeIPV4() for IPv4 and DecodePPP() for * PPP. * * These functions have all a pkt and and a len argument which * are respectively a pointer to the protocol data and the length * of this protocol data. * * \attention The pkt parameter must point to the effective data because * it will be used later to set per protocol pointer like Packet::tcph * * @{ */ /** * \file * * \author Victor Julien <victor@inliniac.net> * * Decode the raw packet */ #include "suricata-common.h" #include "suricata.h" #include "conf.h" #include "decode.h" #include "decode-teredo.h" #include "util-debug.h" #include "util-mem.h" #include "app-layer-detect-proto.h" #include "app-layer.h" #include "tm-threads.h" #include "util-error.h" #include "util-print.h" #include "tmqh-packetpool.h" #include "util-profiling.h" #include "pkt-var.h" #include "util-mpm-ac.h" #include "output.h" #include "output-flow.h" extern bool stats_decoder_events; extern bool stats_stream_events; int DecodeTunnel(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, uint8_t *pkt, uint32_t len, PacketQueue *pq, enum DecodeTunnelProto proto) { switch (proto) { case DECODE_TUNNEL_PPP: return DecodePPP(tv, dtv, p, pkt, len, pq); case DECODE_TUNNEL_IPV4: return DecodeIPV4(tv, dtv, p, pkt, len, pq); case DECODE_TUNNEL_IPV6: case DECODE_TUNNEL_IPV6_TEREDO: return DecodeIPV6(tv, dtv, p, pkt, len, pq); case DECODE_TUNNEL_VLAN: return DecodeVLAN(tv, dtv, p, pkt, len, pq); case DECODE_TUNNEL_ETHERNET: return DecodeEthernet(tv, dtv, p, pkt, len, pq); case DECODE_TUNNEL_ERSPAN: return DecodeERSPAN(tv, dtv, p, pkt, len, pq); default: SCLogDebug("FIXME: DecodeTunnel: protocol %" PRIu32 " not supported.", proto); break; } return TM_ECODE_OK; } /** * \brief Return a malloced packet. */ void PacketFree(Packet *p) { PACKET_DESTRUCTOR(p); SCFree(p); } /** * \brief Finalize decoding of a packet * * This function needs to be call at the end of decode * functions when decoding has been succesful. * */ void PacketDecodeFinalize(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p) { if (p->flags & PKT_IS_INVALID) { StatsIncr(tv, dtv->counter_invalid); } } void PacketUpdateEngineEventCounters(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p) { for (uint8_t i = 0; i < p->events.cnt; i++) { const uint8_t e = p->events.events[i]; if (e <= DECODE_EVENT_PACKET_MAX && !stats_decoder_events) continue; if (e > DECODE_EVENT_PACKET_MAX && !stats_stream_events) continue; StatsIncr(tv, dtv->counter_engine_events[e]); } } /** * \brief Get a malloced packet. * * \retval p packet, NULL on error */ Packet *PacketGetFromAlloc(void) { Packet *p = SCMalloc(SIZE_OF_PACKET); if (unlikely(p == NULL)) { return NULL; } memset(p, 0, SIZE_OF_PACKET); PACKET_INITIALIZE(p); p->ReleasePacket = PacketFree; p->flags |= PKT_ALLOC; SCLogDebug("allocated a new packet only using alloc..."); PACKET_PROFILING_START(p); return p; } /** * \brief Return a packet to where it was allocated. */ void PacketFreeOrRelease(Packet *p) { if (p->flags & PKT_ALLOC) PacketFree(p); else PacketPoolReturnPacket(p); } /** * \brief Get a packet. We try to get a packet from the packetpool first, but * if that is empty we alloc a packet that is free'd again after * processing. * * \retval p packet, NULL on error */ Packet *PacketGetFromQueueOrAlloc(void) { /* try the pool first */ Packet *p = PacketPoolGetPacket(); if (p == NULL) { /* non fatal, we're just not processing a packet then */ p = PacketGetFromAlloc(); } else { PACKET_PROFILING_START(p); } return p; } inline int PacketCallocExtPkt(Packet *p, int datalen) { if (! p->ext_pkt) { p->ext_pkt = SCCalloc(1, datalen); if (unlikely(p->ext_pkt == NULL)) { SET_PKT_LEN(p, 0); return -1; } } return 0; } /** * \brief Copy data to Packet payload at given offset * * This function copies data/payload to a Packet. It uses the * space allocated at Packet creation (pointed by Packet::pkt) * or allocate some memory (pointed by Packet::ext_pkt) if the * data size is to big to fit in initial space (of size * default_packet_size). * * \param Pointer to the Packet to modify * \param Offset of the copy relatively to payload of Packet * \param Pointer to the data to copy * \param Length of the data to copy */ inline int PacketCopyDataOffset(Packet *p, uint32_t offset, uint8_t *data, uint32_t datalen) { if (unlikely(offset + datalen > MAX_PAYLOAD_SIZE)) { /* too big */ return -1; } /* Do we have already an packet with allocated data */ if (! p->ext_pkt) { uint32_t newsize = offset + datalen; // check overflow if (newsize < offset) return -1; if (newsize <= default_packet_size) { /* data will fit in memory allocated with packet */ memcpy(GET_PKT_DIRECT_DATA(p) + offset, data, datalen); } else { /* here we need a dynamic allocation */ p->ext_pkt = SCMalloc(MAX_PAYLOAD_SIZE); if (unlikely(p->ext_pkt == NULL)) { SET_PKT_LEN(p, 0); return -1; } /* copy initial data */ memcpy(p->ext_pkt, GET_PKT_DIRECT_DATA(p), GET_PKT_DIRECT_MAX_SIZE(p)); /* copy data as asked */ memcpy(p->ext_pkt + offset, data, datalen); } } else { memcpy(p->ext_pkt + offset, data, datalen); } return 0; } /** * \brief Copy data to Packet payload and set packet length * * \param Pointer to the Packet to modify * \param Pointer to the data to copy * \param Length of the data to copy */ inline int PacketCopyData(Packet *p, uint8_t *pktdata, uint32_t pktlen) { SET_PKT_LEN(p, (size_t)pktlen); return PacketCopyDataOffset(p, 0, pktdata, pktlen); } /** * \brief Setup a pseudo packet (tunnel) * * \param parent parent packet for this pseudo pkt * \param pkt raw packet data * \param len packet data length * \param proto protocol of the tunneled packet * * \retval p the pseudo packet or NULL if out of memory */ Packet *PacketTunnelPktSetup(ThreadVars *tv, DecodeThreadVars *dtv, Packet *parent, uint8_t *pkt, uint32_t len, enum DecodeTunnelProto proto, PacketQueue *pq) { int ret; SCEnter(); /* get us a packet */ Packet *p = PacketGetFromQueueOrAlloc(); if (unlikely(p == NULL)) { SCReturnPtr(NULL, "Packet"); } /* copy packet and set lenght, proto */ PacketCopyData(p, pkt, len); p->recursion_level = parent->recursion_level + 1; p->ts.tv_sec = parent->ts.tv_sec; p->ts.tv_usec = parent->ts.tv_usec; p->datalink = DLT_RAW; p->tenant_id = parent->tenant_id; /* set the root ptr to the lowest layer */ if (parent->root != NULL) p->root = parent->root; else p->root = parent; /* tell new packet it's part of a tunnel */ SET_TUNNEL_PKT(p); ret = DecodeTunnel(tv, dtv, p, GET_PKT_DATA(p), GET_PKT_LEN(p), pq, proto); if (unlikely(ret != TM_ECODE_OK) || (proto == DECODE_TUNNEL_IPV6_TEREDO && (p->flags & PKT_IS_INVALID))) { /* Not a (valid) tunnel packet */ SCLogDebug("tunnel packet is invalid"); p->root = NULL; UNSET_TUNNEL_PKT(p); TmqhOutputPacketpool(tv, p); SCReturnPtr(NULL, "Packet"); } /* tell parent packet it's part of a tunnel */ SET_TUNNEL_PKT(parent); /* increment tunnel packet refcnt in the root packet */ TUNNEL_INCR_PKT_TPR(p); /* disable payload (not packet) inspection on the parent, as the payload * is the packet we will now run through the system separately. We do * check it against the ip/port/other header checks though */ DecodeSetNoPayloadInspectionFlag(parent); SCReturnPtr(p, "Packet"); } /** * \brief Setup a pseudo packet (reassembled frags) * * Difference with PacketPseudoPktSetup is that this func doesn't increment * the recursion level. It needs to be on the same level as the frags because * we run the flow engine against this and we need to get the same flow. * * \param parent parent packet for this pseudo pkt * \param pkt raw packet data * \param len packet data length * \param proto protocol of the tunneled packet * * \retval p the pseudo packet or NULL if out of memory */ Packet *PacketDefragPktSetup(Packet *parent, uint8_t *pkt, uint32_t len, uint8_t proto) { SCEnter(); /* get us a packet */ Packet *p = PacketGetFromQueueOrAlloc(); if (unlikely(p == NULL)) { SCReturnPtr(NULL, "Packet"); } /* set the root ptr to the lowest layer */ if (parent->root != NULL) p->root = parent->root; else p->root = parent; /* copy packet and set lenght, proto */ if (pkt && len) { PacketCopyData(p, pkt, len); } p->recursion_level = parent->recursion_level; /* NOT incremented */ p->ts.tv_sec = parent->ts.tv_sec; p->ts.tv_usec = parent->ts.tv_usec; p->datalink = DLT_RAW; p->tenant_id = parent->tenant_id; /* tell new packet it's part of a tunnel */ SET_TUNNEL_PKT(p); p->vlan_id[0] = parent->vlan_id[0]; p->vlan_id[1] = parent->vlan_id[1]; p->vlan_idx = parent->vlan_idx; SCReturnPtr(p, "Packet"); } /** * \brief inform defrag "parent" that a pseudo packet is * now assosiated to it. */ void PacketDefragPktSetupParent(Packet *parent) { /* tell parent packet it's part of a tunnel */ SET_TUNNEL_PKT(parent); /* increment tunnel packet refcnt in the root packet */ TUNNEL_INCR_PKT_TPR(parent); /* disable payload (not packet) inspection on the parent, as the payload * is the packet we will now run through the system separately. We do * check it against the ip/port/other header checks though */ DecodeSetNoPayloadInspectionFlag(parent); } void PacketBypassCallback(Packet *p) { /* Don't try to bypass if flow is already out or * if we have failed to do it once */ int state = SC_ATOMIC_GET(p->flow->flow_state); if ((state == FLOW_STATE_LOCAL_BYPASSED) || (state == FLOW_STATE_CAPTURE_BYPASSED)) { return; } if (p->BypassPacketsFlow && p->BypassPacketsFlow(p)) { FlowUpdateState(p->flow, FLOW_STATE_CAPTURE_BYPASSED); } else { FlowUpdateState(p->flow, FLOW_STATE_LOCAL_BYPASSED); } } void DecodeRegisterPerfCounters(DecodeThreadVars *dtv, ThreadVars *tv) { /* register counters */ dtv->counter_pkts = StatsRegisterCounter("decoder.pkts", tv); dtv->counter_bytes = StatsRegisterCounter("decoder.bytes", tv); dtv->counter_invalid = StatsRegisterCounter("decoder.invalid", tv); dtv->counter_ipv4 = StatsRegisterCounter("decoder.ipv4", tv); dtv->counter_ipv6 = StatsRegisterCounter("decoder.ipv6", tv); dtv->counter_eth = StatsRegisterCounter("decoder.ethernet", tv); dtv->counter_raw = StatsRegisterCounter("decoder.raw", tv); dtv->counter_null = StatsRegisterCounter("decoder.null", tv); dtv->counter_sll = StatsRegisterCounter("decoder.sll", tv); dtv->counter_tcp = StatsRegisterCounter("decoder.tcp", tv); dtv->counter_udp = StatsRegisterCounter("decoder.udp", tv); dtv->counter_sctp = StatsRegisterCounter("decoder.sctp", tv); dtv->counter_icmpv4 = StatsRegisterCounter("decoder.icmpv4", tv); dtv->counter_icmpv6 = StatsRegisterCounter("decoder.icmpv6", tv); dtv->counter_ppp = StatsRegisterCounter("decoder.ppp", tv); dtv->counter_pppoe = StatsRegisterCounter("decoder.pppoe", tv); dtv->counter_gre = StatsRegisterCounter("decoder.gre", tv); dtv->counter_vlan = StatsRegisterCounter("decoder.vlan", tv); dtv->counter_vlan_qinq = StatsRegisterCounter("decoder.vlan_qinq", tv); dtv->counter_ieee8021ah = StatsRegisterCounter("decoder.ieee8021ah", tv); dtv->counter_teredo = StatsRegisterCounter("decoder.teredo", tv); dtv->counter_ipv4inipv6 = StatsRegisterCounter("decoder.ipv4_in_ipv6", tv); dtv->counter_ipv6inipv6 = StatsRegisterCounter("decoder.ipv6_in_ipv6", tv); dtv->counter_mpls = StatsRegisterCounter("decoder.mpls", tv); dtv->counter_avg_pkt_size = StatsRegisterAvgCounter("decoder.avg_pkt_size", tv); dtv->counter_max_pkt_size = StatsRegisterMaxCounter("decoder.max_pkt_size", tv); dtv->counter_erspan = StatsRegisterMaxCounter("decoder.erspan", tv); dtv->counter_flow_memcap = StatsRegisterCounter("flow.memcap", tv); dtv->counter_flow_tcp = StatsRegisterCounter("flow.tcp", tv); dtv->counter_flow_udp = StatsRegisterCounter("flow.udp", tv); dtv->counter_flow_icmp4 = StatsRegisterCounter("flow.icmpv4", tv); dtv->counter_flow_icmp6 = StatsRegisterCounter("flow.icmpv6", tv); dtv->counter_defrag_ipv4_fragments = StatsRegisterCounter("defrag.ipv4.fragments", tv); dtv->counter_defrag_ipv4_reassembled = StatsRegisterCounter("defrag.ipv4.reassembled", tv); dtv->counter_defrag_ipv4_timeouts = StatsRegisterCounter("defrag.ipv4.timeouts", tv); dtv->counter_defrag_ipv6_fragments = StatsRegisterCounter("defrag.ipv6.fragments", tv); dtv->counter_defrag_ipv6_reassembled = StatsRegisterCounter("defrag.ipv6.reassembled", tv); dtv->counter_defrag_ipv6_timeouts = StatsRegisterCounter("defrag.ipv6.timeouts", tv); dtv->counter_defrag_max_hit = StatsRegisterCounter("defrag.max_frag_hits", tv); for (int i = 0; i < DECODE_EVENT_MAX; i++) { BUG_ON(i != (int)DEvents[i].code); if (i <= DECODE_EVENT_PACKET_MAX && !stats_decoder_events) continue; if (i > DECODE_EVENT_PACKET_MAX && !stats_stream_events) continue; dtv->counter_engine_events[i] = StatsRegisterCounter( DEvents[i].event_name, tv); } return; } void DecodeUpdatePacketCounters(ThreadVars *tv, const DecodeThreadVars *dtv, const Packet *p) { StatsIncr(tv, dtv->counter_pkts); //StatsIncr(tv, dtv->counter_pkts_per_sec); StatsAddUI64(tv, dtv->counter_bytes, GET_PKT_LEN(p)); StatsAddUI64(tv, dtv->counter_avg_pkt_size, GET_PKT_LEN(p)); StatsSetUI64(tv, dtv->counter_max_pkt_size, GET_PKT_LEN(p)); } /** * \brief Debug print function for printing addresses * * \param Address object * * \todo IPv6 */ void AddressDebugPrint(Address *a) { if (a == NULL) return; switch (a->family) { case AF_INET: { char s[16]; PrintInet(AF_INET, (const void *)&a->addr_data32[0], s, sizeof(s)); SCLogDebug("%s", s); break; } } } /** \brief Alloc and setup DecodeThreadVars */ DecodeThreadVars *DecodeThreadVarsAlloc(ThreadVars *tv) { DecodeThreadVars *dtv = NULL; if ( (dtv = SCMalloc(sizeof(DecodeThreadVars))) == NULL) return NULL; memset(dtv, 0, sizeof(DecodeThreadVars)); dtv->app_tctx = AppLayerGetCtxThread(tv); if (OutputFlowLogThreadInit(tv, NULL, &dtv->output_flow_thread_data) != TM_ECODE_OK) { SCLogError(SC_ERR_THREAD_INIT, "initializing flow log API for thread failed"); DecodeThreadVarsFree(tv, dtv); return NULL; } /** set config defaults */ int vlanbool = 0; if ((ConfGetBool("vlan.use-for-tracking", &vlanbool)) == 1 && vlanbool == 0) { dtv->vlan_disabled = 1; } SCLogDebug("vlan tracking is %s", dtv->vlan_disabled == 0 ? "enabled" : "disabled"); return dtv; } void DecodeThreadVarsFree(ThreadVars *tv, DecodeThreadVars *dtv) { if (dtv != NULL) { if (dtv->app_tctx != NULL) AppLayerDestroyCtxThread(dtv->app_tctx); if (dtv->output_flow_thread_data != NULL) OutputFlowLogThreadDeinit(tv, dtv->output_flow_thread_data); SCFree(dtv); } } /** * \brief Set data for Packet and set length when zeo copy is used * * \param Pointer to the Packet to modify * \param Pointer to the data * \param Length of the data */ inline int PacketSetData(Packet *p, uint8_t *pktdata, uint32_t pktlen) { SET_PKT_LEN(p, (size_t)pktlen); if (unlikely(!pktdata)) { return -1; } p->ext_pkt = pktdata; p->flags |= PKT_ZERO_COPY; return 0; } const char *PktSrcToString(enum PktSrcEnum pkt_src) { const char *pkt_src_str = "<unknown>"; switch (pkt_src) { case PKT_SRC_WIRE: pkt_src_str = "wire/pcap"; break; case PKT_SRC_DECODER_GRE: pkt_src_str = "gre tunnel"; break; case PKT_SRC_DECODER_IPV4: pkt_src_str = "ipv4 tunnel"; break; case PKT_SRC_DECODER_IPV6: pkt_src_str = "ipv6 tunnel"; break; case PKT_SRC_DECODER_TEREDO: pkt_src_str = "teredo tunnel"; break; case PKT_SRC_DEFRAG: pkt_src_str = "defrag"; break; case PKT_SRC_STREAM_TCP_STREAM_END_PSEUDO: pkt_src_str = "stream"; break; case PKT_SRC_STREAM_TCP_DETECTLOG_FLUSH: pkt_src_str = "stream (detect/log)"; break; case PKT_SRC_FFR: pkt_src_str = "stream (flow timeout)"; break; } return pkt_src_str; } void CaptureStatsUpdate(ThreadVars *tv, CaptureStats *s, const Packet *p) { if (unlikely(PACKET_TEST_ACTION(p, (ACTION_REJECT|ACTION_REJECT_DST|ACTION_REJECT_BOTH)))) { StatsIncr(tv, s->counter_ips_rejected); } else if (unlikely(PACKET_TEST_ACTION(p, ACTION_DROP))) { StatsIncr(tv, s->counter_ips_blocked); } else if (unlikely(p->flags & PKT_STREAM_MODIFIED)) { StatsIncr(tv, s->counter_ips_replaced); } else { StatsIncr(tv, s->counter_ips_accepted); } } void CaptureStatsSetup(ThreadVars *tv, CaptureStats *s) { s->counter_ips_accepted = StatsRegisterCounter("ips.accepted", tv); s->counter_ips_blocked = StatsRegisterCounter("ips.blocked", tv); s->counter_ips_rejected = StatsRegisterCounter("ips.rejected", tv); s->counter_ips_replaced = StatsRegisterCounter("ips.replaced", tv); } void DecodeGlobalConfig(void) { DecodeTeredoConfig(); } /** * @} */
./CrossVul/dataset_final_sorted/CWE-20/c/good_721_2
crossvul-cpp_data_good_3160_1
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ /*************************************************************************** * Copyright (C) 2013-2017 Ping Identity Corporation * All rights reserved. * * For further information please contact: * * Ping Identity Corporation * 1099 18th St Suite 2950 * Denver, CO 80202 * 303.468.2900 * http://www.pingidentity.com * * DISCLAIMER OF WARRANTIES: * * THE SOFTWARE PROVIDED HEREUNDER IS PROVIDED ON AN "AS IS" BASIS, WITHOUT * ANY WARRANTIES OR REPRESENTATIONS EXPRESS, IMPLIED OR STATUTORY; INCLUDING, * WITHOUT LIMITATION, WARRANTIES OF QUALITY, PERFORMANCE, NONINFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. NOR ARE THERE ANY * WARRANTIES CREATED BY A COURSE OR DEALING, COURSE OF PERFORMANCE OR TRADE * USAGE. FURTHERMORE, THERE ARE NO WARRANTIES THAT THE SOFTWARE WILL MEET * YOUR NEEDS OR BE FREE FROM ERRORS, OR THAT THE OPERATION OF THE SOFTWARE * WILL BE UNINTERRUPTED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES 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. * * Initially based on mod_auth_cas.c: * https://github.com/Jasig/mod_auth_cas * * Other code copied/borrowed/adapted: * shared memory caching: mod_auth_mellon * * @Author: Hans Zandbelt - hzandbelt@pingidentity.com * **************************************************************************/ #include "apr_hash.h" #include "apr_strings.h" #include "ap_config.h" #include "ap_provider.h" #include "apr_lib.h" #include "apr_file_io.h" #include "apr_sha1.h" #include "apr_base64.h" #include "httpd.h" #include "http_core.h" #include "http_config.h" #include "http_log.h" #include "http_protocol.h" #include "http_request.h" #include "mod_auth_openidc.h" // TODO: // - sort out oidc_cfg vs. oidc_dir_cfg stuff // - rigid input checking on discovery responses // - check self-issued support // - README.quickstart // - refresh metadata once-per too? (for non-signing key changes) extern module AP_MODULE_DECLARE_DATA auth_openidc_module; /* * clean any suspicious headers in the HTTP request sent by the user agent */ static void oidc_scrub_request_headers(request_rec *r, const char *claim_prefix, const char *authn_header) { const int prefix_len = claim_prefix ? strlen(claim_prefix) : 0; /* get an array representation of the incoming HTTP headers */ const apr_array_header_t * const h = apr_table_elts(r->headers_in); /* table to keep the non-suspicious headers */ apr_table_t *clean_headers = apr_table_make(r->pool, h->nelts); /* loop over the incoming HTTP headers */ const apr_table_entry_t * const e = (const apr_table_entry_t *) h->elts; int i; for (i = 0; i < h->nelts; i++) { const char * const k = e[i].key; /* is this header's name equivalent to the header that mod_auth_openidc would set for the authenticated user? */ const int authn_header_matches = (k != NULL) && authn_header && (oidc_strnenvcmp(k, authn_header, -1) == 0); /* * would this header be interpreted as a mod_auth_openidc attribute? Note * that prefix_len will be zero if no attr_prefix is defined, * so this will always be false. Also note that we do not * scrub headers if the prefix is empty because every header * would match. */ const int prefix_matches = (k != NULL) && prefix_len && (oidc_strnenvcmp(k, claim_prefix, prefix_len) == 0); /* add to the clean_headers if non-suspicious, skip and report otherwise */ if (!prefix_matches && !authn_header_matches) { apr_table_addn(clean_headers, k, e[i].val); } else { oidc_warn(r, "scrubbed suspicious request header (%s: %.32s)", k, e[i].val); } } /* overwrite the incoming headers with the cleaned result */ r->headers_in = clean_headers; } /* * strip the session cookie from the headers sent to the application/backend */ static void oidc_strip_cookies(request_rec *r) { char *cookie, *ctx, *result = NULL; const char *name = NULL; int i; apr_array_header_t *strip = oidc_dir_cfg_strip_cookies(r); char *cookies = apr_pstrdup(r->pool, (char *) apr_table_get(r->headers_in, "Cookie")); if ((cookies != NULL) && (strip != NULL)) { oidc_debug(r, "looking for the following cookies to strip from cookie header: %s", apr_array_pstrcat(r->pool, strip, ',')); cookie = apr_strtok(cookies, ";", &ctx); do { while (cookie != NULL && *cookie == ' ') cookie++; for (i = 0; i < strip->nelts; i++) { name = ((const char**) strip->elts)[i]; if ((strncmp(cookie, name, strlen(name)) == 0) && (cookie[strlen(name)] == '=')) { oidc_debug(r, "stripping: %s", name); break; } } if (i == strip->nelts) { result = result ? apr_psprintf(r->pool, "%s;%s", result, cookie) : cookie; } cookie = apr_strtok(NULL, ";", &ctx); } while (cookie != NULL); if (result != NULL) { oidc_debug(r, "set cookie to backend to: %s", result ? apr_psprintf(r->pool, "\"%s\"", result) : "<null>"); apr_table_set(r->headers_in, "Cookie", result); } else { oidc_debug(r, "unsetting all cookies to backend"); apr_table_unset(r->headers_in, "Cookie"); } } } #define OIDC_SHA1_LEN 20 /* * calculates a hash value based on request fingerprint plus a provided nonce string. */ static char *oidc_get_browser_state_hash(request_rec *r, const char *nonce) { oidc_debug(r, "enter"); /* helper to hold to header values */ const char *value = NULL; /* the hash context */ apr_sha1_ctx_t sha1; /* Initialize the hash context */ apr_sha1_init(&sha1); /* get the X_FORWARDED_FOR header value */ value = (char *) apr_table_get(r->headers_in, "X_FORWARDED_FOR"); /* if we have a value for this header, concat it to the hash input */ if (value != NULL) apr_sha1_update(&sha1, value, strlen(value)); /* get the USER_AGENT header value */ value = (char *) apr_table_get(r->headers_in, "USER_AGENT"); /* if we have a value for this header, concat it to the hash input */ if (value != NULL) apr_sha1_update(&sha1, value, strlen(value)); /* get the remote client IP address or host name */ /* int remotehost_is_ip; value = ap_get_remote_host(r->connection, r->per_dir_config, REMOTE_NOLOOKUP, &remotehost_is_ip); apr_sha1_update(&sha1, value, strlen(value)); */ /* concat the nonce parameter to the hash input */ apr_sha1_update(&sha1, nonce, strlen(nonce)); /* finalize the hash input and calculate the resulting hash output */ unsigned char hash[OIDC_SHA1_LEN]; apr_sha1_final(hash, &sha1); /* base64url-encode the resulting hash and return it */ char *result = NULL; oidc_base64url_encode(r, &result, (const char *) hash, OIDC_SHA1_LEN, TRUE); return result; } /* * return the name for the state cookie */ static char *oidc_get_state_cookie_name(request_rec *r, const char *state) { return apr_psprintf(r->pool, "%s%s", OIDCStateCookiePrefix, state); } /* * return the static provider configuration, i.e. from a metadata URL or configuration primitives */ static apr_byte_t oidc_provider_static_config(request_rec *r, oidc_cfg *c, oidc_provider_t **provider) { json_t *j_provider = NULL; const char *s_json = NULL; /* see if we should configure a static provider based on external (cached) metadata */ if ((c->metadata_dir != NULL) || (c->provider.metadata_url == NULL)) { *provider = &c->provider; return TRUE; } c->cache->get(r, OIDC_CACHE_SECTION_PROVIDER, oidc_util_escape_string(r, c->provider.metadata_url), &s_json); if (s_json == NULL) { if (oidc_metadata_provider_retrieve(r, c, NULL, c->provider.metadata_url, &j_provider, &s_json) == FALSE) { oidc_error(r, "could not retrieve metadata from url: %s", c->provider.metadata_url); return FALSE; } c->cache->set(r, OIDC_CACHE_SECTION_PROVIDER, oidc_util_escape_string(r, c->provider.metadata_url), s_json, apr_time_now() + (c->provider_metadata_refresh_interval <= 0 ? apr_time_from_sec( OIDC_CACHE_PROVIDER_METADATA_EXPIRY_DEFAULT) : c->provider_metadata_refresh_interval)); } else { /* correct parsing and validation was already done when it was put in the cache */ j_provider = json_loads(s_json, 0, 0); } *provider = apr_pcalloc(r->pool, sizeof(oidc_provider_t)); memcpy(*provider, &c->provider, sizeof(oidc_provider_t)); if (oidc_metadata_provider_parse(r, c, j_provider, *provider) == FALSE) { oidc_error(r, "could not parse metadata from url: %s", c->provider.metadata_url); if (j_provider) json_decref(j_provider); return FALSE; } json_decref(j_provider); return TRUE; } /* * return the oidc_provider_t struct for the specified issuer */ static oidc_provider_t *oidc_get_provider_for_issuer(request_rec *r, oidc_cfg *c, const char *issuer, apr_byte_t allow_discovery) { /* by default we'll assume that we're dealing with a single statically configured OP */ oidc_provider_t *provider = NULL; if (oidc_provider_static_config(r, c, &provider) == FALSE) return NULL; /* unless a metadata directory was configured, so we'll try and get the provider settings from there */ if (c->metadata_dir != NULL) { /* try and get metadata from the metadata directory for the OP that sent this response */ if ((oidc_metadata_get(r, c, issuer, &provider, allow_discovery) == FALSE) || (provider == NULL)) { /* don't know nothing about this OP/issuer */ oidc_error(r, "no provider metadata found for issuer \"%s\"", issuer); return NULL; } } return provider; } /* * find out whether the request is a response from an IDP discovery page */ static apr_byte_t oidc_is_discovery_response(request_rec *r, oidc_cfg *cfg) { /* * prereq: this is a call to the configured redirect_uri, now see if: * the OIDC_DISC_OP_PARAM is present */ return oidc_util_request_has_parameter(r, OIDC_DISC_OP_PARAM) || oidc_util_request_has_parameter(r, OIDC_DISC_USER_PARAM); } /* * return the HTTP method being called: only for POST data persistence purposes */ static const char *oidc_original_request_method(request_rec *r, oidc_cfg *cfg, apr_byte_t handle_discovery_response) { const char *method = OIDC_METHOD_GET; char *m = NULL; if ((handle_discovery_response == TRUE) && (oidc_util_request_matches_url(r, cfg->redirect_uri)) && (oidc_is_discovery_response(r, cfg))) { oidc_util_get_request_parameter(r, OIDC_DISC_RM_PARAM, &m); if (m != NULL) method = apr_pstrdup(r->pool, m); } else { /* * if POST preserve is not enabled for this location, there's no point in preserving * the method either which would result in POSTing empty data on return; * so we revert to legacy behavior */ if (oidc_cfg_dir_preserve_post(r) == 0) return OIDC_METHOD_GET; const char *content_type = apr_table_get(r->headers_in, "Content-Type"); if ((r->method_number == M_POST) && (apr_strnatcmp(content_type, "application/x-www-form-urlencoded") == 0)) method = OIDC_METHOD_FORM_POST; } oidc_debug(r, "return: %s", method); return method; } /* * send an OpenID Connect authorization request to the specified provider preserving POST parameters using HTML5 storage */ apr_byte_t oidc_post_preserve_javascript(request_rec *r, const char *location, char **javascript, char **javascript_method) { if (oidc_cfg_dir_preserve_post(r) == 0) return FALSE; oidc_debug(r, "enter"); oidc_cfg *cfg = ap_get_module_config(r->server->module_config, &auth_openidc_module); const char *method = oidc_original_request_method(r, cfg, FALSE); if (apr_strnatcmp(method, OIDC_METHOD_FORM_POST) != 0) return FALSE; /* read the parameters that are POST-ed to us */ apr_table_t *params = apr_table_make(r->pool, 8); if (oidc_util_read_post_params(r, params) == FALSE) { oidc_error(r, "something went wrong when reading the POST parameters"); return FALSE; } const apr_array_header_t *arr = apr_table_elts(params); const apr_table_entry_t *elts = (const apr_table_entry_t*) arr->elts; int i; char *json = ""; for (i = 0; i < arr->nelts; i++) { json = apr_psprintf(r->pool, "%s'%s': '%s'%s", json, oidc_util_escape_string(r, elts[i].key), oidc_util_escape_string(r, elts[i].val), i < arr->nelts - 1 ? "," : ""); } json = apr_psprintf(r->pool, "{ %s }", json); const char *jmethod = "preserveOnLoad"; const char *jscript = apr_psprintf(r->pool, " <script type=\"text/javascript\">\n" " function %s() {\n" " localStorage.setItem('mod_auth_openidc_preserve_post_params', JSON.stringify(%s));\n" " %s" " }\n" " </script>\n", jmethod, json, location ? apr_psprintf(r->pool, "window.location='%s';\n", location) : ""); if (location == NULL) { if (javascript_method) *javascript_method = apr_pstrdup(r->pool, jmethod); if (javascript) *javascript = apr_pstrdup(r->pool, jscript); } else { oidc_util_html_send(r, "Preserving...", jscript, jmethod, "<p>Preserving...</p>", DONE); } return TRUE; } /* * restore POST parameters on original_url from HTML5 local storage */ static int oidc_request_post_preserved_restore(request_rec *r, const char *original_url) { oidc_debug(r, "enter: original_url=%s", original_url); const char *method = "postOnLoad"; const char *script = apr_psprintf(r->pool, " <script type=\"text/javascript\">\n" " function %s() {\n" " var mod_auth_openidc_preserve_post_params = JSON.parse(localStorage.getItem('mod_auth_openidc_preserve_post_params'));\n" " localStorage.removeItem('mod_auth_openidc_preserve_post_params');\n" " for (var key in mod_auth_openidc_preserve_post_params) {\n" " var input = document.createElement(\"input\");\n" " input.name = decodeURIComponent(key);\n" " input.value = decodeURIComponent(mod_auth_openidc_preserve_post_params[key]);\n" " input.type = \"hidden\";\n" " document.forms[0].appendChild(input);\n" " }\n" " document.forms[0].action = '%s';\n" " document.forms[0].submit();\n" " }\n" " </script>\n", method, original_url); const char *body = " <p>Restoring...</p>\n" " <form method=\"post\"></form>\n"; return oidc_util_html_send(r, "Restoring...", script, method, body, DONE); } /* * parse state that was sent to us by the issuer */ static apr_byte_t oidc_unsolicited_proto_state(request_rec *r, oidc_cfg *c, const char *state, json_t **proto_state) { char *alg = NULL; oidc_debug(r, "enter: state header=%s", oidc_proto_peek_jwt_header(r, state, &alg)); oidc_jose_error_t err; oidc_jwk_t *jwk = NULL; if (oidc_util_create_symmetric_key(r, c->provider.client_secret, oidc_alg2keysize(alg), "sha256", TRUE, &jwk) == FALSE) return FALSE; oidc_jwt_t *jwt = NULL; if (oidc_jwt_parse(r->pool, state, &jwt, oidc_util_merge_symmetric_key(r->pool, c->private_keys, jwk), &err) == FALSE) { oidc_error(r, "could not parse JWT from state: invalid unsolicited response: %s", oidc_jose_e2s(r->pool, err)); return FALSE; } oidc_jwk_destroy(jwk); oidc_debug(r, "successfully parsed JWT from state"); if (jwt->payload.iss == NULL) { oidc_error(r, "no \"iss\" could be retrieved from JWT state, aborting"); oidc_jwt_destroy(jwt); return FALSE; } oidc_provider_t *provider = oidc_get_provider_for_issuer(r, c, jwt->payload.iss, FALSE); if (provider == NULL) { oidc_jwt_destroy(jwt); return FALSE; } /* validate the state JWT, validating optional exp + iat */ if (oidc_proto_validate_jwt(r, jwt, provider->issuer, FALSE, FALSE, provider->idtoken_iat_slack) == FALSE) { oidc_jwt_destroy(jwt); return FALSE; } char *rfp = NULL; if (oidc_jose_get_string(r->pool, jwt->payload.value.json, "rfp", TRUE, &rfp, &err) == FALSE) { oidc_error(r, "no \"rfp\" claim could be retrieved from JWT state, aborting: %s", oidc_jose_e2s(r->pool, err)); oidc_jwt_destroy(jwt); return FALSE; } if (apr_strnatcmp(rfp, "iss") != 0) { oidc_error(r, "\"rfp\" (%s) does not match \"iss\", aborting", rfp); oidc_jwt_destroy(jwt); return FALSE; } char *target_link_uri = NULL; oidc_jose_get_string(r->pool, jwt->payload.value.json, "target_link_uri", FALSE, &target_link_uri, NULL); if (target_link_uri == NULL) { if (c->default_sso_url == NULL) { oidc_error(r, "no \"target_link_uri\" claim could be retrieved from JWT state and no OIDCDefaultURL is set, aborting"); oidc_jwt_destroy(jwt); return FALSE; } target_link_uri = c->default_sso_url; } if (c->metadata_dir != NULL) { if ((oidc_metadata_get(r, c, jwt->payload.iss, &provider, FALSE) == FALSE) || (provider == NULL)) { oidc_error(r, "no provider metadata found for provider \"%s\"", jwt->payload.iss); oidc_jwt_destroy(jwt); return FALSE; } } char *jti = NULL; oidc_jose_get_string(r->pool, jwt->payload.value.json, "jti", FALSE, &jti, NULL); if (jti == NULL) { char *cser = oidc_jwt_serialize(r->pool, jwt, &err); if (cser == NULL) return FALSE; if (oidc_util_hash_string_and_base64url_encode(r, "sha256", cser, &jti) == FALSE) { oidc_error(r, "oidc_util_hash_string_and_base64url_encode returned an error"); return FALSE; } } const char *replay = NULL; c->cache->get(r, OIDC_CACHE_SECTION_JTI, jti, &replay); if (replay != NULL) { oidc_error(r, "the jti value (%s) passed in the browser state was found in the cache already; possible replay attack!?", jti); oidc_jwt_destroy(jwt); return FALSE; } /* jti cache duration is the configured replay prevention window for token issuance plus 10 seconds for safety */ apr_time_t jti_cache_duration = apr_time_from_sec( provider->idtoken_iat_slack * 2 + 10); /* store it in the cache for the calculated duration */ c->cache->set(r, OIDC_CACHE_SECTION_JTI, jti, jti, apr_time_now() + jti_cache_duration); oidc_debug(r, "jti \"%s\" validated successfully and is now cached for %" APR_TIME_T_FMT " seconds", jti, apr_time_sec(jti_cache_duration)); jwk = NULL; if (oidc_util_create_symmetric_key(r, c->provider.client_secret, 0, NULL, TRUE, &jwk) == FALSE) return FALSE; oidc_jwks_uri_t jwks_uri = { provider->jwks_uri, provider->jwks_refresh_interval, provider->ssl_validate_server }; if (oidc_proto_jwt_verify(r, c, jwt, &jwks_uri, oidc_util_merge_symmetric_key(r->pool, NULL, jwk)) == FALSE) { oidc_error(r, "state JWT could not be validated, aborting"); oidc_jwt_destroy(jwt); return FALSE; } oidc_jwk_destroy(jwk); oidc_debug(r, "successfully verified state JWT"); *proto_state = json_object(); json_object_set_new(*proto_state, "issuer", json_string(jwt->payload.iss)); json_object_set_new(*proto_state, "original_url", json_string(target_link_uri)); json_object_set_new(*proto_state, "original_method", json_string("get")); json_object_set_new(*proto_state, "response_mode", json_string(provider->response_mode)); json_object_set_new(*proto_state, "response_type", json_string(provider->response_type)); json_object_set_new(*proto_state, "timestamp", json_integer(apr_time_sec(apr_time_now()))); oidc_jwt_destroy(jwt); return TRUE; } /* obtain the state from the cookie value */ static json_t * oidc_get_state_from_cookie(request_rec *r, oidc_cfg *c, const char *cookieValue) { json_t *result = NULL; oidc_util_jwt_verify(r, c->crypto_passphrase, cookieValue, &result); return result; } static void oidc_clean_expired_state_cookies(request_rec *r, oidc_cfg *c) { char *cookie, *tokenizerCtx; char *cookies = apr_pstrdup(r->pool, (char *) apr_table_get(r->headers_in, "Cookie")); if (cookies != NULL) { cookie = apr_strtok(cookies, ";", &tokenizerCtx); do { while (cookie != NULL && *cookie == ' ') cookie++; if (strstr(cookie, OIDCStateCookiePrefix) == cookie) { char *cookieName = cookie; while (cookie != NULL && *cookie != '=') cookie++; if (*cookie == '=') { *cookie = '\0'; cookie++; json_t *state = oidc_get_state_from_cookie(r, c, cookie); if (state != NULL) { json_t *v = json_object_get(state, "timestamp"); apr_time_t now = apr_time_sec(apr_time_now()); if (now > json_integer_value(v) + c->state_timeout) { oidc_error(r, "state has expired"); oidc_util_set_cookie(r, cookieName, "", 0); } json_decref(state); } } } cookie = apr_strtok(NULL, ";", &tokenizerCtx); } while (cookie != NULL); } } /* * restore the state that was maintained between authorization request and response in an encrypted cookie */ static apr_byte_t oidc_restore_proto_state(request_rec *r, oidc_cfg *c, const char *state, json_t **proto_state) { oidc_debug(r, "enter"); /* clean expired state cookies to avoid pollution */ oidc_clean_expired_state_cookies(r, c); const char *cookieName = oidc_get_state_cookie_name(r, state); /* get the state cookie value first */ char *cookieValue = oidc_util_get_cookie(r, cookieName); if (cookieValue == NULL) { oidc_error(r, "no \"%s\" state cookie found", cookieName); return oidc_unsolicited_proto_state(r, c, state, proto_state); } /* clear state cookie because we don't need it anymore */ oidc_util_set_cookie(r, cookieName, "", 0); *proto_state = oidc_get_state_from_cookie(r, c, cookieValue); if (*proto_state == NULL) return FALSE; json_t *v = json_object_get(*proto_state, "nonce"); /* calculate the hash of the browser fingerprint concatenated with the nonce */ char *calc = oidc_get_browser_state_hash(r, json_string_value(v)); /* compare the calculated hash with the value provided in the authorization response */ if (apr_strnatcmp(calc, state) != 0) { oidc_error(r, "calculated state from cookie does not match state parameter passed back in URL: \"%s\" != \"%s\"", state, calc); json_decref(*proto_state); return FALSE; } v = json_object_get(*proto_state, "timestamp"); apr_time_t now = apr_time_sec(apr_time_now()); /* check that the timestamp is not beyond the valid interval */ if (now > json_integer_value(v) + c->state_timeout) { oidc_error(r, "state has expired"); json_decref(*proto_state); return FALSE; } /* add the state */ json_object_set_new(*proto_state, "state", json_string(state)); char *s_value = json_dumps(*proto_state, JSON_ENCODE_ANY); oidc_debug(r, "restored state: %s", s_value); free(s_value); /* we've made it */ return TRUE; } /* * set the state that is maintained between an authorization request and an authorization response * in a cookie in the browser that is cryptographically bound to that state */ static apr_byte_t oidc_authorization_request_set_cookie(request_rec *r, oidc_cfg *c, const char *state, json_t *proto_state) { /* * create a cookie consisting of 8 elements: * random value, original URL, original method, issuer, response_type, response_mod, prompt and timestamp * encoded as JSON */ /* encrypt the resulting JSON value */ char *cookieValue = NULL; if (oidc_util_jwt_create(r, c->crypto_passphrase, proto_state, &cookieValue) == FALSE) return FALSE; /* clean expired state cookies to avoid pollution */ oidc_clean_expired_state_cookies(r, c); /* assemble the cookie name for the state cookie */ const char *cookieName = oidc_get_state_cookie_name(r, state); /* set it as a cookie */ oidc_util_set_cookie(r, cookieName, cookieValue, -1); //free(s_value); return TRUE; } /* * get the mod_auth_openidc related context from the (userdata in the) request * (used for passing state between various Apache request processing stages and hook callbacks) */ static apr_table_t *oidc_request_state(request_rec *rr) { /* our state is always stored in the main request */ request_rec *r = (rr->main != NULL) ? rr->main : rr; /* our state is a table, get it */ apr_table_t *state = NULL; apr_pool_userdata_get((void **) &state, OIDC_USERDATA_KEY, r->pool); /* if it does not exist, we'll create a new table */ if (state == NULL) { state = apr_table_make(r->pool, 5); apr_pool_userdata_set(state, OIDC_USERDATA_KEY, NULL, r->pool); } /* return the resulting table, always non-null now */ return state; } /* * set a name/value pair in the mod_auth_openidc-specific request context * (used for passing state between various Apache request processing stages and hook callbacks) */ void oidc_request_state_set(request_rec *r, const char *key, const char *value) { /* get a handle to the global state, which is a table */ apr_table_t *state = oidc_request_state(r); /* put the name/value pair in that table */ apr_table_setn(state, key, value); } /* * get a name/value pair from the mod_auth_openidc-specific request context * (used for passing state between various Apache request processing stages and hook callbacks) */ const char*oidc_request_state_get(request_rec *r, const char *key) { /* get a handle to the global state, which is a table */ apr_table_t *state = oidc_request_state(r); /* return the value from the table */ return apr_table_get(state, key); } /* * set the claims from a JSON object (c.q. id_token or user_info response) stored * in the session in to HTTP headers passed on to the application */ static apr_byte_t oidc_set_app_claims(request_rec *r, const oidc_cfg * const cfg, oidc_session_t *session, const char *s_claims) { json_t *j_claims = NULL; /* decode the string-encoded attributes in to a JSON structure */ if (s_claims != NULL) { json_error_t json_error; j_claims = json_loads(s_claims, 0, &json_error); if (j_claims == NULL) { /* whoops, JSON has been corrupted */ oidc_error(r, "unable to parse \"%s\" JSON stored in the session: %s", s_claims, json_error.text); return FALSE; } } /* set the resolved claims a HTTP headers for the application */ if (j_claims != NULL) { oidc_util_set_app_infos(r, j_claims, cfg->claim_prefix, cfg->claim_delimiter, oidc_cfg_dir_pass_info_in_headers(r), oidc_cfg_dir_pass_info_in_envvars(r)); /* release resources */ json_decref(j_claims); } return TRUE; } static int oidc_authenticate_user(request_rec *r, oidc_cfg *c, oidc_provider_t *provider, const char *original_url, const char *login_hint, const char *id_token_hint, const char *prompt, const char *auth_request_params); /* * log message about max session duration */ static void oidc_log_session_expires(request_rec *r, apr_time_t session_expires) { char buf[APR_RFC822_DATE_LEN + 1]; apr_rfc822_date(buf, session_expires); oidc_debug(r, "session expires %s (in %" APR_TIME_T_FMT " secs from now)", buf, apr_time_sec(session_expires - apr_time_now())); } /* * check if maximum session duration was exceeded */ static int oidc_check_max_session_duration(request_rec *r, oidc_cfg *cfg, oidc_session_t *session) { const char *s_session_expires = NULL; apr_time_t session_expires; /* get the session expiry from the session data */ oidc_session_get(r, session, OIDC_SESSION_EXPIRES_SESSION_KEY, &s_session_expires); /* convert the string to a timestamp */ sscanf(s_session_expires, "%" APR_TIME_T_FMT, &session_expires); /* check the expire timestamp against the current time */ if (apr_time_now() > session_expires) { oidc_warn(r, "maximum session duration exceeded for user: %s", session->remote_user); oidc_session_kill(r, session); return oidc_authenticate_user(r, cfg, NULL, oidc_get_current_url(r), NULL, NULL, NULL, NULL); } /* log message about max session duration */ oidc_log_session_expires(r, session_expires); return OK; } /* * validate received session cookie against the domain it was issued for: * * this handles the case where the cache configured is a the same single memcache, Redis, or file * backend for different (virtual) hosts, or a client-side cookie protected with the same secret * * it also handles the case that a cookie is unexpectedly shared across multiple hosts in * name-based virtual hosting even though the OP(s) would be the same */ static apr_byte_t oidc_check_cookie_domain(request_rec *r, oidc_cfg *cfg, oidc_session_t *session) { const char *c_cookie_domain = cfg->cookie_domain ? cfg->cookie_domain : oidc_get_current_url_host(r); const char *s_cookie_domain = NULL; oidc_session_get(r, session, OIDC_COOKIE_DOMAIN_SESSION_KEY, &s_cookie_domain); if ((s_cookie_domain == NULL) || (apr_strnatcmp(c_cookie_domain, s_cookie_domain) != 0)) { oidc_warn(r, "aborting: detected attempt to play cookie against a different domain/host than issued for! (issued=%s, current=%s)", s_cookie_domain, c_cookie_domain); return FALSE; } return TRUE; } /* * get a handle to the provider configuration via the "issuer" stored in the session */ apr_byte_t oidc_get_provider_from_session(request_rec *r, oidc_cfg *c, oidc_session_t *session, oidc_provider_t **provider) { oidc_debug(r, "enter"); /* get the issuer value from the session state */ const char *issuer = NULL; oidc_session_get(r, session, OIDC_ISSUER_SESSION_KEY, &issuer); if (issuer == NULL) { oidc_error(r, "session corrupted: no issuer found in session"); return FALSE; } /* get the provider info associated with the issuer value */ oidc_provider_t *p = oidc_get_provider_for_issuer(r, c, issuer, FALSE); if (p == NULL) { oidc_error(r, "session corrupted: no provider found for issuer: %s", issuer); return FALSE; } *provider = p; return TRUE; } /* * store the access token expiry timestamp in the session, based on the expires_in */ static void oidc_store_access_token_expiry(request_rec *r, oidc_session_t *session, int expires_in) { if (expires_in != -1) { oidc_session_set(r, session, OIDC_ACCESSTOKEN_EXPIRES_SESSION_KEY, apr_psprintf(r->pool, "%" APR_TIME_T_FMT, apr_time_sec(apr_time_now()) + expires_in)); } } /* * store claims resolved from the userinfo endpoint in the session */ static void oidc_store_userinfo_claims(request_rec *r, oidc_session_t *session, oidc_provider_t *provider, const char *claims) { oidc_debug(r, "enter"); /* see if we've resolved any claims */ if (claims != NULL) { /* * Successfully decoded a set claims from the response so we can store them * (well actually the stringified representation in the response) * in the session context safely now */ oidc_session_set(r, session, OIDC_CLAIMS_SESSION_KEY, claims); } else { /* * clear the existing claims because we could not refresh them */ oidc_session_set(r, session, OIDC_CLAIMS_SESSION_KEY, NULL); } /* store the last refresh time if we've configured a userinfo refresh interval */ if (provider->userinfo_refresh_interval > 0) oidc_session_set(r, session, OIDC_USERINFO_LAST_REFRESH_SESSION_KEY, apr_psprintf(r->pool, "%" APR_TIME_T_FMT, apr_time_now())); } /* * execute refresh token grant to refresh the existing access token */ static apr_byte_t oidc_refresh_access_token(request_rec *r, oidc_cfg *c, oidc_session_t *session, oidc_provider_t *provider, char **new_access_token) { oidc_debug(r, "enter"); /* get the refresh token that was stored in the session */ const char *refresh_token = NULL; oidc_session_get(r, session, OIDC_REFRESHTOKEN_SESSION_KEY, &refresh_token); if (refresh_token == NULL) { oidc_warn(r, "refresh token routine called but no refresh_token found in the session"); return FALSE; } /* elements returned in the refresh response */ char *s_id_token = NULL; int expires_in = -1; char *s_token_type = NULL; char *s_access_token = NULL; char *s_refresh_token = NULL; /* refresh the tokens by calling the token endpoint */ if (oidc_proto_refresh_request(r, c, provider, refresh_token, &s_id_token, &s_access_token, &s_token_type, &expires_in, &s_refresh_token) == FALSE) { oidc_error(r, "access_token could not be refreshed"); return FALSE; } /* store the new access_token in the session and discard the old one */ oidc_session_set(r, session, OIDC_ACCESSTOKEN_SESSION_KEY, s_access_token); oidc_store_access_token_expiry(r, session, expires_in); /* see if we need to return it as a parameter */ if (new_access_token != NULL) *new_access_token = s_access_token; /* if we have a new refresh token (rolling refresh), store it in the session and overwrite the old one */ if (s_refresh_token != NULL) oidc_session_set(r, session, OIDC_REFRESHTOKEN_SESSION_KEY, s_refresh_token); return TRUE; } /* * retrieve claims from the userinfo endpoint and return the stringified response */ static const char *oidc_retrieve_claims_from_userinfo_endpoint(request_rec *r, oidc_cfg *c, oidc_provider_t *provider, const char *access_token, oidc_session_t *session, char *id_token_sub) { oidc_debug(r, "enter"); /* see if a userinfo endpoint is set, otherwise there's nothing to do for us */ if (provider->userinfo_endpoint_url == NULL) { oidc_debug(r, "not retrieving userinfo claims because userinfo_endpoint is not set"); return NULL; } /* see if there's an access token, otherwise we can't call the userinfo endpoint at all */ if (access_token == NULL) { oidc_debug(r, "not retrieving userinfo claims because access_token is not provided"); return NULL; } if ((id_token_sub == NULL) && (session != NULL)) { // when refreshing claims from the userinfo endpoint const char *s_id_token_claims = NULL; oidc_session_get(r, session, OIDC_IDTOKEN_CLAIMS_SESSION_KEY, &s_id_token_claims); if (s_id_token_claims == NULL) { oidc_error(r, "no id_token claims provided"); return NULL; } json_error_t json_error; json_t *id_token_claims = json_loads(s_id_token_claims, 0, &json_error); if (id_token_claims == NULL) { oidc_error(r, "JSON parsing (json_loads) failed: %s (%s)", json_error.text, s_id_token_claims); return NULL; } oidc_jose_get_string(r->pool, id_token_claims, "sub", FALSE, &id_token_sub, NULL); } // TODO: return code should indicate whether the token expired or some other error occurred // TODO: long-term: session storage should be JSON (with explicit types and less conversion, using standard routines) /* try to get claims from the userinfo endpoint using the provided access token */ const char *result = NULL; if (oidc_proto_resolve_userinfo(r, c, provider, id_token_sub, access_token, &result) == FALSE) { /* see if we have an existing session and we are refreshing the user info claims */ if (session != NULL) { /* first call to user info endpoint failed, but the access token may have just expired, so refresh it */ char *access_token = NULL; if (oidc_refresh_access_token(r, c, session, provider, &access_token) == TRUE) { /* try again with the new access token */ if (oidc_proto_resolve_userinfo(r, c, provider, id_token_sub, access_token, &result) == FALSE) { oidc_error(r, "resolving user info claims with the refreshed access token failed, nothing will be stored in the session"); result = NULL; } } else { oidc_warn(r, "refreshing access token failed, claims will not be retrieved/refreshed from the userinfo endpoint"); result = NULL; } } else { oidc_error(r, "resolving user info claims with the existing/provided access token failed, nothing will be stored in the session"); result = NULL; } } return result; } /* * get (new) claims from the userinfo endpoint */ static apr_byte_t oidc_refresh_claims_from_userinfo_endpoint(request_rec *r, oidc_cfg *cfg, oidc_session_t *session) { oidc_provider_t *provider = NULL; const char *claims = NULL; char *access_token = NULL; /* get the current provider info */ if (oidc_get_provider_from_session(r, cfg, session, &provider) == FALSE) return FALSE; /* see if we can do anything here, i.e. we have a userinfo endpoint and a refresh interval is configured */ apr_time_t interval = apr_time_from_sec( provider->userinfo_refresh_interval); oidc_debug(r, "userinfo_endpoint=%s, interval=%d", provider->userinfo_endpoint_url, provider->userinfo_refresh_interval); if ((provider->userinfo_endpoint_url != NULL) && (interval > 0)) { /* get the last refresh timestamp from the session info */ apr_time_t last_refresh = 0; const char *s_last_refresh = NULL; oidc_session_get(r, session, OIDC_USERINFO_LAST_REFRESH_SESSION_KEY, &s_last_refresh); if (s_last_refresh != NULL) { sscanf(s_last_refresh, "%" APR_TIME_T_FMT, &last_refresh); } oidc_debug(r, "refresh needed in: %" APR_TIME_T_FMT " seconds", apr_time_sec(last_refresh + interval - apr_time_now())); /* see if we need to refresh again */ if (last_refresh + interval < apr_time_now()) { /* get the current access token */ oidc_session_get(r, session, OIDC_ACCESSTOKEN_SESSION_KEY, (const char **) &access_token); /* retrieve the current claims */ claims = oidc_retrieve_claims_from_userinfo_endpoint(r, cfg, provider, access_token, session, NULL); /* store claims resolved from userinfo endpoint */ oidc_store_userinfo_claims(r, session, provider, claims); /* indicated something changed */ return TRUE; } } return FALSE; } /* * copy the claims and id_token from the session to the request state and optionally return them */ static void oidc_copy_tokens_to_request_state(request_rec *r, oidc_session_t *session, const char **s_id_token, const char **s_claims) { const char *id_token = NULL, *claims = NULL; oidc_session_get(r, session, OIDC_IDTOKEN_CLAIMS_SESSION_KEY, &id_token); oidc_session_get(r, session, OIDC_CLAIMS_SESSION_KEY, &claims); oidc_debug(r, "id_token=%s claims=%s", id_token, claims); if (id_token != NULL) { oidc_request_state_set(r, OIDC_IDTOKEN_CLAIMS_SESSION_KEY, id_token); if (s_id_token != NULL) *s_id_token = id_token; } if (claims != NULL) { oidc_request_state_set(r, OIDC_CLAIMS_SESSION_KEY, claims); if (s_claims != NULL) *s_claims = claims; } } /* * handle the case where we have identified an existing authentication session for a user */ static int oidc_handle_existing_session(request_rec *r, oidc_cfg *cfg, oidc_session_t *session) { oidc_debug(r, "enter"); /* get the header name in which the remote user name needs to be passed */ char *authn_header = oidc_cfg_dir_authn_header(r); int pass_headers = oidc_cfg_dir_pass_info_in_headers(r); int pass_envvars = oidc_cfg_dir_pass_info_in_envvars(r); /* verify current cookie domain against issued cookie domain */ if (oidc_check_cookie_domain(r, cfg, session) == FALSE) return HTTP_UNAUTHORIZED; /* check if the maximum session duration was exceeded */ int rc = oidc_check_max_session_duration(r, cfg, session); if (rc != OK) return rc; /* if needed, refresh claims from the user info endpoint */ apr_byte_t needs_save = oidc_refresh_claims_from_userinfo_endpoint(r, cfg, session); /* * we're going to pass the information that we have to the application, * but first we need to scrub the headers that we're going to use for security reasons */ if (cfg->scrub_request_headers != 0) { /* scrub all headers starting with OIDC_ first */ oidc_scrub_request_headers(r, OIDC_DEFAULT_HEADER_PREFIX, oidc_cfg_dir_authn_header(r)); /* * then see if the claim headers need to be removed on top of that * (i.e. the prefix does not start with the default OIDC_) */ if ((strstr(cfg->claim_prefix, OIDC_DEFAULT_HEADER_PREFIX) != cfg->claim_prefix)) { oidc_scrub_request_headers(r, cfg->claim_prefix, NULL); } } /* set the user authentication HTTP header if set and required */ if ((r->user != NULL) && (authn_header != NULL)) oidc_util_set_header(r, authn_header, r->user); const char *s_claims = NULL; const char *s_id_token = NULL; /* copy id_token and claims from session to request state and obtain their values */ oidc_copy_tokens_to_request_state(r, session, &s_id_token, &s_claims); /* set the claims in the app headers */ if (oidc_set_app_claims(r, cfg, session, s_claims) == FALSE) return HTTP_INTERNAL_SERVER_ERROR; if ((cfg->pass_idtoken_as & OIDC_PASS_IDTOKEN_AS_CLAIMS)) { /* set the id_token in the app headers */ if (oidc_set_app_claims(r, cfg, session, s_id_token) == FALSE) return HTTP_INTERNAL_SERVER_ERROR; } if ((cfg->pass_idtoken_as & OIDC_PASS_IDTOKEN_AS_PAYLOAD)) { /* pass the id_token JSON object to the app in a header or environment variable */ oidc_util_set_app_info(r, "id_token_payload", s_id_token, OIDC_DEFAULT_HEADER_PREFIX, pass_headers, pass_envvars); } if (cfg->session_type != OIDC_SESSION_TYPE_CLIENT_COOKIE) { if ((cfg->pass_idtoken_as & OIDC_PASS_IDTOKEN_AS_SERIALIZED)) { const char *s_id_token = NULL; /* get the compact serialized JWT from the session */ oidc_session_get(r, session, OIDC_IDTOKEN_SESSION_KEY, &s_id_token); /* pass the compact serialized JWT to the app in a header or environment variable */ oidc_util_set_app_info(r, "id_token", s_id_token, OIDC_DEFAULT_HEADER_PREFIX, pass_headers, pass_envvars); } } else { oidc_error(r, "session type \"client-cookie\" does not allow storing/passing the id_token; use \"OIDCSessionType server-cache\" for that"); } /* set the refresh_token in the app headers/variables, if enabled for this location/directory */ const char *refresh_token = NULL; oidc_session_get(r, session, OIDC_REFRESHTOKEN_SESSION_KEY, &refresh_token); if ((oidc_cfg_dir_pass_refresh_token(r) != 0) && (refresh_token != NULL)) { /* pass it to the app in a header or environment variable */ oidc_util_set_app_info(r, "refresh_token", refresh_token, OIDC_DEFAULT_HEADER_PREFIX, pass_headers, pass_envvars); } /* set the access_token in the app headers/variables */ const char *access_token = NULL; oidc_session_get(r, session, OIDC_ACCESSTOKEN_SESSION_KEY, &access_token); if (access_token != NULL) { /* pass it to the app in a header or environment variable */ oidc_util_set_app_info(r, "access_token", access_token, OIDC_DEFAULT_HEADER_PREFIX, pass_headers, pass_envvars); } /* set the expiry timestamp in the app headers/variables */ const char *access_token_expires = NULL; oidc_session_get(r, session, OIDC_ACCESSTOKEN_EXPIRES_SESSION_KEY, &access_token_expires); if (access_token_expires != NULL) { /* pass it to the app in a header or environment variable */ oidc_util_set_app_info(r, "access_token_expires", access_token_expires, OIDC_DEFAULT_HEADER_PREFIX, pass_headers, pass_envvars); } /* * reset the session inactivity timer * but only do this once per 10% of the inactivity timeout interval (with a max to 60 seconds) * for performance reasons * * now there's a small chance that the session ends 10% (or a minute) earlier than configured/expected * cq. when there's a request after a recent save (so no update) and then no activity happens until * a request comes in just before the session should expire * ("recent" and "just before" refer to 10%-with-a-max-of-60-seconds of the inactivity interval after * the start/last-update and before the expiry of the session respectively) * * this is be deemed acceptable here because of performance gain */ apr_time_t interval = apr_time_from_sec(cfg->session_inactivity_timeout); apr_time_t now = apr_time_now(); apr_time_t slack = interval / 10; if (slack > apr_time_from_sec(60)) slack = apr_time_from_sec(60); if (session->expiry - now < interval - slack) { session->expiry = now + interval; needs_save = TRUE; } /* check if something was updated in the session and we need to save it again */ if (needs_save) if (oidc_session_save(r, session) == FALSE) return HTTP_INTERNAL_SERVER_ERROR; /* return "user authenticated" status */ return OK; } /* * helper function for basic/implicit client flows upon receiving an authorization response: * check that it matches the state stored in the browser and return the variables associated * with the state, such as original_url and OP oidc_provider_t pointer. */ static apr_byte_t oidc_authorization_response_match_state(request_rec *r, oidc_cfg *c, const char *state, struct oidc_provider_t **provider, json_t **proto_state) { oidc_debug(r, "enter (state=%s)", state); if ((state == NULL) || (apr_strnatcmp(state, "") == 0)) { oidc_error(r, "state parameter is not set"); return FALSE; } /* check the state parameter against what we stored in a cookie */ if (oidc_restore_proto_state(r, c, state, proto_state) == FALSE) { oidc_error(r, "unable to restore state"); return FALSE; } *provider = oidc_get_provider_for_issuer(r, c, json_string_value(json_object_get(*proto_state, "issuer")), FALSE); return (*provider != NULL); } /* * redirect the browser to the session logout endpoint */ static int oidc_session_redirect_parent_window_to_logout(request_rec *r, oidc_cfg *c) { oidc_debug(r, "enter"); char *java_script = apr_psprintf(r->pool, " <script type=\"text/javascript\">\n" " window.top.location.href = '%s?session=logout';\n" " </script>\n", c->redirect_uri); return oidc_util_html_send(r, "Redirecting...", java_script, NULL, NULL, DONE); } /* * handle an error returned by the OP */ static int oidc_authorization_response_error(request_rec *r, oidc_cfg *c, json_t *proto_state, const char *error, const char *error_description) { const char *prompt = json_object_get(proto_state, "prompt") ? apr_pstrdup(r->pool, json_string_value( json_object_get(proto_state, "prompt"))) : NULL; json_decref(proto_state); if ((prompt != NULL) && (apr_strnatcmp(prompt, "none") == 0)) { return oidc_session_redirect_parent_window_to_logout(r, c); } return oidc_util_html_send_error(r, c->error_template, apr_psprintf(r->pool, "OpenID Connect Provider error: %s", error), error_description, DONE); } /* * set the unique user identifier that will be propagated in the Apache r->user and REMOTE_USER variables */ static apr_byte_t oidc_get_remote_user(request_rec *r, oidc_cfg *c, oidc_provider_t *provider, oidc_jwt_t *jwt, char **user, const char *s_claims) { char *issuer = provider->issuer; char *claim_name = apr_pstrdup(r->pool, c->remote_user_claim.claim_name); int n = strlen(claim_name); int post_fix_with_issuer = (claim_name[n - 1] == '@'); if (post_fix_with_issuer) { claim_name[n - 1] = '\0'; issuer = (strstr(issuer, "https://") == NULL) ? apr_pstrdup(r->pool, issuer) : apr_pstrdup(r->pool, issuer + strlen("https://")); } /* extract the username claim (default: "sub") from the id_token payload or user claims */ char *username = NULL; json_error_t json_error; json_t *claims = json_loads(s_claims, 0, &json_error); if (claims == NULL) { username = apr_pstrdup(r->pool, json_string_value( json_object_get(jwt->payload.value.json, claim_name))); } else { oidc_util_json_merge(jwt->payload.value.json, claims); username = apr_pstrdup(r->pool, json_string_value(json_object_get(claims, claim_name))); json_decref(claims); } if (username == NULL) { oidc_error(r, "OIDCRemoteUserClaim is set to \"%s\", but the id_token JSON payload and user claims did not contain a \"%s\" string", c->remote_user_claim.claim_name, claim_name); *user = NULL; return FALSE; } /* set the unique username in the session (will propagate to r->user/REMOTE_USER) */ *user = post_fix_with_issuer ? apr_psprintf(r->pool, "%s@%s", username, issuer) : username; if (c->remote_user_claim.reg_exp != NULL) { char *error_str = NULL; if (oidc_util_regexp_first_match(r->pool, *user, c->remote_user_claim.reg_exp, user, &error_str) == FALSE) { oidc_error(r, "oidc_util_regexp_first_match failed: %s", error_str); *user = NULL; return FALSE; } } oidc_debug(r, "set user to \"%s\"", *user); return TRUE; } /* * store resolved information in the session */ static apr_byte_t oidc_save_in_session(request_rec *r, oidc_cfg *c, oidc_session_t *session, oidc_provider_t *provider, const char *remoteUser, const char *id_token, oidc_jwt_t *id_token_jwt, const char *claims, const char *access_token, const int expires_in, const char *refresh_token, const char *session_state, const char *state, const char *original_url) { /* store the user in the session */ session->remote_user = remoteUser; /* set the session expiry to the inactivity timeout */ session->expiry = apr_time_now() + apr_time_from_sec(c->session_inactivity_timeout); /* store the claims payload in the id_token for later reference */ oidc_session_set(r, session, OIDC_IDTOKEN_CLAIMS_SESSION_KEY, id_token_jwt->payload.value.str); if (c->session_type != OIDC_SESSION_TYPE_CLIENT_COOKIE) { /* store the compact serialized representation of the id_token for later reference */ oidc_session_set(r, session, OIDC_IDTOKEN_SESSION_KEY, id_token); } /* store the issuer in the session (at least needed for session mgmt and token refresh */ oidc_session_set(r, session, OIDC_ISSUER_SESSION_KEY, provider->issuer); /* store the state and original URL in the session for handling browser-back more elegantly */ oidc_session_set(r, session, OIDC_REQUEST_STATE_SESSION_KEY, state); oidc_session_set(r, session, OIDC_REQUEST_ORIGINAL_URL, original_url); if ((session_state != NULL) && (provider->check_session_iframe != NULL)) { /* store the session state and required parameters session management */ oidc_session_set(r, session, OIDC_SESSION_STATE_SESSION_KEY, session_state); oidc_session_set(r, session, OIDC_CHECK_IFRAME_SESSION_KEY, provider->check_session_iframe); oidc_session_set(r, session, OIDC_CLIENTID_SESSION_KEY, provider->client_id); oidc_debug(r, "session management enabled: stored session_state (%s), check_session_iframe (%s) and client_id (%s) in the session", session_state, provider->check_session_iframe, provider->client_id); } else { oidc_debug(r, "session management disabled: session_state (%s) and/or check_session_iframe (%s) is not provided", session_state, provider->check_session_iframe); } if (provider->end_session_endpoint != NULL) oidc_session_set(r, session, OIDC_LOGOUT_ENDPOINT_SESSION_KEY, provider->end_session_endpoint); /* store claims resolved from userinfo endpoint */ oidc_store_userinfo_claims(r, session, provider, claims); /* see if we have an access_token */ if (access_token != NULL) { /* store the access_token in the session context */ oidc_session_set(r, session, OIDC_ACCESSTOKEN_SESSION_KEY, access_token); /* store the associated expires_in value */ oidc_store_access_token_expiry(r, session, expires_in); } /* see if we have a refresh_token */ if (refresh_token != NULL) { /* store the refresh_token in the session context */ oidc_session_set(r, session, OIDC_REFRESHTOKEN_SESSION_KEY, refresh_token); } /* store max session duration in the session as a hard cut-off expiry timestamp */ apr_time_t session_expires = (provider->session_max_duration == 0) ? apr_time_from_sec(id_token_jwt->payload.exp) : (apr_time_now() + apr_time_from_sec(provider->session_max_duration)); oidc_session_set(r, session, OIDC_SESSION_EXPIRES_SESSION_KEY, apr_psprintf(r->pool, "%" APR_TIME_T_FMT, session_expires)); /* log message about max session duration */ oidc_log_session_expires(r, session_expires); /* store the domain for which this session is valid */ oidc_session_set(r, session, OIDC_COOKIE_DOMAIN_SESSION_KEY, c->cookie_domain ? c->cookie_domain : oidc_get_current_url_host(r)); /* store the session */ return oidc_session_save(r, session); } /* * parse the expiry for the access token */ static int oidc_parse_expires_in(request_rec *r, const char *expires_in) { if (expires_in != NULL) { char *ptr = NULL; long number = strtol(expires_in, &ptr, 10); if (number <= 0) { oidc_warn(r, "could not convert \"expires_in\" value (%s) to a number", expires_in); return -1; } return number; } return -1; } /* * handle the different flows (hybrid, implicit, Authorization Code) */ static apr_byte_t oidc_handle_flows(request_rec *r, oidc_cfg *c, json_t *proto_state, oidc_provider_t *provider, apr_table_t *params, const char *response_mode, oidc_jwt_t **jwt) { apr_byte_t rc = FALSE; const char *requested_response_type = json_string_value( json_object_get(proto_state, "response_type")); /* handle the requested response type/mode */ if (oidc_util_spaced_string_equals(r->pool, requested_response_type, "code id_token token")) { rc = oidc_proto_authorization_response_code_idtoken_token(r, c, proto_state, provider, params, response_mode, jwt); } else if (oidc_util_spaced_string_equals(r->pool, requested_response_type, "code id_token")) { rc = oidc_proto_authorization_response_code_idtoken(r, c, proto_state, provider, params, response_mode, jwt); } else if (oidc_util_spaced_string_equals(r->pool, requested_response_type, "code token")) { rc = oidc_proto_handle_authorization_response_code_token(r, c, proto_state, provider, params, response_mode, jwt); } else if (oidc_util_spaced_string_equals(r->pool, requested_response_type, "code")) { rc = oidc_proto_handle_authorization_response_code(r, c, proto_state, provider, params, response_mode, jwt); } else if (oidc_util_spaced_string_equals(r->pool, requested_response_type, "id_token token")) { rc = oidc_proto_handle_authorization_response_idtoken_token(r, c, proto_state, provider, params, response_mode, jwt); } else if (oidc_util_spaced_string_equals(r->pool, requested_response_type, "id_token")) { rc = oidc_proto_handle_authorization_response_idtoken(r, c, proto_state, provider, params, response_mode, jwt); } else { oidc_error(r, "unsupported response type: \"%s\"", requested_response_type); } if ((rc == FALSE) && (*jwt != NULL)) { oidc_jwt_destroy(*jwt); *jwt = NULL; } return rc; } /* handle the browser back on an authorization response */ static apr_byte_t oidc_handle_browser_back(request_rec *r, const char *r_state, oidc_session_t *session) { /* see if we have an existing session and browser-back was used */ const char *s_state = NULL, *o_url = NULL; if (session->remote_user != NULL) { oidc_session_get(r, session, OIDC_REQUEST_STATE_SESSION_KEY, &s_state); oidc_session_get(r, session, OIDC_REQUEST_ORIGINAL_URL, &o_url); if ((r_state != NULL) && (s_state != NULL) && (apr_strnatcmp(r_state, s_state) == 0)) { /* log the browser back event detection */ oidc_warn(r, "browser back detected, redirecting to original URL: %s", o_url); /* go back to the URL that he originally tried to access */ apr_table_add(r->headers_out, "Location", o_url); return TRUE; } } return FALSE; } /* * complete the handling of an authorization response by obtaining, parsing and verifying the * id_token and storing the authenticated user state in the session */ static int oidc_handle_authorization_response(request_rec *r, oidc_cfg *c, oidc_session_t *session, apr_table_t *params, const char *response_mode) { oidc_debug(r, "enter, response_mode=%s", response_mode); oidc_provider_t *provider = NULL; json_t *proto_state = NULL; oidc_jwt_t *jwt = NULL; /* see if this response came from a browser-back event */ if (oidc_handle_browser_back(r, apr_table_get(params, "state"), session) == TRUE) return HTTP_MOVED_TEMPORARILY; /* match the returned state parameter against the state stored in the browser */ if (oidc_authorization_response_match_state(r, c, apr_table_get(params, "state"), &provider, &proto_state) == FALSE) { if (c->default_sso_url != NULL) { oidc_warn(r, "invalid authorization response state; a default SSO URL is set, sending the user there: %s", c->default_sso_url); apr_table_add(r->headers_out, "Location", c->default_sso_url); return HTTP_MOVED_TEMPORARILY; } oidc_error(r, "invalid authorization response state and no default SSO URL is set, sending an error..."); return HTTP_INTERNAL_SERVER_ERROR; } /* see if the response is an error response */ if (apr_table_get(params, "error") != NULL) return oidc_authorization_response_error(r, c, proto_state, apr_table_get(params, "error"), apr_table_get(params, "error_description")); /* handle the code, implicit or hybrid flow */ if (oidc_handle_flows(r, c, proto_state, provider, params, response_mode, &jwt) == FALSE) return oidc_authorization_response_error(r, c, proto_state, "Error in handling response type.", NULL); if (jwt == NULL) { oidc_error(r, "no id_token was provided"); return oidc_authorization_response_error(r, c, proto_state, "No id_token was provided.", NULL); } int expires_in = oidc_parse_expires_in(r, apr_table_get(params, "expires_in")); /* * optionally resolve additional claims against the userinfo endpoint * parsed claims are not actually used here but need to be parsed anyway for error checking purposes */ const char *claims = oidc_retrieve_claims_from_userinfo_endpoint(r, c, provider, apr_table_get(params, "access_token"), NULL, jwt->payload.sub); /* restore the original protected URL that the user was trying to access */ const char *original_url = apr_pstrdup(r->pool, json_string_value(json_object_get(proto_state, "original_url"))); const char *original_method = apr_pstrdup(r->pool, json_string_value(json_object_get(proto_state, "original_method"))); /* set the user */ if (oidc_get_remote_user(r, c, provider, jwt, &r->user, claims) == TRUE) { /* session management: if the user in the new response is not equal to the old one, error out */ if ((json_object_get(proto_state, "prompt") != NULL) && (apr_strnatcmp( json_string_value( json_object_get(proto_state, "prompt")), "none") == 0)) { // TOOD: actually need to compare sub? (need to store it in the session separately then //const char *sub = NULL; //oidc_session_get(r, session, "sub", &sub); //if (apr_strnatcmp(sub, jwt->payload.sub) != 0) { if (apr_strnatcmp(session->remote_user, r->user) != 0) { oidc_warn(r, "user set from new id_token is different from current one"); oidc_jwt_destroy(jwt); return oidc_authorization_response_error(r, c, proto_state, "User changed!", NULL); } } /* store resolved information in the session */ if (oidc_save_in_session(r, c, session, provider, r->user, apr_table_get(params, "id_token"), jwt, claims, apr_table_get(params, "access_token"), expires_in, apr_table_get(params, "refresh_token"), apr_table_get(params, "session_state"), apr_table_get(params, "state"), original_url) == FALSE) return HTTP_INTERNAL_SERVER_ERROR; } else { oidc_error(r, "remote user could not be set"); return oidc_authorization_response_error(r, c, proto_state, "Remote user could not be set: contact the website administrator", NULL); } /* cleanup */ json_decref(proto_state); oidc_jwt_destroy(jwt); /* check that we've actually authenticated a user; functions as error handling for oidc_get_remote_user */ if (r->user == NULL) return HTTP_UNAUTHORIZED; /* log the successful response */ oidc_debug(r, "session created and stored, returning to original URL: %s, original method: %s", original_url, original_method); /* check whether form post data was preserved; if so restore it */ if (apr_strnatcmp(original_method, OIDC_METHOD_FORM_POST) == 0) { return oidc_request_post_preserved_restore(r, original_url); } /* now we've authenticated the user so go back to the URL that he originally tried to access */ apr_table_add(r->headers_out, "Location", original_url); /* do the actual redirect to the original URL */ return HTTP_MOVED_TEMPORARILY; } /* * handle an OpenID Connect Authorization Response using the POST (+fragment->POST) response_mode */ static int oidc_handle_post_authorization_response(request_rec *r, oidc_cfg *c, oidc_session_t *session) { oidc_debug(r, "enter"); /* initialize local variables */ char *response_mode = NULL; /* read the parameters that are POST-ed to us */ apr_table_t *params = apr_table_make(r->pool, 8); if (oidc_util_read_post_params(r, params) == FALSE) { oidc_error(r, "something went wrong when reading the POST parameters"); return HTTP_INTERNAL_SERVER_ERROR; } /* see if we've got any POST-ed data at all */ if ((apr_table_elts(params)->nelts < 1) || ((apr_table_elts(params)->nelts == 1) && apr_table_get(params, "response_mode") && (apr_strnatcmp(apr_table_get(params, "response_mode"), "fragment") == 0))) { return oidc_util_html_send_error(r, c->error_template, "Invalid Request", "You've hit an OpenID Connect Redirect URI with no parameters, this is an invalid request; you should not open this URL in your browser directly, or have the server administrator use a different OIDCRedirectURI setting.", HTTP_INTERNAL_SERVER_ERROR); } /* get the parameters */ response_mode = (char *) apr_table_get(params, "response_mode"); /* do the actual implicit work */ return oidc_handle_authorization_response(r, c, session, params, response_mode ? response_mode : "form_post"); } /* * handle an OpenID Connect Authorization Response using the redirect response_mode */ static int oidc_handle_redirect_authorization_response(request_rec *r, oidc_cfg *c, oidc_session_t *session) { oidc_debug(r, "enter"); /* read the parameters from the query string */ apr_table_t *params = apr_table_make(r->pool, 8); oidc_util_read_form_encoded_params(r, params, r->args); /* do the actual work */ return oidc_handle_authorization_response(r, c, session, params, "query"); } /* * present the user with an OP selection screen */ static int oidc_discovery(request_rec *r, oidc_cfg *cfg) { oidc_debug(r, "enter"); /* obtain the URL we're currently accessing, to be stored in the state/session */ char *current_url = oidc_get_current_url(r); const char *method = oidc_original_request_method(r, cfg, FALSE); /* generate CSRF token */ char *csrf = NULL; if (oidc_proto_generate_nonce(r, &csrf, 8) == FALSE) return HTTP_INTERNAL_SERVER_ERROR; char *discover_url = oidc_cfg_dir_discover_url(r); /* see if there's an external discovery page configured */ if (discover_url != NULL) { /* yes, assemble the parameters for external discovery */ char *url = apr_psprintf(r->pool, "%s%s%s=%s&%s=%s&%s=%s&%s=%s", discover_url, strchr(discover_url, '?') != NULL ? "&" : "?", OIDC_DISC_RT_PARAM, oidc_util_escape_string(r, current_url), OIDC_DISC_RM_PARAM, method, OIDC_DISC_CB_PARAM, oidc_util_escape_string(r, cfg->redirect_uri), OIDC_CSRF_NAME, oidc_util_escape_string(r, csrf)); /* log what we're about to do */ oidc_debug(r, "redirecting to external discovery page: %s", url); /* set CSRF cookie */ oidc_util_set_cookie(r, OIDC_CSRF_NAME, csrf, -1); /* see if we need to preserve POST parameters through Javascript/HTML5 storage */ if (oidc_post_preserve_javascript(r, url, NULL, NULL) == TRUE) return DONE; /* do the actual redirect to an external discovery page */ apr_table_add(r->headers_out, "Location", url); return HTTP_MOVED_TEMPORARILY; } /* get a list of all providers configured in the metadata directory */ apr_array_header_t *arr = NULL; if (oidc_metadata_list(r, cfg, &arr) == FALSE) return oidc_util_html_send_error(r, cfg->error_template, "Configuration Error", "No configured providers found, contact your administrator", HTTP_UNAUTHORIZED); /* assemble a where-are-you-from IDP discovery HTML page */ const char *s = " <h3>Select your OpenID Connect Identity Provider</h3>\n"; /* list all configured providers in there */ int i; for (i = 0; i < arr->nelts; i++) { const char *issuer = ((const char**) arr->elts)[i]; // TODO: html escape (especially & character) char *display = (strstr(issuer, "https://") == NULL) ? apr_pstrdup(r->pool, issuer) : apr_pstrdup(r->pool, issuer + strlen("https://")); /* strip port number */ //char *p = strstr(display, ":"); //if (p != NULL) *p = '\0'; /* point back to the redirect_uri, where the selection is handled, with an IDP selection and return_to URL */ s = apr_psprintf(r->pool, "%s<p><a href=\"%s?%s=%s&amp;%s=%s&amp;%s=%s&amp;%s=%s\">%s</a></p>\n", s, cfg->redirect_uri, OIDC_DISC_OP_PARAM, oidc_util_escape_string(r, issuer), OIDC_DISC_RT_PARAM, oidc_util_escape_string(r, current_url), OIDC_DISC_RM_PARAM, method, OIDC_CSRF_NAME, csrf, display); } /* add an option to enter an account or issuer name for dynamic OP discovery */ s = apr_psprintf(r->pool, "%s<form method=\"get\" action=\"%s\">\n", s, cfg->redirect_uri); s = apr_psprintf(r->pool, "%s<p><input type=\"hidden\" name=\"%s\" value=\"%s\"><p>\n", s, OIDC_DISC_RT_PARAM, current_url); s = apr_psprintf(r->pool, "%s<p><input type=\"hidden\" name=\"%s\" value=\"%s\"><p>\n", s, OIDC_DISC_RM_PARAM, method); s = apr_psprintf(r->pool, "%s<p><input type=\"hidden\" name=\"%s\" value=\"%s\"><p>\n", s, OIDC_CSRF_NAME, csrf); s = apr_psprintf(r->pool, "%s<p>Or enter your account name (eg. &quot;mike@seed.gluu.org&quot;, or an IDP identifier (eg. &quot;mitreid.org&quot;):</p>\n", s); s = apr_psprintf(r->pool, "%s<p><input type=\"text\" name=\"%s\" value=\"%s\"></p>\n", s, OIDC_DISC_OP_PARAM, ""); s = apr_psprintf(r->pool, "%s<p><input type=\"submit\" value=\"Submit\"></p>\n", s); s = apr_psprintf(r->pool, "%s</form>\n", s); oidc_util_set_cookie(r, OIDC_CSRF_NAME, csrf, -1); char *javascript = NULL, *javascript_method = NULL; char *html_head = "<style type=\"text/css\">body {text-align: center}</style>"; if (oidc_post_preserve_javascript(r, NULL, &javascript, &javascript_method) == TRUE) html_head = apr_psprintf(r->pool, "%s%s", html_head, javascript); /* now send the HTML contents to the user agent */ return oidc_util_html_send(r, "OpenID Connect Provider Discovery", html_head, javascript_method, s, DONE); } /* * authenticate the user to the selected OP, if the OP is not selected yet perform discovery first */ static int oidc_authenticate_user(request_rec *r, oidc_cfg *c, oidc_provider_t *provider, const char *original_url, const char *login_hint, const char *id_token_hint, const char *prompt, const char *auth_request_params) { oidc_debug(r, "enter"); if (provider == NULL) { // TODO: should we use an explicit redirect to the discovery endpoint (maybe a "discovery" param to the redirect_uri)? if (c->metadata_dir != NULL) return oidc_discovery(r, c); /* we're not using multiple OP's configured in a metadata directory, pick the statically configured OP */ if (oidc_provider_static_config(r, c, &provider) == FALSE) return HTTP_INTERNAL_SERVER_ERROR; } /* generate the random nonce value that correlates requests and responses */ char *nonce = NULL; if (oidc_proto_generate_nonce(r, &nonce, OIDC_PROTO_NONCE_LENGTH) == FALSE) return HTTP_INTERNAL_SERVER_ERROR; char *code_verifier = NULL; char *code_challenge = NULL; if ((oidc_util_spaced_string_contains(r->pool, provider->response_type, "code") == TRUE) && (provider->pkce_method != NULL)) { /* generate the code verifier value that correlates authorization requests and code exchange requests */ if (oidc_proto_generate_code_verifier(r, &code_verifier, OIDC_PROTO_CODE_VERIFIER_LENGTH) == FALSE) return HTTP_INTERNAL_SERVER_ERROR; /* generate the PKCE code challenge */ if (oidc_proto_generate_code_challenge(r, code_verifier, &code_challenge, provider->pkce_method) == FALSE) return HTTP_INTERNAL_SERVER_ERROR; } /* create the state between request/response */ json_t *proto_state = json_object(); json_object_set_new(proto_state, "original_url", json_string(original_url)); json_object_set_new(proto_state, "original_method", json_string(oidc_original_request_method(r, c, TRUE))); json_object_set_new(proto_state, "issuer", json_string(provider->issuer)); json_object_set_new(proto_state, "response_type", json_string(provider->response_type)); json_object_set_new(proto_state, "nonce", json_string(nonce)); json_object_set_new(proto_state, "timestamp", json_integer(apr_time_sec(apr_time_now()))); if (provider->response_mode) json_object_set_new(proto_state, "response_mode", json_string(provider->response_mode)); if (prompt) json_object_set_new(proto_state, "prompt", json_string(prompt)); if (code_verifier) json_object_set_new(proto_state, "code_verifier", json_string(code_verifier)); /* get a hash value that fingerprints the browser concatenated with the random input */ char *state = oidc_get_browser_state_hash(r, nonce); /* create state that restores the context when the authorization response comes in; cryptographically bind it to the browser */ if (oidc_authorization_request_set_cookie(r, c, state, proto_state) == FALSE) return HTTP_INTERNAL_SERVER_ERROR; /* * printout errors if Cookie settings are not going to work */ apr_uri_t o_uri; memset(&o_uri, 0, sizeof(apr_uri_t)); apr_uri_t r_uri; memset(&r_uri, 0, sizeof(apr_uri_t)); apr_uri_parse(r->pool, original_url, &o_uri); apr_uri_parse(r->pool, c->redirect_uri, &r_uri); if ((apr_strnatcmp(o_uri.scheme, r_uri.scheme) != 0) && (apr_strnatcmp(r_uri.scheme, "https") == 0)) { oidc_error(r, "the URL scheme (%s) of the configured OIDCRedirectURI does not match the URL scheme of the URL being accessed (%s): the \"state\" and \"session\" cookies will not be shared between the two!", r_uri.scheme, o_uri.scheme); return HTTP_INTERNAL_SERVER_ERROR; } if (c->cookie_domain == NULL) { if (apr_strnatcmp(o_uri.hostname, r_uri.hostname) != 0) { char *p = strstr(o_uri.hostname, r_uri.hostname); if ((p == NULL) || (apr_strnatcmp(r_uri.hostname, p) != 0)) { oidc_error(r, "the URL hostname (%s) of the configured OIDCRedirectURI does not match the URL hostname of the URL being accessed (%s): the \"state\" and \"session\" cookies will not be shared between the two!", r_uri.hostname, o_uri.hostname); return HTTP_INTERNAL_SERVER_ERROR; } } } else { if (!oidc_util_cookie_domain_valid(r_uri.hostname, c->cookie_domain)) { oidc_error(r, "the domain (%s) configured in OIDCCookieDomain does not match the URL hostname (%s) of the URL being accessed (%s): setting \"state\" and \"session\" cookies will not work!!", c->cookie_domain, o_uri.hostname, original_url); return HTTP_INTERNAL_SERVER_ERROR; } } /* send off to the OpenID Connect Provider */ // TODO: maybe show intermediate/progress screen "redirecting to" return oidc_proto_authorization_request(r, provider, login_hint, c->redirect_uri, state, proto_state, id_token_hint, code_challenge, auth_request_params); } /* * check if the target_link_uri matches to configuration settings to prevent an open redirect */ static int oidc_target_link_uri_matches_configuration(request_rec *r, oidc_cfg *cfg, const char *target_link_uri) { apr_uri_t o_uri; apr_uri_parse(r->pool, target_link_uri, &o_uri); if (o_uri.hostname == NULL) { oidc_error(r, "could not parse the \"target_link_uri\" (%s) in to a valid URL: aborting.", target_link_uri); return FALSE; } apr_uri_t r_uri; apr_uri_parse(r->pool, cfg->redirect_uri, &r_uri); if (cfg->cookie_domain == NULL) { /* cookie_domain set: see if the target_link_uri matches the redirect_uri host (because the session cookie will be set host-wide) */ if (apr_strnatcmp(o_uri.hostname, r_uri.hostname) != 0) { char *p = strstr(o_uri.hostname, r_uri.hostname); if ((p == NULL) || (apr_strnatcmp(r_uri.hostname, p) != 0)) { oidc_error(r, "the URL hostname (%s) of the configured OIDCRedirectURI does not match the URL hostname of the \"target_link_uri\" (%s): aborting to prevent an open redirect.", r_uri.hostname, o_uri.hostname); return FALSE; } } } else { /* cookie_domain set: see if the target_link_uri is within the cookie_domain */ char *p = strstr(o_uri.hostname, cfg->cookie_domain); if ((p == NULL) || (apr_strnatcmp(cfg->cookie_domain, p) != 0)) { oidc_error(r, "the domain (%s) configured in OIDCCookieDomain does not match the URL hostname (%s) of the \"target_link_uri\" (%s): aborting to prevent an open redirect.", cfg->cookie_domain, o_uri.hostname, target_link_uri); return FALSE; } } /* see if the cookie_path setting matches the target_link_uri path */ char *cookie_path = oidc_cfg_dir_cookie_path(r); if (cookie_path != NULL) { char *p = (o_uri.path != NULL) ? strstr(o_uri.path, cookie_path) : NULL; if ((p == NULL) || (p != o_uri.path)) { oidc_error(r, "the path (%s) configured in OIDCCookiePath does not match the URL path (%s) of the \"target_link_uri\" (%s): aborting to prevent an open redirect.", cfg->cookie_domain, o_uri.path, target_link_uri); return FALSE; } else if (strlen(o_uri.path) > strlen(cookie_path)) { int n = strlen(cookie_path); if (cookie_path[n - 1] == '/') n--; if (o_uri.path[n] != '/') { oidc_error(r, "the path (%s) configured in OIDCCookiePath does not match the URL path (%s) of the \"target_link_uri\" (%s): aborting to prevent an open redirect.", cfg->cookie_domain, o_uri.path, target_link_uri); return FALSE; } } } return TRUE; } /* * handle a response from an IDP discovery page and/or handle 3rd-party initiated SSO */ static int oidc_handle_discovery_response(request_rec *r, oidc_cfg *c) { /* variables to hold the values returned in the response */ char *issuer = NULL, *target_link_uri = NULL, *login_hint = NULL, *auth_request_params = NULL, *csrf_cookie, *csrf_query = NULL, *user = NULL; oidc_provider_t *provider = NULL; oidc_util_get_request_parameter(r, OIDC_DISC_OP_PARAM, &issuer); oidc_util_get_request_parameter(r, OIDC_DISC_USER_PARAM, &user); oidc_util_get_request_parameter(r, OIDC_DISC_RT_PARAM, &target_link_uri); oidc_util_get_request_parameter(r, OIDC_DISC_LH_PARAM, &login_hint); oidc_util_get_request_parameter(r, OIDC_DISC_AR_PARAM, &auth_request_params); oidc_util_get_request_parameter(r, OIDC_CSRF_NAME, &csrf_query); csrf_cookie = oidc_util_get_cookie(r, OIDC_CSRF_NAME); /* do CSRF protection if not 3rd party initiated SSO */ if (csrf_cookie) { /* clean CSRF cookie */ oidc_util_set_cookie(r, OIDC_CSRF_NAME, "", 0); /* compare CSRF cookie value with query parameter value */ if ((csrf_query == NULL) || apr_strnatcmp(csrf_query, csrf_cookie) != 0) { oidc_warn(r, "CSRF protection failed, no Discovery and dynamic client registration will be allowed"); csrf_cookie = NULL; } } // TODO: trim issuer/accountname/domain input and do more input validation oidc_debug(r, "issuer=\"%s\", target_link_uri=\"%s\", login_hint=\"%s\", user=\"%s\"", issuer, target_link_uri, login_hint, user); if (target_link_uri == NULL) { if (c->default_sso_url == NULL) { return oidc_util_html_send_error(r, c->error_template, "Invalid Request", "SSO to this module without specifying a \"target_link_uri\" parameter is not possible because OIDCDefaultURL is not set.", HTTP_INTERNAL_SERVER_ERROR); } target_link_uri = c->default_sso_url; } /* do open redirect prevention */ if (oidc_target_link_uri_matches_configuration(r, c, target_link_uri) == FALSE) { return oidc_util_html_send_error(r, c->error_template, "Invalid Request", "\"target_link_uri\" parameter does not match configuration settings, aborting to prevent an open redirect.", HTTP_UNAUTHORIZED); } /* find out if the user entered an account name or selected an OP manually */ if (user != NULL) { if (login_hint == NULL) login_hint = apr_pstrdup(r->pool, user); /* normalize the user identifier */ if (strstr(user, "https://") != user) user = apr_psprintf(r->pool, "https://%s", user); /* got an user identifier as input, perform OP discovery with that */ if (oidc_proto_url_based_discovery(r, c, user, &issuer) == FALSE) { /* something did not work out, show a user facing error */ return oidc_util_html_send_error(r, c->error_template, "Invalid Request", "Could not resolve the provided user identifier to an OpenID Connect provider; check your syntax.", HTTP_NOT_FOUND); } /* issuer is set now, so let's continue as planned */ } else if (strstr(issuer, "@") != NULL) { if (login_hint == NULL) { login_hint = apr_pstrdup(r->pool, issuer); //char *p = strstr(issuer, "@"); //*p = '\0'; } /* got an account name as input, perform OP discovery with that */ if (oidc_proto_account_based_discovery(r, c, issuer, &issuer) == FALSE) { /* something did not work out, show a user facing error */ return oidc_util_html_send_error(r, c->error_template, "Invalid Request", "Could not resolve the provided account name to an OpenID Connect provider; check your syntax.", HTTP_NOT_FOUND); } /* issuer is set now, so let's continue as planned */ } /* strip trailing '/' */ int n = strlen(issuer); if (issuer[n - 1] == '/') issuer[n - 1] = '\0'; /* try and get metadata from the metadata directories for the selected OP */ if ((oidc_metadata_get(r, c, issuer, &provider, csrf_cookie != NULL) == TRUE) && (provider != NULL)) { /* now we've got a selected OP, send the user there to authenticate */ return oidc_authenticate_user(r, c, provider, target_link_uri, login_hint, NULL, NULL, auth_request_params); } /* something went wrong */ return oidc_util_html_send_error(r, c->error_template, "Invalid Request", "Could not find valid provider metadata for the selected OpenID Connect provider; contact the administrator", HTTP_NOT_FOUND); } static apr_uint32_t oidc_transparent_pixel[17] = { 0x474e5089, 0x0a1a0a0d, 0x0d000000, 0x52444849, 0x01000000, 0x01000000, 0x00000408, 0x0c1cb500, 0x00000002, 0x4144490b, 0x639c7854, 0x0000cffa, 0x02010702, 0x71311c9a, 0x00000000, 0x444e4549, 0x826042ae }; static apr_byte_t oidc_is_front_channel_logout(const char *logout_param_value) { return ((logout_param_value != NULL) && ((apr_strnatcmp(logout_param_value, OIDC_GET_STYLE_LOGOUT_PARAM_VALUE) == 0) || (apr_strnatcmp(logout_param_value, OIDC_IMG_STYLE_LOGOUT_PARAM_VALUE) == 0))); } /* * handle a local logout */ static int oidc_handle_logout_request(request_rec *r, oidc_cfg *c, oidc_session_t *session, const char *url) { oidc_debug(r, "enter (url=%s)", url); /* if there's no remote_user then there's no (stored) session to kill */ if (session->remote_user != NULL) { /* remove session state (cq. cache entry and cookie) */ oidc_session_kill(r, session); } /* see if this is the OP calling us */ if (oidc_is_front_channel_logout(url)) { /* set recommended cache control headers */ apr_table_add(r->err_headers_out, "Cache-Control", "no-cache, no-store"); apr_table_add(r->err_headers_out, "Pragma", "no-cache"); apr_table_add(r->err_headers_out, "P3P", "CAO PSA OUR"); apr_table_add(r->err_headers_out, "Expires", "0"); apr_table_add(r->err_headers_out, "X-Frame-Options", "DENY"); /* see if this is PF-PA style logout in which case we return a transparent pixel */ const char *accept = apr_table_get(r->headers_in, "Accept"); if ((apr_strnatcmp(url, OIDC_IMG_STYLE_LOGOUT_PARAM_VALUE) == 0) || ((accept) && strstr(accept, "image/png"))) { return oidc_util_http_send(r, (const char *) &oidc_transparent_pixel, sizeof(oidc_transparent_pixel), "image/png", DONE); } /* standard HTTP based logout: should be called in an iframe from the OP */ return oidc_util_html_send(r, "Logged Out", NULL, NULL, "<p>Logged Out</p>", DONE); } /* see if we don't need to go somewhere special after killing the session locally */ if (url == NULL) return oidc_util_html_send(r, "Logged Out", NULL, NULL, "<p>Logged Out</p>", DONE); /* send the user to the specified where-to-go-after-logout URL */ apr_table_add(r->headers_out, "Location", url); return HTTP_MOVED_TEMPORARILY; } /* * perform (single) logout */ static int oidc_handle_logout(request_rec *r, oidc_cfg *c, oidc_session_t *session) { /* pickup the command or URL where the user wants to go after logout */ char *url = NULL; oidc_util_get_request_parameter(r, "logout", &url); oidc_debug(r, "enter (url=%s)", url); if (oidc_is_front_channel_logout(url)) { return oidc_handle_logout_request(r, c, session, url); } if ((url == NULL) || (apr_strnatcmp(url, "") == 0)) { url = c->default_slo_url; } else { /* do input validation on the logout parameter value */ const char *error_description = NULL; apr_uri_t uri; if (apr_uri_parse(r->pool, url, &uri) != APR_SUCCESS) { const char *error_description = apr_psprintf(r->pool, "Logout URL malformed: %s", url); oidc_error(r, "%s", error_description); return oidc_util_html_send_error(r, c->error_template, "Malformed URL", error_description, HTTP_INTERNAL_SERVER_ERROR); } if ((strstr(r->hostname, uri.hostname) == NULL) || (strstr(uri.hostname, r->hostname) == NULL)) { error_description = apr_psprintf(r->pool, "logout value \"%s\" does not match the hostname of the current request \"%s\"", apr_uri_unparse(r->pool, &uri, 0), r->hostname); oidc_error(r, "%s", error_description); return oidc_util_html_send_error(r, c->error_template, "Invalid Request", error_description, HTTP_INTERNAL_SERVER_ERROR); } /* validate the URL to prevent HTTP header splitting */ if (((strstr(url, "\n") != NULL) || strstr(url, "\r") != NULL)) { error_description = apr_psprintf(r->pool, "logout value \"%s\" contains illegal \"\n\" or \"\r\" character(s)", url); oidc_error(r, "%s", error_description); return oidc_util_html_send_error(r, c->error_template, "Invalid Request", error_description, HTTP_INTERNAL_SERVER_ERROR); } } const char *end_session_endpoint = NULL; oidc_session_get(r, session, OIDC_LOGOUT_ENDPOINT_SESSION_KEY, &end_session_endpoint); if (end_session_endpoint != NULL) { const char *id_token_hint = NULL; oidc_session_get(r, session, OIDC_IDTOKEN_SESSION_KEY, &id_token_hint); char *logout_request = apr_pstrdup(r->pool, end_session_endpoint); if (id_token_hint != NULL) { logout_request = apr_psprintf(r->pool, "%s%sid_token_hint=%s", logout_request, strchr(logout_request, '?') != NULL ? "&" : "?", oidc_util_escape_string(r, id_token_hint)); } if (url != NULL) { logout_request = apr_psprintf(r->pool, "%s%spost_logout_redirect_uri=%s", logout_request, strchr(logout_request, '?') != NULL ? "&" : "?", oidc_util_escape_string(r, url)); } url = logout_request; } return oidc_handle_logout_request(r, c, session, url); } /* * handle request for JWKs */ int oidc_handle_jwks(request_rec *r, oidc_cfg *c) { /* pickup requested JWKs type */ // char *jwks_type = NULL; // oidc_util_get_request_parameter(r, "jwks", &jwks_type); char *jwks = apr_pstrdup(r->pool, "{ \"keys\" : ["); apr_hash_index_t *hi = NULL; apr_byte_t first = TRUE; oidc_jose_error_t err; if (c->public_keys != NULL) { /* loop over the RSA public keys */ for (hi = apr_hash_first(r->pool, c->public_keys); hi; hi = apr_hash_next(hi)) { const char *s_kid = NULL; oidc_jwk_t *jwk = NULL; char *s_json = NULL; apr_hash_this(hi, (const void**) &s_kid, NULL, (void**) &jwk); if (oidc_jwk_to_json(r->pool, jwk, &s_json, &err) == TRUE) { jwks = apr_psprintf(r->pool, "%s%s %s ", jwks, first ? "" : ",", s_json); first = FALSE; } else { oidc_error(r, "could not convert RSA JWK to JSON using oidc_jwk_to_json: %s", oidc_jose_e2s(r->pool, err)); } } } // TODO: send stuff if first == FALSE? jwks = apr_psprintf(r->pool, "%s ] }", jwks); return oidc_util_http_send(r, jwks, strlen(jwks), "application/json", DONE); } static int oidc_handle_session_management_iframe_op(request_rec *r, oidc_cfg *c, oidc_session_t *session, const char *check_session_iframe) { oidc_debug(r, "enter"); apr_table_add(r->headers_out, "Location", check_session_iframe); return HTTP_MOVED_TEMPORARILY; } static int oidc_handle_session_management_iframe_rp(request_rec *r, oidc_cfg *c, oidc_session_t *session, const char *client_id, const char *check_session_iframe) { oidc_debug(r, "enter"); const char *java_script = " <script type=\"text/javascript\">\n" " var targetOrigin = '%s';\n" " var message = '%s' + ' ' + '%s';\n" " var timerID;\n" "\n" " function checkSession() {\n" " console.log('checkSession: posting ' + message + ' to ' + targetOrigin);\n" " var win = window.parent.document.getElementById('%s').contentWindow;\n" " win.postMessage( message, targetOrigin);\n" " }\n" "\n" " function setTimer() {\n" " checkSession();\n" " timerID = setInterval('checkSession()', %s);\n" " }\n" "\n" " function receiveMessage(e) {\n" " console.log('receiveMessage: ' + e.data + ' from ' + e.origin);\n" " if (e.origin !== targetOrigin ) {\n" " console.log('receiveMessage: cross-site scripting attack?');\n" " return;\n" " }\n" " if (e.data != 'unchanged') {\n" " clearInterval(timerID);\n" " if (e.data == 'changed') {\n" " window.location.href = '%s?session=check';\n" " } else {\n" " window.location.href = '%s?session=logout';\n" " }\n" " }\n" " }\n" "\n" " window.addEventListener('message', receiveMessage, false);\n" "\n" " </script>\n"; /* determine the origin for the check_session_iframe endpoint */ char *origin = apr_pstrdup(r->pool, check_session_iframe); apr_uri_t uri; apr_uri_parse(r->pool, check_session_iframe, &uri); char *p = strstr(origin, uri.path); *p = '\0'; /* the element identifier for the OP iframe */ const char *op_iframe_id = "openidc-op"; /* restore the OP session_state from the session */ const char *session_state = NULL; oidc_session_get(r, session, OIDC_SESSION_STATE_SESSION_KEY, &session_state); if (session_state == NULL) { oidc_warn(r, "no session_state found in the session; the OP does probably not support session management!?"); return DONE; } char *s_poll_interval = NULL; oidc_util_get_request_parameter(r, "poll", &s_poll_interval); if (s_poll_interval == NULL) s_poll_interval = "3000"; java_script = apr_psprintf(r->pool, java_script, origin, client_id, session_state, op_iframe_id, s_poll_interval, c->redirect_uri, c->redirect_uri); return oidc_util_html_send(r, NULL, java_script, "setTimer", NULL, DONE); } /* * handle session management request */ static int oidc_handle_session_management(request_rec *r, oidc_cfg *c, oidc_session_t *session) { char *cmd = NULL; const char *id_token_hint = NULL, *client_id = NULL, *check_session_iframe = NULL; oidc_provider_t *provider = NULL; /* get the command passed to the session management handler */ oidc_util_get_request_parameter(r, "session", &cmd); if (cmd == NULL) { oidc_error(r, "session management handler called with no command"); return HTTP_INTERNAL_SERVER_ERROR; } /* see if this is a local logout during session management */ if (apr_strnatcmp("logout", cmd) == 0) { oidc_debug(r, "[session=logout] calling oidc_handle_logout_request because of session mgmt local logout call."); return oidc_handle_logout_request(r, c, session, c->default_slo_url); } /* see if this is a request for the OP iframe */ if (apr_strnatcmp("iframe_op", cmd) == 0) { oidc_session_get(r, session, OIDC_CHECK_IFRAME_SESSION_KEY, &check_session_iframe); if (check_session_iframe != NULL) { return oidc_handle_session_management_iframe_op(r, c, session, check_session_iframe); } return HTTP_NOT_FOUND; } /* see if this is a request for the RP iframe */ if (apr_strnatcmp("iframe_rp", cmd) == 0) { oidc_session_get(r, session, OIDC_CLIENTID_SESSION_KEY, &client_id); oidc_session_get(r, session, OIDC_CHECK_IFRAME_SESSION_KEY, &check_session_iframe); if ((client_id != NULL) && (check_session_iframe != NULL)) { return oidc_handle_session_management_iframe_rp(r, c, session, client_id, check_session_iframe); } oidc_debug(r, "iframe_rp command issued but no client (%s) and/or no check_session_iframe (%s) set", client_id, check_session_iframe); return HTTP_NOT_FOUND; } /* see if this is a request check the login state with the OP */ if (apr_strnatcmp("check", cmd) == 0) { oidc_session_get(r, session, OIDC_IDTOKEN_SESSION_KEY, &id_token_hint); oidc_get_provider_from_session(r, c, session, &provider); if ((session->remote_user != NULL) && (provider != NULL)) { return oidc_authenticate_user(r, c, provider, apr_psprintf(r->pool, "%s?session=iframe_rp", c->redirect_uri), NULL, id_token_hint, "none", NULL); } oidc_debug(r, "[session=check] calling oidc_handle_logout_request because no session found."); return oidc_session_redirect_parent_window_to_logout(r, c); } /* handle failure in fallthrough */ oidc_error(r, "unknown command: %s", cmd); return HTTP_INTERNAL_SERVER_ERROR; } /* * handle refresh token request */ static int oidc_handle_refresh_token_request(request_rec *r, oidc_cfg *c, oidc_session_t *session) { char *return_to = NULL; char *r_access_token = NULL; char *error_code = NULL; /* get the command passed to the session management handler */ oidc_util_get_request_parameter(r, "refresh", &return_to); oidc_util_get_request_parameter(r, "access_token", &r_access_token); /* check the input parameters */ if (return_to == NULL) { oidc_error(r, "refresh token request handler called with no URL to return to"); return HTTP_INTERNAL_SERVER_ERROR; } if (r_access_token == NULL) { oidc_error(r, "refresh token request handler called with no access_token parameter"); error_code = "no_access_token"; goto end; } char *s_access_token = NULL; oidc_session_get(r, session, OIDC_ACCESSTOKEN_SESSION_KEY, (const char **) &s_access_token); if (s_access_token == NULL) { oidc_error(r, "no existing access_token found in the session, nothing to refresh"); error_code = "no_access_token_exists"; goto end; } /* compare the access_token parameter used for XSRF protection */ if (apr_strnatcmp(s_access_token, r_access_token) != 0) { oidc_error(r, "access_token passed in refresh request does not match the one stored in the session"); error_code = "no_access_token_match"; goto end; } /* get a handle to the provider configuration */ oidc_provider_t *provider = NULL; if (oidc_get_provider_from_session(r, c, session, &provider) == FALSE) { error_code = "session_corruption"; goto end; } /* execute the actual refresh grant */ if (oidc_refresh_access_token(r, c, session, provider, NULL) == FALSE) { oidc_error(r, "access_token could not be refreshed"); error_code = "refresh_failed"; goto end; } /* store the session */ if (oidc_session_save(r, session) == FALSE) { error_code = "session_corruption"; goto end; } end: /* pass optional error message to the return URL */ if (error_code != NULL) return_to = apr_psprintf(r->pool, "%s%serror_code=%s", return_to, strchr(return_to, '?') ? "&" : "?", oidc_util_escape_string(r, error_code)); /* add the redirect location header */ apr_table_add(r->headers_out, "Location", return_to); return HTTP_MOVED_TEMPORARILY; } /* * handle request object by reference request */ static int oidc_handle_request_uri(request_rec *r, oidc_cfg *c) { char *request_ref = NULL; oidc_util_get_request_parameter(r, "request_uri", &request_ref); if (request_ref == NULL) { oidc_error(r, "no \"request_uri\" parameter found"); return HTTP_BAD_REQUEST; } const char *jwt = NULL; c->cache->get(r, OIDC_CACHE_SECTION_REQUEST_URI, request_ref, &jwt); if (jwt == NULL) { oidc_error(r, "no cached JWT found for request_uri reference: %s", request_ref); return HTTP_NOT_FOUND; } c->cache->set(r, OIDC_CACHE_SECTION_REQUEST_URI, request_ref, NULL, 0); return oidc_util_http_send(r, jwt, strlen(jwt), " application/jwt", DONE); } /* * handle a request to invalidate a cached access token introspection result */ static int oidc_handle_remove_at_cache(request_rec *r, oidc_cfg *c) { char *access_token = NULL; oidc_util_get_request_parameter(r, "remove_at_cache", &access_token); const char *cache_entry = NULL; c->cache->get(r, OIDC_CACHE_SECTION_ACCESS_TOKEN, access_token, &cache_entry); if (cache_entry == NULL) { oidc_error(r, "no cached access token found for value: %s", access_token); return HTTP_NOT_FOUND; } c->cache->set(r, OIDC_CACHE_SECTION_ACCESS_TOKEN, access_token, NULL, 0); return DONE; } /* * handle all requests to the redirect_uri */ int oidc_handle_redirect_uri_request(request_rec *r, oidc_cfg *c, oidc_session_t *session) { if (oidc_proto_is_redirect_authorization_response(r, c)) { /* this is an authorization response from the OP using the Basic Client profile or a Hybrid flow*/ return oidc_handle_redirect_authorization_response(r, c, session); } else if (oidc_proto_is_post_authorization_response(r, c)) { /* this is an authorization response using the fragment(+POST) response_mode with the Implicit Client profile */ return oidc_handle_post_authorization_response(r, c, session); } else if (oidc_is_discovery_response(r, c)) { /* this is response from the OP discovery page */ return oidc_handle_discovery_response(r, c); } else if (oidc_util_request_has_parameter(r, "logout")) { /* handle logout */ return oidc_handle_logout(r, c, session); } else if (oidc_util_request_has_parameter(r, "jwks")) { /* handle JWKs request */ return oidc_handle_jwks(r, c); } else if (oidc_util_request_has_parameter(r, "session")) { /* handle session management request */ return oidc_handle_session_management(r, c, session); } else if (oidc_util_request_has_parameter(r, "refresh")) { /* handle refresh token request */ return oidc_handle_refresh_token_request(r, c, session); } else if (oidc_util_request_has_parameter(r, "request_uri")) { /* handle request object by reference request */ return oidc_handle_request_uri(r, c); } else if (oidc_util_request_has_parameter(r, "remove_at_cache")) { /* handle request to invalidate access token cache */ return oidc_handle_remove_at_cache(r, c); } else if ((r->args == NULL) || (apr_strnatcmp(r->args, "") == 0)) { /* this is a "bare" request to the redirect URI, indicating implicit flow using the fragment response_mode */ return oidc_proto_javascript_implicit(r, c); } /* this is not an authorization response or logout request */ /* check for "error" response */ if (oidc_util_request_has_parameter(r, "error")) { // char *error = NULL, *descr = NULL; // oidc_util_get_request_parameter(r, "error", &error); // oidc_util_get_request_parameter(r, "error_description", &descr); // // /* send user facing error to browser */ // return oidc_util_html_send_error(r, error, descr, DONE); oidc_handle_redirect_authorization_response(r, c, session); } /* something went wrong */ return oidc_util_html_send_error(r, c->error_template, "Invalid Request", apr_psprintf(r->pool, "The OpenID Connect callback URL received an invalid request"), HTTP_INTERNAL_SERVER_ERROR); } /* * main routine: handle OpenID Connect authentication */ static int oidc_check_userid_openidc(request_rec *r, oidc_cfg *c) { if (c->redirect_uri == NULL) { oidc_error(r, "configuration error: the authentication type is set to \"openid-connect\" but OIDCRedirectURI has not been set"); return HTTP_INTERNAL_SERVER_ERROR; } /* check if this is a sub-request or an initial request */ if (ap_is_initial_req(r)) { int rc = OK; /* load the session from the request state; this will be a new "empty" session if no state exists */ oidc_session_t *session = NULL; oidc_session_load(r, &session); /* see if the initial request is to the redirect URI; this handles potential logout too */ if (oidc_util_request_matches_url(r, c->redirect_uri)) { /* handle request to the redirect_uri */ rc = oidc_handle_redirect_uri_request(r, c, session); /* free resources allocated for the session */ oidc_session_free(r, session); return rc; /* initial request to non-redirect URI, check if we have an existing session */ } else if (session->remote_user != NULL) { /* set the user in the main request for further (incl. sub-request) processing */ r->user = (char *) session->remote_user; /* this is initial request and we already have a session */ rc = oidc_handle_existing_session(r, c, session); /* free resources allocated for the session */ oidc_session_free(r, session); /* strip any cookies that we need to */ oidc_strip_cookies(r); return rc; } /* free resources allocated for the session */ oidc_session_free(r, session); /* * else: initial request, we have no session and it is not an authorization or * discovery response: just hit the default flow for unauthenticated users */ } else { /* not an initial request, try to recycle what we've already established in the main request */ if (r->main != NULL) r->user = r->main->user; else if (r->prev != NULL) r->user = r->prev->user; if (r->user != NULL) { /* this is a sub-request and we have a session (headers will have been scrubbed and set already) */ oidc_debug(r, "recycling user '%s' from initial request for sub-request", r->user); /* * apparently request state can get lost in sub-requests, so let's see * if we need to restore id_token and/or claims from the session cache */ const char *s_id_token = oidc_request_state_get(r, OIDC_IDTOKEN_CLAIMS_SESSION_KEY); if (s_id_token == NULL) { oidc_session_t *session = NULL; oidc_session_load(r, &session); oidc_copy_tokens_to_request_state(r, session, NULL, NULL); /* free resources allocated for the session */ oidc_session_free(r, session); } /* strip any cookies that we need to */ oidc_strip_cookies(r); return OK; } /* * else: not initial request, but we could not find a session, so: * just hit the default flow for unauthenticated users */ } /* find out which action we need to take when encountering an unauthenticated request */ switch (oidc_dir_cfg_unauth_action(r)) { case OIDC_UNAUTH_RETURN410: return HTTP_GONE; case OIDC_UNAUTH_RETURN401: return HTTP_UNAUTHORIZED; case OIDC_UNAUTH_PASS: r->user = ""; return OK; case OIDC_UNAUTH_AUTHENTICATE: /* if this is a Javascript path we won't redirect the user and create a state cookie */ if (apr_table_get(r->headers_in, "X-Requested-With") != NULL) return HTTP_UNAUTHORIZED; break; } /* else: no session (regardless of whether it is main or sub-request), go and authenticate the user */ return oidc_authenticate_user(r, c, NULL, oidc_get_current_url(r), NULL, NULL, NULL, NULL); } /* * generic Apache authentication hook for this module: dispatches to OpenID Connect or OAuth 2.0 specific routines */ int oidc_check_user_id(request_rec *r) { oidc_cfg *c = ap_get_module_config(r->server->module_config, &auth_openidc_module); /* log some stuff about the incoming HTTP request */ oidc_debug(r, "incoming request: \"%s?%s\", ap_is_initial_req(r)=%d", r->parsed_uri.path, r->args, ap_is_initial_req(r)); /* see if any authentication has been defined at all */ if (ap_auth_type(r) == NULL) return DECLINED; /* see if we've configured OpenID Connect user authentication for this request */ if (apr_strnatcasecmp((const char *) ap_auth_type(r), "openid-connect") == 0) return oidc_check_userid_openidc(r, c); /* see if we've configured OAuth 2.0 access control for this request */ if (apr_strnatcasecmp((const char *) ap_auth_type(r), "oauth20") == 0) return oidc_oauth_check_userid(r, c); /* this is not for us but for some other handler */ return DECLINED; } /* * get the claims and id_token from request state */ static void oidc_authz_get_claims_and_idtoken(request_rec *r, json_t **claims, json_t **id_token) { const char *s_claims = oidc_request_state_get(r, OIDC_CLAIMS_SESSION_KEY); const char *s_id_token = oidc_request_state_get(r, OIDC_IDTOKEN_CLAIMS_SESSION_KEY); json_error_t json_error; if (s_claims != NULL) { *claims = json_loads(s_claims, 0, &json_error); if (*claims == NULL) { oidc_error(r, "could not restore claims from request state: %s", json_error.text); } } if (s_id_token != NULL) { *id_token = json_loads(s_id_token, 0, &json_error); if (*id_token == NULL) { oidc_error(r, "could not restore id_token from request state: %s", json_error.text); } } } #if MODULE_MAGIC_NUMBER_MAJOR >= 20100714 /* * generic Apache >=2.4 authorization hook for this module * handles both OpenID Connect or OAuth 2.0 in the same way, based on the claims stored in the session */ authz_status oidc_authz_checker(request_rec *r, const char *require_args, const void *parsed_require_args) { /* check for anonymous access and PASS mode */ if (r->user != NULL && strlen(r->user) == 0) { r->user = NULL; if (oidc_dir_cfg_unauth_action(r) == OIDC_UNAUTH_PASS) return AUTHZ_GRANTED; } /* get the set of claims from the request state (they've been set in the authentication part earlier */ json_t *claims = NULL, *id_token = NULL; oidc_authz_get_claims_and_idtoken(r, &claims, &id_token); /* merge id_token claims (e.g. "iss") in to claims json object */ if (claims) oidc_util_json_merge(id_token, claims); /* dispatch to the >=2.4 specific authz routine */ authz_status rc = oidc_authz_worker24(r, claims ? claims : id_token, require_args); /* cleanup */ if (claims) json_decref(claims); if (id_token) json_decref(id_token); if ((rc == AUTHZ_DENIED) && ap_auth_type(r) && (apr_strnatcasecmp((const char *) ap_auth_type(r), "oauth20") == 0)) oidc_oauth_return_www_authenticate(r, "insufficient_scope", "Different scope(s) or other claims required"); return rc; } #else /* * generic Apache <2.4 authorization hook for this module * handles both OpenID Connect and OAuth 2.0 in the same way, based on the claims stored in the request context */ int oidc_auth_checker(request_rec *r) { /* check for anonymous access and PASS mode */ if (r->user != NULL && strlen(r->user) == 0) { r->user = NULL; if (oidc_dir_cfg_unauth_action(r) == OIDC_UNAUTH_PASS) return OK; } /* get the set of claims from the request state (they've been set in the authentication part earlier */ json_t *claims = NULL, *id_token = NULL; oidc_authz_get_claims_and_idtoken(r, &claims, &id_token); /* get the Require statements */ const apr_array_header_t * const reqs_arr = ap_requires(r); /* see if we have any */ const require_line * const reqs = reqs_arr ? (require_line *) reqs_arr->elts : NULL; if (!reqs_arr) { oidc_debug(r, "no require statements found, so declining to perform authorization."); return DECLINED; } /* merge id_token claims (e.g. "iss") in to claims json object */ if (claims) oidc_util_json_merge(id_token, claims); /* dispatch to the <2.4 specific authz routine */ int rc = oidc_authz_worker(r, claims ? claims : id_token, reqs, reqs_arr->nelts); /* cleanup */ if (claims) json_decref(claims); if (id_token) json_decref(id_token); if ((rc == HTTP_UNAUTHORIZED) && ap_auth_type(r) && (apr_strnatcasecmp((const char *) ap_auth_type(r), "oauth20") == 0)) oidc_oauth_return_www_authenticate(r, "insufficient_scope", "Different scope(s) or other claims required"); return rc; } #endif extern const command_rec oidc_config_cmds[]; module AP_MODULE_DECLARE_DATA auth_openidc_module = { STANDARD20_MODULE_STUFF, oidc_create_dir_config, oidc_merge_dir_config, oidc_create_server_config, oidc_merge_server_config, oidc_config_cmds, oidc_register_hooks };
./CrossVul/dataset_final_sorted/CWE-20/c/good_3160_1
crossvul-cpp_data_bad_5844_6
/* * L2TPv3 IP encapsulation support * * Copyright (c) 2008,2009,2010 Katalix Systems Ltd * * 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. */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/icmp.h> #include <linux/module.h> #include <linux/skbuff.h> #include <linux/random.h> #include <linux/socket.h> #include <linux/l2tp.h> #include <linux/in.h> #include <net/sock.h> #include <net/ip.h> #include <net/icmp.h> #include <net/udp.h> #include <net/inet_common.h> #include <net/inet_hashtables.h> #include <net/tcp_states.h> #include <net/protocol.h> #include <net/xfrm.h> #include "l2tp_core.h" struct l2tp_ip_sock { /* inet_sock has to be the first member of l2tp_ip_sock */ struct inet_sock inet; u32 conn_id; u32 peer_conn_id; }; static DEFINE_RWLOCK(l2tp_ip_lock); static struct hlist_head l2tp_ip_table; static struct hlist_head l2tp_ip_bind_table; static inline struct l2tp_ip_sock *l2tp_ip_sk(const struct sock *sk) { return (struct l2tp_ip_sock *)sk; } static struct sock *__l2tp_ip_bind_lookup(struct net *net, __be32 laddr, int dif, u32 tunnel_id) { struct sock *sk; sk_for_each_bound(sk, &l2tp_ip_bind_table) { struct inet_sock *inet = inet_sk(sk); struct l2tp_ip_sock *l2tp = l2tp_ip_sk(sk); if (l2tp == NULL) continue; if ((l2tp->conn_id == tunnel_id) && net_eq(sock_net(sk), net) && !(inet->inet_rcv_saddr && inet->inet_rcv_saddr != laddr) && !(sk->sk_bound_dev_if && sk->sk_bound_dev_if != dif)) goto found; } sk = NULL; found: return sk; } static inline struct sock *l2tp_ip_bind_lookup(struct net *net, __be32 laddr, int dif, u32 tunnel_id) { struct sock *sk = __l2tp_ip_bind_lookup(net, laddr, dif, tunnel_id); if (sk) sock_hold(sk); return sk; } /* When processing receive frames, there are two cases to * consider. Data frames consist of a non-zero session-id and an * optional cookie. Control frames consist of a regular L2TP header * preceded by 32-bits of zeros. * * L2TPv3 Session Header Over IP * * 0 1 2 3 * 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 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Session ID | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Cookie (optional, maximum 64 bits)... * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * * L2TPv3 Control Message Header Over IP * * 0 1 2 3 * 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 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | (32 bits of zeros) | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * |T|L|x|x|S|x|x|x|x|x|x|x| Ver | Length | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Control Connection ID | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Ns | Nr | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * * All control frames are passed to userspace. */ static int l2tp_ip_recv(struct sk_buff *skb) { struct net *net = dev_net(skb->dev); struct sock *sk; u32 session_id; u32 tunnel_id; unsigned char *ptr, *optr; struct l2tp_session *session; struct l2tp_tunnel *tunnel = NULL; int length; /* Point to L2TP header */ optr = ptr = skb->data; if (!pskb_may_pull(skb, 4)) goto discard; session_id = ntohl(*((__be32 *) ptr)); ptr += 4; /* RFC3931: L2TP/IP packets have the first 4 bytes containing * the session_id. If it is 0, the packet is a L2TP control * frame and the session_id value can be discarded. */ if (session_id == 0) { __skb_pull(skb, 4); goto pass_up; } /* Ok, this is a data packet. Lookup the session. */ session = l2tp_session_find(net, NULL, session_id); if (session == NULL) goto discard; tunnel = session->tunnel; if (tunnel == NULL) goto discard; /* Trace packet contents, if enabled */ if (tunnel->debug & L2TP_MSG_DATA) { length = min(32u, skb->len); if (!pskb_may_pull(skb, length)) goto discard; pr_debug("%s: ip recv\n", tunnel->name); print_hex_dump_bytes("", DUMP_PREFIX_OFFSET, ptr, length); } l2tp_recv_common(session, skb, ptr, optr, 0, skb->len, tunnel->recv_payload_hook); return 0; pass_up: /* Get the tunnel_id from the L2TP header */ if (!pskb_may_pull(skb, 12)) goto discard; if ((skb->data[0] & 0xc0) != 0xc0) goto discard; tunnel_id = ntohl(*(__be32 *) &skb->data[4]); tunnel = l2tp_tunnel_find(net, tunnel_id); if (tunnel != NULL) sk = tunnel->sock; else { struct iphdr *iph = (struct iphdr *) skb_network_header(skb); read_lock_bh(&l2tp_ip_lock); sk = __l2tp_ip_bind_lookup(net, iph->daddr, 0, tunnel_id); read_unlock_bh(&l2tp_ip_lock); } if (sk == NULL) goto discard; sock_hold(sk); if (!xfrm4_policy_check(sk, XFRM_POLICY_IN, skb)) goto discard_put; nf_reset(skb); return sk_receive_skb(sk, skb, 1); discard_put: sock_put(sk); discard: kfree_skb(skb); return 0; } static int l2tp_ip_open(struct sock *sk) { /* Prevent autobind. We don't have ports. */ inet_sk(sk)->inet_num = IPPROTO_L2TP; write_lock_bh(&l2tp_ip_lock); sk_add_node(sk, &l2tp_ip_table); write_unlock_bh(&l2tp_ip_lock); return 0; } static void l2tp_ip_close(struct sock *sk, long timeout) { write_lock_bh(&l2tp_ip_lock); hlist_del_init(&sk->sk_bind_node); sk_del_node_init(sk); write_unlock_bh(&l2tp_ip_lock); sk_common_release(sk); } static void l2tp_ip_destroy_sock(struct sock *sk) { struct sk_buff *skb; struct l2tp_tunnel *tunnel = l2tp_sock_to_tunnel(sk); while ((skb = __skb_dequeue_tail(&sk->sk_write_queue)) != NULL) kfree_skb(skb); if (tunnel) { l2tp_tunnel_closeall(tunnel); sock_put(sk); } sk_refcnt_debug_dec(sk); } static int l2tp_ip_bind(struct sock *sk, struct sockaddr *uaddr, int addr_len) { struct inet_sock *inet = inet_sk(sk); struct sockaddr_l2tpip *addr = (struct sockaddr_l2tpip *) uaddr; struct net *net = sock_net(sk); int ret; int chk_addr_ret; if (!sock_flag(sk, SOCK_ZAPPED)) return -EINVAL; if (addr_len < sizeof(struct sockaddr_l2tpip)) return -EINVAL; if (addr->l2tp_family != AF_INET) return -EINVAL; ret = -EADDRINUSE; read_lock_bh(&l2tp_ip_lock); if (__l2tp_ip_bind_lookup(net, addr->l2tp_addr.s_addr, sk->sk_bound_dev_if, addr->l2tp_conn_id)) goto out_in_use; read_unlock_bh(&l2tp_ip_lock); lock_sock(sk); if (sk->sk_state != TCP_CLOSE || addr_len < sizeof(struct sockaddr_l2tpip)) goto out; chk_addr_ret = inet_addr_type(net, addr->l2tp_addr.s_addr); ret = -EADDRNOTAVAIL; if (addr->l2tp_addr.s_addr && chk_addr_ret != RTN_LOCAL && chk_addr_ret != RTN_MULTICAST && chk_addr_ret != RTN_BROADCAST) goto out; if (addr->l2tp_addr.s_addr) inet->inet_rcv_saddr = inet->inet_saddr = addr->l2tp_addr.s_addr; if (chk_addr_ret == RTN_MULTICAST || chk_addr_ret == RTN_BROADCAST) inet->inet_saddr = 0; /* Use device */ sk_dst_reset(sk); l2tp_ip_sk(sk)->conn_id = addr->l2tp_conn_id; write_lock_bh(&l2tp_ip_lock); sk_add_bind_node(sk, &l2tp_ip_bind_table); sk_del_node_init(sk); write_unlock_bh(&l2tp_ip_lock); ret = 0; sock_reset_flag(sk, SOCK_ZAPPED); out: release_sock(sk); return ret; out_in_use: read_unlock_bh(&l2tp_ip_lock); return ret; } static int l2tp_ip_connect(struct sock *sk, struct sockaddr *uaddr, int addr_len) { struct sockaddr_l2tpip *lsa = (struct sockaddr_l2tpip *) uaddr; int rc; if (sock_flag(sk, SOCK_ZAPPED)) /* Must bind first - autobinding does not work */ return -EINVAL; if (addr_len < sizeof(*lsa)) return -EINVAL; if (ipv4_is_multicast(lsa->l2tp_addr.s_addr)) return -EINVAL; rc = ip4_datagram_connect(sk, uaddr, addr_len); if (rc < 0) return rc; lock_sock(sk); l2tp_ip_sk(sk)->peer_conn_id = lsa->l2tp_conn_id; write_lock_bh(&l2tp_ip_lock); hlist_del_init(&sk->sk_bind_node); sk_add_bind_node(sk, &l2tp_ip_bind_table); write_unlock_bh(&l2tp_ip_lock); release_sock(sk); return rc; } static int l2tp_ip_disconnect(struct sock *sk, int flags) { if (sock_flag(sk, SOCK_ZAPPED)) return 0; return udp_disconnect(sk, flags); } static int l2tp_ip_getname(struct socket *sock, struct sockaddr *uaddr, int *uaddr_len, int peer) { struct sock *sk = sock->sk; struct inet_sock *inet = inet_sk(sk); struct l2tp_ip_sock *lsk = l2tp_ip_sk(sk); struct sockaddr_l2tpip *lsa = (struct sockaddr_l2tpip *)uaddr; memset(lsa, 0, sizeof(*lsa)); lsa->l2tp_family = AF_INET; if (peer) { if (!inet->inet_dport) return -ENOTCONN; lsa->l2tp_conn_id = lsk->peer_conn_id; lsa->l2tp_addr.s_addr = inet->inet_daddr; } else { __be32 addr = inet->inet_rcv_saddr; if (!addr) addr = inet->inet_saddr; lsa->l2tp_conn_id = lsk->conn_id; lsa->l2tp_addr.s_addr = addr; } *uaddr_len = sizeof(*lsa); return 0; } static int l2tp_ip_backlog_recv(struct sock *sk, struct sk_buff *skb) { int rc; /* Charge it to the socket, dropping if the queue is full. */ rc = sock_queue_rcv_skb(sk, skb); if (rc < 0) goto drop; return 0; drop: IP_INC_STATS(sock_net(sk), IPSTATS_MIB_INDISCARDS); kfree_skb(skb); return -1; } /* Userspace will call sendmsg() on the tunnel socket to send L2TP * control frames. */ static int l2tp_ip_sendmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg, size_t len) { struct sk_buff *skb; int rc; struct inet_sock *inet = inet_sk(sk); struct rtable *rt = NULL; struct flowi4 *fl4; int connected = 0; __be32 daddr; lock_sock(sk); rc = -ENOTCONN; if (sock_flag(sk, SOCK_DEAD)) goto out; /* Get and verify the address. */ if (msg->msg_name) { struct sockaddr_l2tpip *lip = (struct sockaddr_l2tpip *) msg->msg_name; rc = -EINVAL; if (msg->msg_namelen < sizeof(*lip)) goto out; if (lip->l2tp_family != AF_INET) { rc = -EAFNOSUPPORT; if (lip->l2tp_family != AF_UNSPEC) goto out; } daddr = lip->l2tp_addr.s_addr; } else { rc = -EDESTADDRREQ; if (sk->sk_state != TCP_ESTABLISHED) goto out; daddr = inet->inet_daddr; connected = 1; } /* Allocate a socket buffer */ rc = -ENOMEM; skb = sock_wmalloc(sk, 2 + NET_SKB_PAD + sizeof(struct iphdr) + 4 + len, 0, GFP_KERNEL); if (!skb) goto error; /* Reserve space for headers, putting IP header on 4-byte boundary. */ skb_reserve(skb, 2 + NET_SKB_PAD); skb_reset_network_header(skb); skb_reserve(skb, sizeof(struct iphdr)); skb_reset_transport_header(skb); /* Insert 0 session_id */ *((__be32 *) skb_put(skb, 4)) = 0; /* Copy user data into skb */ rc = memcpy_fromiovec(skb_put(skb, len), msg->msg_iov, len); if (rc < 0) { kfree_skb(skb); goto error; } fl4 = &inet->cork.fl.u.ip4; if (connected) rt = (struct rtable *) __sk_dst_check(sk, 0); rcu_read_lock(); if (rt == NULL) { const struct ip_options_rcu *inet_opt; inet_opt = rcu_dereference(inet->inet_opt); /* Use correct destination address if we have options. */ if (inet_opt && inet_opt->opt.srr) daddr = inet_opt->opt.faddr; /* If this fails, retransmit mechanism of transport layer will * keep trying until route appears or the connection times * itself out. */ rt = ip_route_output_ports(sock_net(sk), fl4, sk, daddr, inet->inet_saddr, inet->inet_dport, inet->inet_sport, sk->sk_protocol, RT_CONN_FLAGS(sk), sk->sk_bound_dev_if); if (IS_ERR(rt)) goto no_route; if (connected) { sk_setup_caps(sk, &rt->dst); } else { skb_dst_set(skb, &rt->dst); goto xmit; } } /* We dont need to clone dst here, it is guaranteed to not disappear. * __dev_xmit_skb() might force a refcount if needed. */ skb_dst_set_noref(skb, &rt->dst); xmit: /* Queue the packet to IP for output */ rc = ip_queue_xmit(skb, &inet->cork.fl); rcu_read_unlock(); error: if (rc >= 0) rc = len; out: release_sock(sk); return rc; no_route: rcu_read_unlock(); IP_INC_STATS(sock_net(sk), IPSTATS_MIB_OUTNOROUTES); kfree_skb(skb); rc = -EHOSTUNREACH; goto out; } static int l2tp_ip_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg, size_t len, int noblock, int flags, int *addr_len) { struct inet_sock *inet = inet_sk(sk); size_t copied = 0; int err = -EOPNOTSUPP; struct sockaddr_in *sin = (struct sockaddr_in *)msg->msg_name; struct sk_buff *skb; if (flags & MSG_OOB) goto out; if (addr_len) *addr_len = sizeof(*sin); skb = skb_recv_datagram(sk, flags, noblock, &err); if (!skb) goto out; copied = skb->len; if (len < copied) { msg->msg_flags |= MSG_TRUNC; copied = len; } err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied); if (err) goto done; sock_recv_timestamp(msg, sk, skb); /* Copy the address. */ if (sin) { sin->sin_family = AF_INET; sin->sin_addr.s_addr = ip_hdr(skb)->saddr; sin->sin_port = 0; memset(&sin->sin_zero, 0, sizeof(sin->sin_zero)); } if (inet->cmsg_flags) ip_cmsg_recv(msg, skb); if (flags & MSG_TRUNC) copied = skb->len; done: skb_free_datagram(sk, skb); out: return err ? err : copied; } static struct proto l2tp_ip_prot = { .name = "L2TP/IP", .owner = THIS_MODULE, .init = l2tp_ip_open, .close = l2tp_ip_close, .bind = l2tp_ip_bind, .connect = l2tp_ip_connect, .disconnect = l2tp_ip_disconnect, .ioctl = udp_ioctl, .destroy = l2tp_ip_destroy_sock, .setsockopt = ip_setsockopt, .getsockopt = ip_getsockopt, .sendmsg = l2tp_ip_sendmsg, .recvmsg = l2tp_ip_recvmsg, .backlog_rcv = l2tp_ip_backlog_recv, .hash = inet_hash, .unhash = inet_unhash, .obj_size = sizeof(struct l2tp_ip_sock), #ifdef CONFIG_COMPAT .compat_setsockopt = compat_ip_setsockopt, .compat_getsockopt = compat_ip_getsockopt, #endif }; static const struct proto_ops l2tp_ip_ops = { .family = PF_INET, .owner = THIS_MODULE, .release = inet_release, .bind = inet_bind, .connect = inet_dgram_connect, .socketpair = sock_no_socketpair, .accept = sock_no_accept, .getname = l2tp_ip_getname, .poll = datagram_poll, .ioctl = inet_ioctl, .listen = sock_no_listen, .shutdown = inet_shutdown, .setsockopt = sock_common_setsockopt, .getsockopt = sock_common_getsockopt, .sendmsg = inet_sendmsg, .recvmsg = sock_common_recvmsg, .mmap = sock_no_mmap, .sendpage = sock_no_sendpage, #ifdef CONFIG_COMPAT .compat_setsockopt = compat_sock_common_setsockopt, .compat_getsockopt = compat_sock_common_getsockopt, #endif }; static struct inet_protosw l2tp_ip_protosw = { .type = SOCK_DGRAM, .protocol = IPPROTO_L2TP, .prot = &l2tp_ip_prot, .ops = &l2tp_ip_ops, .no_check = 0, }; static struct net_protocol l2tp_ip_protocol __read_mostly = { .handler = l2tp_ip_recv, .netns_ok = 1, }; static int __init l2tp_ip_init(void) { int err; pr_info("L2TP IP encapsulation support (L2TPv3)\n"); err = proto_register(&l2tp_ip_prot, 1); if (err != 0) goto out; err = inet_add_protocol(&l2tp_ip_protocol, IPPROTO_L2TP); if (err) goto out1; inet_register_protosw(&l2tp_ip_protosw); return 0; out1: proto_unregister(&l2tp_ip_prot); out: return err; } static void __exit l2tp_ip_exit(void) { inet_unregister_protosw(&l2tp_ip_protosw); inet_del_protocol(&l2tp_ip_protocol, IPPROTO_L2TP); proto_unregister(&l2tp_ip_prot); } module_init(l2tp_ip_init); module_exit(l2tp_ip_exit); MODULE_LICENSE("GPL"); MODULE_AUTHOR("James Chapman <jchapman@katalix.com>"); MODULE_DESCRIPTION("L2TP over IP"); MODULE_VERSION("1.0"); /* Use the value of SOCK_DGRAM (2) directory, because __stringify doesn't like * enums */ MODULE_ALIAS_NET_PF_PROTO_TYPE(PF_INET, 2, IPPROTO_L2TP);
./CrossVul/dataset_final_sorted/CWE-20/c/bad_5844_6
crossvul-cpp_data_good_906_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % CCC U U TTTTT % % C U U T % % C U U T % % C U U T % % CCC UUU T % % % % % % Read DR Halo Image Format % % % % Software Design % % Jaroslav Fojtik % % June 2000 % % % % % % Permission is hereby granted, free of charge, to any person obtaining a % % copy of this software and associated documentation files ("ImageMagick"), % % to deal in ImageMagick without restriction, including without limitation % % the rights to use, copy, modify, merge, publish, distribute, sublicense, % % and/or sell copies of ImageMagick, and to permit persons to whom the % % ImageMagick is furnished to do so, subject to the following conditions: % % % % The above copyright notice and this permission notice shall be included in % % all copies or substantial portions of ImageMagick. % % % % The software is provided "as is", without warranty of any kind, express or % % implied, including but not limited to the warranties of merchantability, % % fitness for a particular purpose and noninfringement. In no event shall % % ImageMagick Studio be liable for any claim, damages or other liability, % % whether in an action of contract, tort or otherwise, arising from, out of % % or in connection with ImageMagick or the use or other dealings in % % ImageMagick. % % % % Except as contained in this notice, the name of the ImageMagick Studio % % shall not be used in advertising or otherwise to promote the sale, use or % % other dealings in ImageMagick without prior written authorization from the % % ImageMagick Studio. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* 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/colormap-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/pixel-accessor.h" #include "MagickCore/quantum-private.h" #include "MagickCore/static.h" #include "MagickCore/string_.h" #include "MagickCore/module.h" #include "MagickCore/utility.h" #include "MagickCore/utility-private.h" typedef struct { unsigned Width; unsigned Height; unsigned Reserved; } CUTHeader; typedef struct { char FileId[2]; unsigned Version; unsigned Size; char FileType; char SubType; unsigned BoardID; unsigned GraphicsMode; unsigned MaxIndex; unsigned MaxRed; unsigned MaxGreen; unsigned MaxBlue; char PaletteId[20]; } CUTPalHeader; static MagickBooleanType InsertRow(Image *image,ssize_t bpp,unsigned char *p, ssize_t y,ExceptionInfo *exception) { int bit; Quantum index; register Quantum *q; ssize_t x; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) return(MagickFalse); switch (bpp) { case 1: /* Convert bitmap scanline. */ { for (x=0; x < ((ssize_t) image->columns-7); x+=8) { for (bit=0; bit < 8; bit++) { index=((*p) & (0x80 >> bit) ? 0x01 : 0x00); SetPixelIndex(image,index,q); if (index < image->colors) SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q); q+=GetPixelChannels(image); } p++; } if ((image->columns % 8) != 0) { for (bit=0; bit < (ssize_t) (image->columns % 8); bit++) { index=((*p) & (0x80 >> bit) ? 0x01 : 0x00); SetPixelIndex(image,index,q); if (index < image->colors) SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q); SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q); q+=GetPixelChannels(image); } p++; } break; } case 2: /* Convert PseudoColor scanline. */ { for (x=0; x < ((ssize_t) image->columns-3); x+=4) { index=ConstrainColormapIndex(image,(*p >> 6) & 0x3,exception); SetPixelIndex(image,index,q); if (index < image->colors) SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q); q+=GetPixelChannels(image); index=ConstrainColormapIndex(image,(*p >> 4) & 0x3,exception); SetPixelIndex(image,index,q); if (index < image->colors) SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q); q+=GetPixelChannels(image); index=ConstrainColormapIndex(image,(*p >> 2) & 0x3,exception); SetPixelIndex(image,index,q); if (index < image->colors) SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q); q+=GetPixelChannels(image); index=ConstrainColormapIndex(image,(*p) & 0x3,exception); SetPixelIndex(image,index,q); if (index < image->colors) SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q); q+=GetPixelChannels(image); p++; } if ((image->columns % 4) != 0) { index=ConstrainColormapIndex(image,(*p >> 6) & 0x3,exception); SetPixelIndex(image,index,q); if (index < image->colors) SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q); q+=GetPixelChannels(image); if ((image->columns % 4) > 1) { index=ConstrainColormapIndex(image,(*p >> 4) & 0x3,exception); SetPixelIndex(image,index,q); if (index < image->colors) SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q); q+=GetPixelChannels(image); if ((image->columns % 4) > 2) { index=ConstrainColormapIndex(image,(*p >> 2) & 0x3, exception); SetPixelIndex(image,index,q); if (index < image->colors) SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q); q+=GetPixelChannels(image); } } p++; } break; } case 4: /* Convert PseudoColor scanline. */ { for (x=0; x < ((ssize_t) image->columns-1); x+=2) { index=ConstrainColormapIndex(image,(*p >> 4) & 0x0f,exception); SetPixelIndex(image,index,q); if (index < image->colors) SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q); q+=GetPixelChannels(image); index=ConstrainColormapIndex(image,(*p) & 0x0f,exception); SetPixelIndex(image,index,q); if (index < image->colors) SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q); p++; q+=GetPixelChannels(image); } if ((image->columns % 2) != 0) { index=ConstrainColormapIndex(image,(*p >> 4) & 0x0f,exception); SetPixelIndex(image,index,q); if (index < image->colors) SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q); p++; q+=GetPixelChannels(image); } break; } case 8: /* Convert PseudoColor scanline. */ { for (x=0; x < (ssize_t) image->columns; x++) { index=ConstrainColormapIndex(image,*p,exception); SetPixelIndex(image,index,q); if (index < image->colors) SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q); p++; q+=GetPixelChannels(image); } } break; case 24: /* Convert DirectColor scanline. */ for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(image,ScaleCharToQuantum(*p++),q); SetPixelGreen(image,ScaleCharToQuantum(*p++),q); SetPixelBlue(image,ScaleCharToQuantum(*p++),q); q+=GetPixelChannels(image); } break; } if (!SyncAuthenticPixels(image,exception)) return(MagickFalse); return(MagickTrue); } /* Compute the number of colors in Grayed R[i]=G[i]=B[i] image */ static int GetCutColors(Image *image,ExceptionInfo *exception) { Quantum intensity, scale_intensity; register Quantum *q; ssize_t x, y; intensity=0; scale_intensity=ScaleCharToQuantum(16); for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (intensity < GetPixelRed(image,q)) intensity=GetPixelRed(image,q); if (intensity >= scale_intensity) return(255); q+=GetPixelChannels(image); } } if (intensity < ScaleCharToQuantum(2)) return(2); if (intensity < ScaleCharToQuantum(16)) return(16); return((int) intensity); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d C U T I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadCUTImage() reads an CUT X 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 ReadCUTImage method is: % % Image *ReadCUTImage(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 *ReadCUTImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define ThrowCUTReaderException(severity,tag) \ { \ if (palette != NULL) \ palette=DestroyImage(palette); \ if (clone_info != NULL) \ clone_info=DestroyImageInfo(clone_info); \ ThrowReaderException(severity,tag); \ } Image *image,*palette; ImageInfo *clone_info; MagickBooleanType status; MagickOffsetType offset; size_t EncodedByte; unsigned char RunCount,RunValue,RunCountMasked; CUTHeader Header; CUTPalHeader PalHeader; ssize_t depth; ssize_t i,j; ssize_t ldblk; unsigned char *BImgBuff=NULL,*ptrB; register Quantum *q; /* 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 CUT image. */ palette=NULL; clone_info=NULL; Header.Width=ReadBlobLSBShort(image); Header.Height=ReadBlobLSBShort(image); Header.Reserved=ReadBlobLSBShort(image); if (Header.Width==0 || Header.Height==0 || Header.Reserved!=0) CUT_KO: ThrowCUTReaderException(CorruptImageError,"ImproperImageHeader"); /*---This code checks first line of image---*/ EncodedByte=ReadBlobLSBShort(image); RunCount=(unsigned char) ReadBlobByte(image); RunCountMasked=RunCount & 0x7F; ldblk=0; while((int) RunCountMasked!=0) /*end of line?*/ { i=1; if((int) RunCount<0x80) i=(ssize_t) RunCountMasked; offset=SeekBlob(image,TellBlob(image)+i,SEEK_SET); if (offset < 0) ThrowCUTReaderException(CorruptImageError,"ImproperImageHeader"); if(EOFBlob(image) != MagickFalse) goto CUT_KO; /*wrong data*/ EncodedByte-=i+1; ldblk+=(ssize_t) RunCountMasked; RunCount=(unsigned char) ReadBlobByte(image); if(EOFBlob(image) != MagickFalse) goto CUT_KO; /*wrong data: unexpected eof in line*/ RunCountMasked=RunCount & 0x7F; } if(EncodedByte!=1) goto CUT_KO; /*wrong data: size incorrect*/ i=0; /*guess a number of bit planes*/ if(ldblk==(int) Header.Width) i=8; if(2*ldblk==(int) Header.Width) i=4; if(8*ldblk==(int) Header.Width) i=1; if(i==0) goto CUT_KO; /*wrong data: incorrect bit planes*/ depth=i; image->columns=Header.Width; image->rows=Header.Height; image->depth=8; image->colors=(size_t) (GetQuantumRange(1UL*i)+1); if (image_info->ping != MagickFalse) goto Finish; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); /* ----- Do something with palette ----- */ if ((clone_info=CloneImageInfo(image_info)) == NULL) goto NoPalette; i=(ssize_t) strlen(clone_info->filename); j=i; while(--i>0) { if(clone_info->filename[i]=='.') { break; } if(clone_info->filename[i]=='/' || clone_info->filename[i]=='\\' || clone_info->filename[i]==':' ) { i=j; break; } } (void) CopyMagickString(clone_info->filename+i,".PAL",(size_t) (MagickPathExtent-i)); if((clone_info->file=fopen_utf8(clone_info->filename,"rb"))==NULL) { (void) CopyMagickString(clone_info->filename+i,".pal",(size_t) (MagickPathExtent-i)); if((clone_info->file=fopen_utf8(clone_info->filename,"rb"))==NULL) { clone_info->filename[i]='\0'; if((clone_info->file=fopen_utf8(clone_info->filename,"rb"))==NULL) { clone_info=DestroyImageInfo(clone_info); clone_info=NULL; goto NoPalette; } } } if( (palette=AcquireImage(clone_info,exception))==NULL ) goto NoPalette; status=OpenBlob(clone_info,palette,ReadBinaryBlobMode,exception); if (status == MagickFalse) { ErasePalette: palette=DestroyImage(palette); palette=NULL; goto NoPalette; } if(palette!=NULL) { (void) ReadBlob(palette,2,(unsigned char *) PalHeader.FileId); if(strncmp(PalHeader.FileId,"AH",2) != 0) goto ErasePalette; PalHeader.Version=ReadBlobLSBShort(palette); PalHeader.Size=ReadBlobLSBShort(palette); PalHeader.FileType=(char) ReadBlobByte(palette); PalHeader.SubType=(char) ReadBlobByte(palette); PalHeader.BoardID=ReadBlobLSBShort(palette); PalHeader.GraphicsMode=ReadBlobLSBShort(palette); PalHeader.MaxIndex=ReadBlobLSBShort(palette); PalHeader.MaxRed=ReadBlobLSBShort(palette); PalHeader.MaxGreen=ReadBlobLSBShort(palette); PalHeader.MaxBlue=ReadBlobLSBShort(palette); (void) ReadBlob(palette,20,(unsigned char *) PalHeader.PaletteId); if (EOFBlob(image)) ThrowCUTReaderException(CorruptImageError,"UnexpectedEndOfFile"); if(PalHeader.MaxIndex<1) goto ErasePalette; image->colors=PalHeader.MaxIndex+1; if (AcquireImageColormap(image,image->colors,exception) == MagickFalse) goto NoMemory; if(PalHeader.MaxRed==0) PalHeader.MaxRed=(unsigned int) QuantumRange; /*avoid division by 0*/ if(PalHeader.MaxGreen==0) PalHeader.MaxGreen=(unsigned int) QuantumRange; if(PalHeader.MaxBlue==0) PalHeader.MaxBlue=(unsigned int) QuantumRange; for(i=0;i<=(int) PalHeader.MaxIndex;i++) { /*this may be wrong- I don't know why is palette such strange*/ j=(ssize_t) TellBlob(palette); if((j % 512)>512-6) { j=((j / 512)+1)*512; offset=SeekBlob(palette,j,SEEK_SET); if (offset < 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } image->colormap[i].red=(Quantum) ReadBlobLSBShort(palette); if (QuantumRange != (Quantum) PalHeader.MaxRed) { image->colormap[i].red=ClampToQuantum(((double) image->colormap[i].red*QuantumRange+(PalHeader.MaxRed>>1))/ PalHeader.MaxRed); } image->colormap[i].green=(Quantum) ReadBlobLSBShort(palette); if (QuantumRange != (Quantum) PalHeader.MaxGreen) { image->colormap[i].green=ClampToQuantum (((double) image->colormap[i].green*QuantumRange+(PalHeader.MaxGreen>>1))/PalHeader.MaxGreen); } image->colormap[i].blue=(Quantum) ReadBlobLSBShort(palette); if (QuantumRange != (Quantum) PalHeader.MaxBlue) { image->colormap[i].blue=ClampToQuantum (((double)image->colormap[i].blue*QuantumRange+(PalHeader.MaxBlue>>1))/PalHeader.MaxBlue); } } if (EOFBlob(image)) ThrowCUTReaderException(CorruptImageError,"UnexpectedEndOfFile"); } NoPalette: if(palette==NULL) { image->colors=256; if (AcquireImageColormap(image,image->colors,exception) == MagickFalse) { NoMemory: ThrowCUTReaderException(ResourceLimitError,"MemoryAllocationFailed"); } for (i=0; i < (ssize_t)image->colors; i++) { image->colormap[i].red=ScaleCharToQuantum((unsigned char) i); image->colormap[i].green=ScaleCharToQuantum((unsigned char) i); image->colormap[i].blue=ScaleCharToQuantum((unsigned char) i); } } /* ----- Load RLE compressed raster ----- */ BImgBuff=(unsigned char *) AcquireQuantumMemory((size_t) ldblk, sizeof(*BImgBuff)); /*Ldblk was set in the check phase*/ if(BImgBuff==NULL) goto NoMemory; (void) memset(BImgBuff,0,(size_t) ldblk*sizeof(*BImgBuff)); offset=SeekBlob(image,6 /*sizeof(Header)*/,SEEK_SET); if (offset < 0) { if (palette != NULL) palette=DestroyImage(palette); if (clone_info != NULL) clone_info=DestroyImageInfo(clone_info); BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } for (i=0; i < (int) Header.Height; i++) { EncodedByte=ReadBlobLSBShort(image); ptrB=BImgBuff; j=ldblk; RunCount=(unsigned char) ReadBlobByte(image); RunCountMasked=RunCount & 0x7F; while ((int) RunCountMasked != 0) { if((ssize_t) RunCountMasked>j) { /*Wrong Data*/ RunCountMasked=(unsigned char) j; if(j==0) { break; } } if((int) RunCount>0x80) { RunValue=(unsigned char) ReadBlobByte(image); (void) memset(ptrB,(int) RunValue,(size_t) RunCountMasked); } else { (void) ReadBlob(image,(size_t) RunCountMasked,ptrB); } ptrB+=(int) RunCountMasked; j-=(int) RunCountMasked; if (EOFBlob(image) != MagickFalse) goto Finish; /* wrong data: unexpected eof in line */ RunCount=(unsigned char) ReadBlobByte(image); RunCountMasked=RunCount & 0x7F; } InsertRow(image,depth,BImgBuff,i,exception); } (void) SyncImage(image,exception); /*detect monochrome image*/ if(palette==NULL) { /*attempt to detect binary (black&white) images*/ if ((image->storage_class == PseudoClass) && (SetImageGray(image,exception) != MagickFalse)) { if(GetCutColors(image,exception)==2) { for (i=0; i < (ssize_t)image->colors; i++) { register Quantum sample; sample=ScaleCharToQuantum((unsigned char) i); if(image->colormap[i].red!=sample) goto Finish; if(image->colormap[i].green!=sample) goto Finish; if(image->colormap[i].blue!=sample) goto Finish; } image->colormap[1].red=image->colormap[1].green= image->colormap[1].blue=QuantumRange; for (i=0; i < (ssize_t)image->rows; i++) { q=QueueAuthenticPixels(image,0,i,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (j=0; j < (ssize_t)image->columns; j++) { if (GetPixelRed(image,q) == ScaleCharToQuantum(1)) { SetPixelRed(image,QuantumRange,q); SetPixelGreen(image,QuantumRange,q); SetPixelBlue(image,QuantumRange,q); } q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) goto Finish; } } } } Finish: if (BImgBuff != NULL) BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff); if (palette != NULL) palette=DestroyImage(palette); if (clone_info != NULL) clone_info=DestroyImageInfo(clone_info); if (EOFBlob(image) != MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r C U T I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterCUTImage() adds attributes for the CUT 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 RegisterCUTImage method is: % % size_t RegisterCUTImage(void) % */ ModuleExport size_t RegisterCUTImage(void) { MagickInfo *entry; entry=AcquireMagickInfo("CUT","CUT","DR Halo"); entry->decoder=(DecodeImageHandler *) ReadCUTImage; entry->flags|=CoderDecoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r C U T I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterCUTImage() removes format registrations made by the % CUT module from the list of supported formats. % % The format of the UnregisterCUTImage method is: % % UnregisterCUTImage(void) % */ ModuleExport void UnregisterCUTImage(void) { (void) UnregisterMagickInfo("CUT"); }
./CrossVul/dataset_final_sorted/CWE-20/c/good_906_0
crossvul-cpp_data_good_1027_0
/* * Copyright (c) 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. * * sf-pcapng.c - pcapng-file-format-specific code from savefile.c */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <pcap/pcap-inttypes.h> #include <errno.h> #include <memory.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "pcap-int.h" #include "pcap-common.h" #ifdef HAVE_OS_PROTO_H #include "os-proto.h" #endif #include "sf-pcapng.h" /* * Block types. */ /* * Common part at the beginning of all blocks. */ struct block_header { bpf_u_int32 block_type; bpf_u_int32 total_length; }; /* * Common trailer at the end of all blocks. */ struct block_trailer { bpf_u_int32 total_length; }; /* * Common options. */ #define OPT_ENDOFOPT 0 /* end of options */ #define OPT_COMMENT 1 /* comment string */ /* * Option header. */ struct option_header { u_short option_code; u_short option_length; }; /* * Structures for the part of each block type following the common * part. */ /* * Section Header Block. */ #define BT_SHB 0x0A0D0D0A #define BT_SHB_INSANE_MAX 1024U*1024U*1U /* 1MB should be enough */ struct section_header_block { bpf_u_int32 byte_order_magic; u_short major_version; u_short minor_version; uint64_t section_length; /* followed by options and trailer */ }; /* * Byte-order magic value. */ #define BYTE_ORDER_MAGIC 0x1A2B3C4D /* * Current version number. If major_version isn't PCAP_NG_VERSION_MAJOR, * that means that this code can't read the file. */ #define PCAP_NG_VERSION_MAJOR 1 #define PCAP_NG_VERSION_MINOR 0 /* * Interface Description Block. */ #define BT_IDB 0x00000001 struct interface_description_block { u_short linktype; u_short reserved; bpf_u_int32 snaplen; /* followed by options and trailer */ }; /* * Options in the IDB. */ #define IF_NAME 2 /* interface name string */ #define IF_DESCRIPTION 3 /* interface description string */ #define IF_IPV4ADDR 4 /* interface's IPv4 address and netmask */ #define IF_IPV6ADDR 5 /* interface's IPv6 address and prefix length */ #define IF_MACADDR 6 /* interface's MAC address */ #define IF_EUIADDR 7 /* interface's EUI address */ #define IF_SPEED 8 /* interface's speed, in bits/s */ #define IF_TSRESOL 9 /* interface's time stamp resolution */ #define IF_TZONE 10 /* interface's time zone */ #define IF_FILTER 11 /* filter used when capturing on interface */ #define IF_OS 12 /* string OS on which capture on this interface was done */ #define IF_FCSLEN 13 /* FCS length for this interface */ #define IF_TSOFFSET 14 /* time stamp offset for this interface */ /* * Enhanced Packet Block. */ #define BT_EPB 0x00000006 struct enhanced_packet_block { bpf_u_int32 interface_id; bpf_u_int32 timestamp_high; bpf_u_int32 timestamp_low; bpf_u_int32 caplen; bpf_u_int32 len; /* followed by packet data, options, and trailer */ }; /* * Simple Packet Block. */ #define BT_SPB 0x00000003 struct simple_packet_block { bpf_u_int32 len; /* followed by packet data and trailer */ }; /* * Packet Block. */ #define BT_PB 0x00000002 struct packet_block { u_short interface_id; u_short drops_count; bpf_u_int32 timestamp_high; bpf_u_int32 timestamp_low; bpf_u_int32 caplen; bpf_u_int32 len; /* followed by packet data, options, and trailer */ }; /* * Block cursor - used when processing the contents of a block. * Contains a pointer into the data being processed and a count * of bytes remaining in the block. */ struct block_cursor { u_char *data; size_t data_remaining; bpf_u_int32 block_type; }; typedef enum { PASS_THROUGH, SCALE_UP_DEC, SCALE_DOWN_DEC, SCALE_UP_BIN, SCALE_DOWN_BIN } tstamp_scale_type_t; /* * Per-interface information. */ struct pcap_ng_if { uint64_t tsresol; /* time stamp resolution */ tstamp_scale_type_t scale_type; /* how to scale */ uint64_t scale_factor; /* time stamp scale factor for power-of-10 tsresol */ uint64_t tsoffset; /* time stamp offset */ }; /* * Per-pcap_t private data. * * max_blocksize is the maximum size of a block that we'll accept. We * reject blocks bigger than this, so we don't consume too much memory * with a truly huge block. It can change as we see IDBs with different * link-layer header types. (Currently, we don't support IDBs with * different link-layer header types, but we will support it in the * future, when we offer file-reading APIs that support it.) * * XXX - that's an issue on ILP32 platforms, where the maximum block * size of 2^31-1 would eat all but one byte of the entire address space. * It's less of an issue on ILP64/LLP64 platforms, but the actual size * of the address space may be limited by 1) the number of *significant* * address bits (currently, x86-64 only supports 48 bits of address), 2) * any limitations imposed by the operating system; 3) any limitations * imposed by the amount of available backing store for anonymous pages, * so we impose a limit regardless of the size of a pointer. */ struct pcap_ng_sf { uint64_t user_tsresol; /* time stamp resolution requested by the user */ u_int max_blocksize; /* don't grow buffer size past this */ bpf_u_int32 ifcount; /* number of interfaces seen in this capture */ bpf_u_int32 ifaces_size; /* size of array below */ struct pcap_ng_if *ifaces; /* array of interface information */ }; /* * The maximum block size we start with; we use an arbitrary value of * 16 MiB. */ #define INITIAL_MAX_BLOCKSIZE (16*1024*1024) /* * Maximum block size for a given maximum snapshot length; we define it * as the size of an EPB with a max_snaplen-sized packet and 128KB of * options. */ #define MAX_BLOCKSIZE_FOR_SNAPLEN(max_snaplen) \ (sizeof (struct block_header) + \ sizeof (struct enhanced_packet_block) + \ (max_snaplen) + 131072 + \ sizeof (struct block_trailer)) static void pcap_ng_cleanup(pcap_t *p); static int pcap_ng_next_packet(pcap_t *p, struct pcap_pkthdr *hdr, u_char **data); static int read_bytes(FILE *fp, void *buf, size_t bytes_to_read, int fail_on_eof, char *errbuf) { size_t amt_read; amt_read = fread(buf, 1, bytes_to_read, fp); if (amt_read != bytes_to_read) { if (ferror(fp)) { pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE, errno, "error reading dump file"); } else { if (amt_read == 0 && !fail_on_eof) return (0); /* EOF */ pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "truncated pcapng dump file; tried to read %" PRIsize " bytes, only got %" PRIsize, bytes_to_read, amt_read); } return (-1); } return (1); } static int read_block(FILE *fp, pcap_t *p, struct block_cursor *cursor, char *errbuf) { struct pcap_ng_sf *ps; int status; struct block_header bhdr; struct block_trailer *btrlr; u_char *bdata; size_t data_remaining; ps = p->priv; status = read_bytes(fp, &bhdr, sizeof(bhdr), 0, errbuf); if (status <= 0) return (status); /* error or EOF */ if (p->swapped) { bhdr.block_type = SWAPLONG(bhdr.block_type); bhdr.total_length = SWAPLONG(bhdr.total_length); } /* * Is this block "too small" - i.e., is it shorter than a block * header plus a block trailer? */ if (bhdr.total_length < sizeof(struct block_header) + sizeof(struct block_trailer)) { pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "block in pcapng dump file has a length of %u < %" PRIsize, bhdr.total_length, sizeof(struct block_header) + sizeof(struct block_trailer)); return (-1); } /* * Is the block total length a multiple of 4? */ if ((bhdr.total_length % 4) != 0) { /* * No. Report that as an error. */ pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "block in pcapng dump file has a length of %u that is not a multiple of 4" PRIsize, bhdr.total_length); return (-1); } /* * Is the buffer big enough? */ if (p->bufsize < bhdr.total_length) { /* * No - make it big enough, unless it's too big, in * which case we fail. */ void *bigger_buffer; if (bhdr.total_length > ps->max_blocksize) { pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "pcapng block size %u > maximum %u", bhdr.total_length, ps->max_blocksize); return (-1); } bigger_buffer = realloc(p->buffer, bhdr.total_length); if (bigger_buffer == NULL) { pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "out of memory"); return (-1); } p->buffer = bigger_buffer; } /* * Copy the stuff we've read to the buffer, and read the rest * of the block. */ memcpy(p->buffer, &bhdr, sizeof(bhdr)); bdata = (u_char *)p->buffer + sizeof(bhdr); data_remaining = bhdr.total_length - sizeof(bhdr); if (read_bytes(fp, bdata, data_remaining, 1, errbuf) == -1) return (-1); /* * Get the block size from the trailer. */ btrlr = (struct block_trailer *)(bdata + data_remaining - sizeof (struct block_trailer)); if (p->swapped) btrlr->total_length = SWAPLONG(btrlr->total_length); /* * Is the total length from the trailer the same as the total * length from the header? */ if (bhdr.total_length != btrlr->total_length) { /* * No. */ pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "block total length in header and trailer don't match"); return (-1); } /* * Initialize the cursor. */ cursor->data = bdata; cursor->data_remaining = data_remaining - sizeof(struct block_trailer); cursor->block_type = bhdr.block_type; return (1); } static void * get_from_block_data(struct block_cursor *cursor, size_t chunk_size, char *errbuf) { void *data; /* * Make sure we have the specified amount of data remaining in * the block data. */ if (cursor->data_remaining < chunk_size) { pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "block of type %u in pcapng dump file is too short", cursor->block_type); return (NULL); } /* * Return the current pointer, and skip past the chunk. */ data = cursor->data; cursor->data += chunk_size; cursor->data_remaining -= chunk_size; return (data); } static struct option_header * get_opthdr_from_block_data(pcap_t *p, struct block_cursor *cursor, char *errbuf) { struct option_header *opthdr; opthdr = get_from_block_data(cursor, sizeof(*opthdr), errbuf); if (opthdr == NULL) { /* * Option header is cut short. */ return (NULL); } /* * Byte-swap it if necessary. */ if (p->swapped) { opthdr->option_code = SWAPSHORT(opthdr->option_code); opthdr->option_length = SWAPSHORT(opthdr->option_length); } return (opthdr); } static void * get_optvalue_from_block_data(struct block_cursor *cursor, struct option_header *opthdr, char *errbuf) { size_t padded_option_len; void *optvalue; /* Pad option length to 4-byte boundary */ padded_option_len = opthdr->option_length; padded_option_len = ((padded_option_len + 3)/4)*4; optvalue = get_from_block_data(cursor, padded_option_len, errbuf); if (optvalue == NULL) { /* * Option value is cut short. */ return (NULL); } return (optvalue); } static int process_idb_options(pcap_t *p, struct block_cursor *cursor, uint64_t *tsresol, uint64_t *tsoffset, int *is_binary, char *errbuf) { struct option_header *opthdr; void *optvalue; int saw_tsresol, saw_tsoffset; uint8_t tsresol_opt; u_int i; saw_tsresol = 0; saw_tsoffset = 0; while (cursor->data_remaining != 0) { /* * Get the option header. */ opthdr = get_opthdr_from_block_data(p, cursor, errbuf); if (opthdr == NULL) { /* * Option header is cut short. */ return (-1); } /* * Get option value. */ optvalue = get_optvalue_from_block_data(cursor, opthdr, errbuf); if (optvalue == NULL) { /* * Option value is cut short. */ return (-1); } switch (opthdr->option_code) { case OPT_ENDOFOPT: if (opthdr->option_length != 0) { pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Interface Description Block has opt_endofopt option with length %u != 0", opthdr->option_length); return (-1); } goto done; case IF_TSRESOL: if (opthdr->option_length != 1) { pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Interface Description Block has if_tsresol option with length %u != 1", opthdr->option_length); return (-1); } if (saw_tsresol) { pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Interface Description Block has more than one if_tsresol option"); return (-1); } saw_tsresol = 1; memcpy(&tsresol_opt, optvalue, sizeof(tsresol_opt)); if (tsresol_opt & 0x80) { /* * Resolution is negative power of 2. */ uint8_t tsresol_shift = (tsresol_opt & 0x7F); if (tsresol_shift > 63) { /* * Resolution is too high; 2^-{res} * won't fit in a 64-bit value. */ pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Interface Description Block if_tsresol option resolution 2^-%u is too high", tsresol_shift); return (-1); } *is_binary = 1; *tsresol = ((uint64_t)1) << tsresol_shift; } else { /* * Resolution is negative power of 10. */ if (tsresol_opt > 19) { /* * Resolution is too high; 2^-{res} * won't fit in a 64-bit value (the * largest power of 10 that fits * in a 64-bit value is 10^19, as * the largest 64-bit unsigned * value is ~1.8*10^19). */ pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Interface Description Block if_tsresol option resolution 10^-%u is too high", tsresol_opt); return (-1); } *is_binary = 0; *tsresol = 1; for (i = 0; i < tsresol_opt; i++) *tsresol *= 10; } break; case IF_TSOFFSET: if (opthdr->option_length != 8) { pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Interface Description Block has if_tsoffset option with length %u != 8", opthdr->option_length); return (-1); } if (saw_tsoffset) { pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Interface Description Block has more than one if_tsoffset option"); return (-1); } saw_tsoffset = 1; memcpy(tsoffset, optvalue, sizeof(*tsoffset)); if (p->swapped) *tsoffset = SWAPLL(*tsoffset); break; default: break; } } done: return (0); } static int add_interface(pcap_t *p, struct block_cursor *cursor, char *errbuf) { struct pcap_ng_sf *ps; uint64_t tsresol; uint64_t tsoffset; int is_binary; ps = p->priv; /* * Count this interface. */ ps->ifcount++; /* * Grow the array of per-interface information as necessary. */ if (ps->ifcount > ps->ifaces_size) { /* * We need to grow the array. */ bpf_u_int32 new_ifaces_size; struct pcap_ng_if *new_ifaces; if (ps->ifaces_size == 0) { /* * It's currently empty. * * (The Clang static analyzer doesn't do enough, * err, umm, dataflow *analysis* to realize that * ps->ifaces_size == 0 if ps->ifaces == NULL, * and so complains about a possible zero argument * to realloc(), so we check for the former * condition to shut it up. * * However, it doesn't complain that one of the * multiplications below could overflow, which is * a real, albeit extremely unlikely, problem (you'd * need a pcapng file with tens of millions of * interfaces).) */ new_ifaces_size = 1; new_ifaces = malloc(sizeof (struct pcap_ng_if)); } else { /* * It's not currently empty; double its size. * (Perhaps overkill once we have a lot of interfaces.) * * Check for overflow if we double it. */ if (ps->ifaces_size * 2 < ps->ifaces_size) { /* * The maximum number of interfaces before * ps->ifaces_size overflows is the largest * possible 32-bit power of 2, as we do * size doubling. */ pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "more than %u interfaces in the file", 0x80000000U); return (0); } /* * ps->ifaces_size * 2 doesn't overflow, so it's * safe to multiply. */ new_ifaces_size = ps->ifaces_size * 2; /* * Now make sure that's not so big that it overflows * if we multiply by sizeof (struct pcap_ng_if). * * That can happen on 32-bit platforms, with a 32-bit * size_t; it shouldn't happen on 64-bit platforms, * with a 64-bit size_t, as new_ifaces_size is * 32 bits. */ if (new_ifaces_size * sizeof (struct pcap_ng_if) < new_ifaces_size) { /* * As this fails only with 32-bit size_t, * the multiplication was 32x32->32, and * the largest 32-bit value that can safely * be multiplied by sizeof (struct pcap_ng_if) * without overflow is the largest 32-bit * (unsigned) value divided by * sizeof (struct pcap_ng_if). */ pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "more than %u interfaces in the file", 0xFFFFFFFFU / ((u_int)sizeof (struct pcap_ng_if))); return (0); } new_ifaces = realloc(ps->ifaces, new_ifaces_size * sizeof (struct pcap_ng_if)); } if (new_ifaces == NULL) { /* * We ran out of memory. * Give up. */ pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "out of memory for per-interface information (%u interfaces)", ps->ifcount); return (0); } ps->ifaces_size = new_ifaces_size; ps->ifaces = new_ifaces; } /* * Set the default time stamp resolution and offset. */ tsresol = 1000000; /* microsecond resolution */ is_binary = 0; /* which is a power of 10 */ tsoffset = 0; /* absolute timestamps */ /* * Now look for various time stamp options, so we know * how to interpret the time stamps for this interface. */ if (process_idb_options(p, cursor, &tsresol, &tsoffset, &is_binary, errbuf) == -1) return (0); ps->ifaces[ps->ifcount - 1].tsresol = tsresol; ps->ifaces[ps->ifcount - 1].tsoffset = tsoffset; /* * Determine whether we're scaling up or down or not * at all for this interface. */ if (tsresol == ps->user_tsresol) { /* * The resolution is the resolution the user wants, * so we don't have to do scaling. */ ps->ifaces[ps->ifcount - 1].scale_type = PASS_THROUGH; } else if (tsresol > ps->user_tsresol) { /* * The resolution is greater than what the user wants, * so we have to scale the timestamps down. */ if (is_binary) ps->ifaces[ps->ifcount - 1].scale_type = SCALE_DOWN_BIN; else { /* * Calculate the scale factor. */ ps->ifaces[ps->ifcount - 1].scale_factor = tsresol/ps->user_tsresol; ps->ifaces[ps->ifcount - 1].scale_type = SCALE_DOWN_DEC; } } else { /* * The resolution is less than what the user wants, * so we have to scale the timestamps up. */ if (is_binary) ps->ifaces[ps->ifcount - 1].scale_type = SCALE_UP_BIN; else { /* * Calculate the scale factor. */ ps->ifaces[ps->ifcount - 1].scale_factor = ps->user_tsresol/tsresol; ps->ifaces[ps->ifcount - 1].scale_type = SCALE_UP_DEC; } } return (1); } /* * Check whether this is a pcapng savefile and, if it is, extract the * relevant information from the header. */ pcap_t * pcap_ng_check_header(const uint8_t *magic, FILE *fp, u_int precision, char *errbuf, int *err) { bpf_u_int32 magic_int; size_t amt_read; bpf_u_int32 total_length; bpf_u_int32 byte_order_magic; struct block_header *bhdrp; struct section_header_block *shbp; pcap_t *p; int swapped = 0; struct pcap_ng_sf *ps; int status; struct block_cursor cursor; struct interface_description_block *idbp; /* * Assume no read errors. */ *err = 0; /* * Check whether the first 4 bytes of the file are the block * type for a pcapng savefile. */ memcpy(&magic_int, magic, sizeof(magic_int)); if (magic_int != BT_SHB) { /* * XXX - check whether this looks like what the block * type would be after being munged by mapping between * UN*X and DOS/Windows text file format and, if it * does, look for the byte-order magic number in * the appropriate place and, if we find it, report * this as possibly being a pcapng file transferred * between UN*X and Windows in text file format? */ return (NULL); /* nope */ } /* * OK, they are. However, that's just \n\r\r\n, so it could, * conceivably, be an ordinary text file. * * It could not, however, conceivably be any other type of * capture file, so we can read the rest of the putative * Section Header Block; put the block type in the common * header, read the rest of the common header and the * fixed-length portion of the SHB, and look for the byte-order * magic value. */ amt_read = fread(&total_length, 1, sizeof(total_length), fp); if (amt_read < sizeof(total_length)) { if (ferror(fp)) { pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE, errno, "error reading dump file"); *err = 1; return (NULL); /* fail */ } /* * Possibly a weird short text file, so just say * "not pcapng". */ return (NULL); } amt_read = fread(&byte_order_magic, 1, sizeof(byte_order_magic), fp); if (amt_read < sizeof(byte_order_magic)) { if (ferror(fp)) { pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE, errno, "error reading dump file"); *err = 1; return (NULL); /* fail */ } /* * Possibly a weird short text file, so just say * "not pcapng". */ return (NULL); } if (byte_order_magic != BYTE_ORDER_MAGIC) { byte_order_magic = SWAPLONG(byte_order_magic); if (byte_order_magic != BYTE_ORDER_MAGIC) { /* * Not a pcapng file. */ return (NULL); } swapped = 1; total_length = SWAPLONG(total_length); } /* * Check the sanity of the total length. */ if (total_length < sizeof(*bhdrp) + sizeof(*shbp) + sizeof(struct block_trailer) || (total_length > BT_SHB_INSANE_MAX)) { pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Section Header Block in pcapng dump file has invalid length %" PRIsize " < _%u_ < %u (BT_SHB_INSANE_MAX)", sizeof(*bhdrp) + sizeof(*shbp) + sizeof(struct block_trailer), total_length, BT_SHB_INSANE_MAX); *err = 1; return (NULL); } /* * OK, this is a good pcapng file. * Allocate a pcap_t for it. */ p = pcap_open_offline_common(errbuf, sizeof (struct pcap_ng_sf)); if (p == NULL) { /* Allocation failed. */ *err = 1; return (NULL); } p->swapped = swapped; ps = p->priv; /* * What precision does the user want? */ switch (precision) { case PCAP_TSTAMP_PRECISION_MICRO: ps->user_tsresol = 1000000; break; case PCAP_TSTAMP_PRECISION_NANO: ps->user_tsresol = 1000000000; break; default: pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "unknown time stamp resolution %u", precision); free(p); *err = 1; return (NULL); } p->opt.tstamp_precision = precision; /* * Allocate a buffer into which to read blocks. We default to * the maximum of: * * the total length of the SHB for which we read the header; * * 2K, which should be more than large enough for an Enhanced * Packet Block containing a full-size Ethernet frame, and * leaving room for some options. * * If we find a bigger block, we reallocate the buffer, up to * the maximum size. We start out with a maximum size of * INITIAL_MAX_BLOCKSIZE; if we see any link-layer header types * with a maximum snapshot that results in a larger maximum * block length, we boost the maximum. */ p->bufsize = 2048; if (p->bufsize < total_length) p->bufsize = total_length; p->buffer = malloc(p->bufsize); if (p->buffer == NULL) { pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "out of memory"); free(p); *err = 1; return (NULL); } ps->max_blocksize = INITIAL_MAX_BLOCKSIZE; /* * Copy the stuff we've read to the buffer, and read the rest * of the SHB. */ bhdrp = (struct block_header *)p->buffer; shbp = (struct section_header_block *)((u_char *)p->buffer + sizeof(struct block_header)); bhdrp->block_type = magic_int; bhdrp->total_length = total_length; shbp->byte_order_magic = byte_order_magic; if (read_bytes(fp, (u_char *)p->buffer + (sizeof(magic_int) + sizeof(total_length) + sizeof(byte_order_magic)), total_length - (sizeof(magic_int) + sizeof(total_length) + sizeof(byte_order_magic)), 1, errbuf) == -1) goto fail; if (p->swapped) { /* * Byte-swap the fields we've read. */ shbp->major_version = SWAPSHORT(shbp->major_version); shbp->minor_version = SWAPSHORT(shbp->minor_version); /* * XXX - we don't care about the section length. */ } /* currently only SHB version 1.0 is supported */ if (! (shbp->major_version == PCAP_NG_VERSION_MAJOR && shbp->minor_version == PCAP_NG_VERSION_MINOR)) { pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "unsupported pcapng savefile version %u.%u", shbp->major_version, shbp->minor_version); goto fail; } p->version_major = shbp->major_version; p->version_minor = shbp->minor_version; /* * Save the time stamp resolution the user requested. */ p->opt.tstamp_precision = precision; /* * Now start looking for an Interface Description Block. */ for (;;) { /* * Read the next block. */ status = read_block(fp, p, &cursor, errbuf); if (status == 0) { /* EOF - no IDB in this file */ pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "the capture file has no Interface Description Blocks"); goto fail; } if (status == -1) goto fail; /* error */ switch (cursor.block_type) { case BT_IDB: /* * Get a pointer to the fixed-length portion of the * IDB. */ idbp = get_from_block_data(&cursor, sizeof(*idbp), errbuf); if (idbp == NULL) goto fail; /* error */ /* * Byte-swap it if necessary. */ if (p->swapped) { idbp->linktype = SWAPSHORT(idbp->linktype); idbp->snaplen = SWAPLONG(idbp->snaplen); } /* * Try to add this interface. */ if (!add_interface(p, &cursor, errbuf)) goto fail; goto done; case BT_EPB: case BT_SPB: case BT_PB: /* * Saw a packet before we saw any IDBs. That's * not valid, as we don't know what link-layer * encapsulation the packet has. */ pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "the capture file has a packet block before any Interface Description Blocks"); goto fail; default: /* * Just ignore it. */ break; } } done: p->tzoff = 0; /* XXX - not used in pcap */ p->linktype = linktype_to_dlt(idbp->linktype); p->snapshot = pcap_adjust_snapshot(p->linktype, idbp->snaplen); p->linktype_ext = 0; /* * If the maximum block size for a packet with the maximum * snapshot length for this DLT_ is bigger than the current * maximum block size, increase the maximum. */ if (MAX_BLOCKSIZE_FOR_SNAPLEN(max_snaplen_for_dlt(p->linktype)) > ps->max_blocksize) ps->max_blocksize = MAX_BLOCKSIZE_FOR_SNAPLEN(max_snaplen_for_dlt(p->linktype)); p->next_packet_op = pcap_ng_next_packet; p->cleanup_op = pcap_ng_cleanup; return (p); fail: free(ps->ifaces); free(p->buffer); free(p); *err = 1; return (NULL); } static void pcap_ng_cleanup(pcap_t *p) { struct pcap_ng_sf *ps = p->priv; free(ps->ifaces); sf_cleanup(p); } /* * Read and return the next packet from the savefile. Return the header * in hdr and a pointer to the contents in data. Return 0 on success, 1 * if there were no more packets, and -1 on an error. */ static int pcap_ng_next_packet(pcap_t *p, struct pcap_pkthdr *hdr, u_char **data) { struct pcap_ng_sf *ps = p->priv; struct block_cursor cursor; int status; struct enhanced_packet_block *epbp; struct simple_packet_block *spbp; struct packet_block *pbp; bpf_u_int32 interface_id = 0xFFFFFFFF; struct interface_description_block *idbp; struct section_header_block *shbp; FILE *fp = p->rfile; uint64_t t, sec, frac; /* * Look for an Enhanced Packet Block, a Simple Packet Block, * or a Packet Block. */ for (;;) { /* * Read the block type and length; those are common * to all blocks. */ status = read_block(fp, p, &cursor, p->errbuf); if (status == 0) return (1); /* EOF */ if (status == -1) return (-1); /* error */ switch (cursor.block_type) { case BT_EPB: /* * Get a pointer to the fixed-length portion of the * EPB. */ epbp = get_from_block_data(&cursor, sizeof(*epbp), p->errbuf); if (epbp == NULL) return (-1); /* error */ /* * Byte-swap it if necessary. */ if (p->swapped) { /* these were written in opposite byte order */ interface_id = SWAPLONG(epbp->interface_id); hdr->caplen = SWAPLONG(epbp->caplen); hdr->len = SWAPLONG(epbp->len); t = ((uint64_t)SWAPLONG(epbp->timestamp_high)) << 32 | SWAPLONG(epbp->timestamp_low); } else { interface_id = epbp->interface_id; hdr->caplen = epbp->caplen; hdr->len = epbp->len; t = ((uint64_t)epbp->timestamp_high) << 32 | epbp->timestamp_low; } goto found; case BT_SPB: /* * Get a pointer to the fixed-length portion of the * SPB. */ spbp = get_from_block_data(&cursor, sizeof(*spbp), p->errbuf); if (spbp == NULL) return (-1); /* error */ /* * SPB packets are assumed to have arrived on * the first interface. */ interface_id = 0; /* * Byte-swap it if necessary. */ if (p->swapped) { /* these were written in opposite byte order */ hdr->len = SWAPLONG(spbp->len); } else hdr->len = spbp->len; /* * The SPB doesn't give the captured length; * it's the minimum of the snapshot length * and the packet length. */ hdr->caplen = hdr->len; if (hdr->caplen > (bpf_u_int32)p->snapshot) hdr->caplen = p->snapshot; t = 0; /* no time stamps */ goto found; case BT_PB: /* * Get a pointer to the fixed-length portion of the * PB. */ pbp = get_from_block_data(&cursor, sizeof(*pbp), p->errbuf); if (pbp == NULL) return (-1); /* error */ /* * Byte-swap it if necessary. */ if (p->swapped) { /* these were written in opposite byte order */ interface_id = SWAPSHORT(pbp->interface_id); hdr->caplen = SWAPLONG(pbp->caplen); hdr->len = SWAPLONG(pbp->len); t = ((uint64_t)SWAPLONG(pbp->timestamp_high)) << 32 | SWAPLONG(pbp->timestamp_low); } else { interface_id = pbp->interface_id; hdr->caplen = pbp->caplen; hdr->len = pbp->len; t = ((uint64_t)pbp->timestamp_high) << 32 | pbp->timestamp_low; } goto found; case BT_IDB: /* * Interface Description Block. Get a pointer * to its fixed-length portion. */ idbp = get_from_block_data(&cursor, sizeof(*idbp), p->errbuf); if (idbp == NULL) return (-1); /* error */ /* * Byte-swap it if necessary. */ if (p->swapped) { idbp->linktype = SWAPSHORT(idbp->linktype); idbp->snaplen = SWAPLONG(idbp->snaplen); } /* * If the link-layer type or snapshot length * differ from the ones for the first IDB we * saw, quit. * * XXX - just discard packets from those * interfaces? */ if (p->linktype != idbp->linktype) { pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "an interface has a type %u different from the type of the first interface", idbp->linktype); return (-1); } /* * Check against the *adjusted* value of this IDB's * snapshot length. */ if ((bpf_u_int32)p->snapshot != pcap_adjust_snapshot(p->linktype, idbp->snaplen)) { pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "an interface has a snapshot length %u different from the type of the first interface", idbp->snaplen); return (-1); } /* * Try to add this interface. */ if (!add_interface(p, &cursor, p->errbuf)) return (-1); break; case BT_SHB: /* * Section Header Block. Get a pointer * to its fixed-length portion. */ shbp = get_from_block_data(&cursor, sizeof(*shbp), p->errbuf); if (shbp == NULL) return (-1); /* error */ /* * Assume the byte order of this section is * the same as that of the previous section. * We'll check for that later. */ if (p->swapped) { shbp->byte_order_magic = SWAPLONG(shbp->byte_order_magic); shbp->major_version = SWAPSHORT(shbp->major_version); } /* * Make sure the byte order doesn't change; * pcap_is_swapped() shouldn't change its * return value in the middle of reading a capture. */ switch (shbp->byte_order_magic) { case BYTE_ORDER_MAGIC: /* * OK. */ break; case SWAPLONG(BYTE_ORDER_MAGIC): /* * Byte order changes. */ pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "the file has sections with different byte orders"); return (-1); default: /* * Not a valid SHB. */ pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "the file has a section with a bad byte order magic field"); return (-1); } /* * Make sure the major version is the version * we handle. */ if (shbp->major_version != PCAP_NG_VERSION_MAJOR) { pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "unknown pcapng savefile major version number %u", shbp->major_version); return (-1); } /* * Reset the interface count; this section should * have its own set of IDBs. If any of them * don't have the same interface type, snapshot * length, or resolution as the first interface * we saw, we'll fail. (And if we don't see * any IDBs, we'll fail when we see a packet * block.) */ ps->ifcount = 0; break; default: /* * Not a packet block, IDB, or SHB; ignore it. */ break; } } found: /* * Is the interface ID an interface we know? */ if (interface_id >= ps->ifcount) { /* * Yes. Fail. */ pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "a packet arrived on interface %u, but there's no Interface Description Block for that interface", interface_id); return (-1); } if (hdr->caplen > (bpf_u_int32)p->snapshot) { pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "invalid packet capture length %u, bigger than " "snaplen of %d", hdr->caplen, p->snapshot); return (-1); } /* * Convert the time stamp to seconds and fractions of a second, * with the fractions being in units of the file-supplied resolution. */ sec = t / ps->ifaces[interface_id].tsresol + ps->ifaces[interface_id].tsoffset; frac = t % ps->ifaces[interface_id].tsresol; /* * Convert the fractions from units of the file-supplied resolution * to units of the user-requested resolution. */ switch (ps->ifaces[interface_id].scale_type) { case PASS_THROUGH: /* * The interface resolution is what the user wants, * so we're done. */ break; case SCALE_UP_DEC: /* * The interface resolution is less than what the user * wants; scale the fractional part up to the units of * the resolution the user requested by multiplying by * the quotient of the user-requested resolution and the * file-supplied resolution. * * Those resolutions are both powers of 10, and the user- * requested resolution is greater than the file-supplied * resolution, so the quotient in question is an integer. * We've calculated that quotient already, so we just * multiply by it. */ frac *= ps->ifaces[interface_id].scale_factor; break; case SCALE_UP_BIN: /* * The interface resolution is less than what the user * wants; scale the fractional part up to the units of * the resolution the user requested by multiplying by * the quotient of the user-requested resolution and the * file-supplied resolution. * * The file-supplied resolution is a power of 2, so the * quotient is not an integer, so, in order to do this * entirely with integer arithmetic, we multiply by the * user-requested resolution and divide by the file- * supplied resolution. * * XXX - Is there something clever we could do here, * given that we know that the file-supplied resolution * is a power of 2? Doing a multiplication followed by * a division runs the risk of overflowing, and involves * two non-simple arithmetic operations. */ frac *= ps->user_tsresol; frac /= ps->ifaces[interface_id].tsresol; break; case SCALE_DOWN_DEC: /* * The interface resolution is greater than what the user * wants; scale the fractional part up to the units of * the resolution the user requested by multiplying by * the quotient of the user-requested resolution and the * file-supplied resolution. * * Those resolutions are both powers of 10, and the user- * requested resolution is less than the file-supplied * resolution, so the quotient in question isn't an * integer, but its reciprocal is, and we can just divide * by the reciprocal of the quotient. We've calculated * the reciprocal of that quotient already, so we must * divide by it. */ frac /= ps->ifaces[interface_id].scale_factor; break; case SCALE_DOWN_BIN: /* * The interface resolution is greater than what the user * wants; convert the fractional part to units of the * resolution the user requested by multiplying by the * quotient of the user-requested resolution and the * file-supplied resolution. We do that by multiplying * by the user-requested resolution and dividing by the * file-supplied resolution, as the quotient might not * fit in an integer. * * The file-supplied resolution is a power of 2, so the * quotient is not an integer, and neither is its * reciprocal, so, in order to do this entirely with * integer arithmetic, we multiply by the user-requested * resolution and divide by the file-supplied resolution. * * XXX - Is there something clever we could do here, * given that we know that the file-supplied resolution * is a power of 2? Doing a multiplication followed by * a division runs the risk of overflowing, and involves * two non-simple arithmetic operations. */ frac *= ps->user_tsresol; frac /= ps->ifaces[interface_id].tsresol; break; } #ifdef _WIN32 /* * tv_sec and tv_used in the Windows struct timeval are both * longs. */ hdr->ts.tv_sec = (long)sec; hdr->ts.tv_usec = (long)frac; #else /* * tv_sec in the UN*X struct timeval is a time_t; tv_usec is * suseconds_t in UN*Xes that work the way the current Single * UNIX Standard specify - but not all older UN*Xes necessarily * support that type, so just cast to int. */ hdr->ts.tv_sec = (time_t)sec; hdr->ts.tv_usec = (int)frac; #endif /* * Get a pointer to the packet data. */ *data = get_from_block_data(&cursor, hdr->caplen, p->errbuf); if (*data == NULL) return (-1); if (p->swapped) swap_pseudo_headers(p->linktype, hdr, *data); return (0); }
./CrossVul/dataset_final_sorted/CWE-20/c/good_1027_0
crossvul-cpp_data_bad_5213_0
/* $OpenBSD: auth-passwd.c,v 1.44 2014/07/15 15:54:14 millert Exp $ */ /* * Author: Tatu Ylonen <ylo@cs.hut.fi> * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland * All rights reserved * Password authentication. This file contains the functions to check whether * the password is valid for the user. * * As far as I am concerned, the code I have written for this software * can be used freely for any purpose. Any derived versions of this * software must be clearly marked as such, and if the derived work is * incompatible with the protocol description in the RFC file, it must be * called by a name other than "ssh" or "Secure Shell". * * Copyright (c) 1999 Dug Song. All rights reserved. * Copyright (c) 2000 Markus Friedl. 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 ``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 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 "includes.h" #include <sys/types.h> #include <pwd.h> #include <stdio.h> #include <string.h> #include <stdarg.h> #include "packet.h" #include "buffer.h" #include "log.h" #include "misc.h" #include "servconf.h" #include "key.h" #include "hostfile.h" #include "auth.h" #include "auth-options.h" extern Buffer loginmsg; extern ServerOptions options; #ifdef HAVE_LOGIN_CAP extern login_cap_t *lc; #endif #define DAY (24L * 60 * 60) /* 1 day in seconds */ #define TWO_WEEKS (2L * 7 * DAY) /* 2 weeks in seconds */ void disable_forwarding(void) { no_port_forwarding_flag = 1; no_agent_forwarding_flag = 1; no_x11_forwarding_flag = 1; } /* * Tries to authenticate the user using password. Returns true if * authentication succeeds. */ int auth_password(Authctxt *authctxt, const char *password) { struct passwd * pw = authctxt->pw; int result, ok = authctxt->valid; #if defined(USE_SHADOW) && defined(HAS_SHADOW_EXPIRE) static int expire_checked = 0; #endif #ifndef HAVE_CYGWIN if (pw->pw_uid == 0 && options.permit_root_login != PERMIT_YES) ok = 0; #endif if (*password == '\0' && options.permit_empty_passwd == 0) return 0; #ifdef KRB5 if (options.kerberos_authentication == 1) { int ret = auth_krb5_password(authctxt, password); if (ret == 1 || ret == 0) return ret && ok; /* Fall back to ordinary passwd authentication. */ } #endif #ifdef HAVE_CYGWIN { HANDLE hToken = cygwin_logon_user(pw, password); if (hToken == INVALID_HANDLE_VALUE) return 0; cygwin_set_impersonation_token(hToken); return ok; } #endif #ifdef USE_PAM if (options.use_pam) return (sshpam_auth_passwd(authctxt, password) && ok); #endif #if defined(USE_SHADOW) && defined(HAS_SHADOW_EXPIRE) if (!expire_checked) { expire_checked = 1; if (auth_shadow_pwexpired(authctxt)) authctxt->force_pwchange = 1; } #endif result = sys_auth_passwd(authctxt, password); if (authctxt->force_pwchange) disable_forwarding(); return (result && ok); } #ifdef BSD_AUTH static void warn_expiry(Authctxt *authctxt, auth_session_t *as) { char buf[256]; quad_t pwtimeleft, actimeleft, daysleft, pwwarntime, acwarntime; pwwarntime = acwarntime = TWO_WEEKS; pwtimeleft = auth_check_change(as); actimeleft = auth_check_expire(as); #ifdef HAVE_LOGIN_CAP if (authctxt->valid) { pwwarntime = login_getcaptime(lc, "password-warn", TWO_WEEKS, TWO_WEEKS); acwarntime = login_getcaptime(lc, "expire-warn", TWO_WEEKS, TWO_WEEKS); } #endif if (pwtimeleft != 0 && pwtimeleft < pwwarntime) { daysleft = pwtimeleft / DAY + 1; snprintf(buf, sizeof(buf), "Your password will expire in %lld day%s.\n", daysleft, daysleft == 1 ? "" : "s"); buffer_append(&loginmsg, buf, strlen(buf)); } if (actimeleft != 0 && actimeleft < acwarntime) { daysleft = actimeleft / DAY + 1; snprintf(buf, sizeof(buf), "Your account will expire in %lld day%s.\n", daysleft, daysleft == 1 ? "" : "s"); buffer_append(&loginmsg, buf, strlen(buf)); } } int sys_auth_passwd(Authctxt *authctxt, const char *password) { struct passwd *pw = authctxt->pw; auth_session_t *as; static int expire_checked = 0; as = auth_usercheck(pw->pw_name, authctxt->style, "auth-ssh", (char *)password); if (as == NULL) return (0); if (auth_getstate(as) & AUTH_PWEXPIRED) { auth_close(as); disable_forwarding(); authctxt->force_pwchange = 1; return (1); } else { if (!expire_checked) { expire_checked = 1; warn_expiry(authctxt, as); } return (auth_close(as)); } } #elif !defined(CUSTOM_SYS_AUTH_PASSWD) int sys_auth_passwd(Authctxt *authctxt, const char *password) { struct passwd *pw = authctxt->pw; char *encrypted_password, *salt = NULL; /* Just use the supplied fake password if authctxt is invalid */ char *pw_password = authctxt->valid ? shadow_pw(pw) : pw->pw_passwd; /* Check for users with no password. */ if (strcmp(pw_password, "") == 0 && strcmp(password, "") == 0) return (1); /* * Encrypt the candidate password using the proper salt, or pass a * NULL and let xcrypt pick one. */ if (authctxt->valid && pw_password[0] && pw_password[1]) salt = pw_password; encrypted_password = xcrypt(password, salt); /* * Authentication is accepted if the encrypted passwords * are identical. */ return encrypted_password != NULL && strcmp(encrypted_password, pw_password) == 0; } #endif
./CrossVul/dataset_final_sorted/CWE-20/c/bad_5213_0
crossvul-cpp_data_good_3442_0
/* BNEP implementation for Linux Bluetooth stack (BlueZ). Copyright (C) 2001-2002 Inventel Systemes Written 2001-2002 by David Libault <david.libault@inventel.fr> Copyright (C) 2002 Maxim Krasnyansky <maxk@qualcomm.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) AND AUTHOR(S) BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ALL LIABILITY, INCLUDING LIABILITY FOR INFRINGEMENT OF ANY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS, RELATING TO USE OF THIS SOFTWARE IS DISCLAIMED. */ #include <linux/module.h> #include <linux/types.h> #include <linux/capability.h> #include <linux/errno.h> #include <linux/kernel.h> #include <linux/poll.h> #include <linux/fcntl.h> #include <linux/skbuff.h> #include <linux/socket.h> #include <linux/ioctl.h> #include <linux/file.h> #include <linux/init.h> #include <linux/compat.h> #include <linux/gfp.h> #include <net/sock.h> #include <asm/system.h> #include <asm/uaccess.h> #include "bnep.h" static int bnep_sock_release(struct socket *sock) { struct sock *sk = sock->sk; BT_DBG("sock %p sk %p", sock, sk); if (!sk) return 0; sock_orphan(sk); sock_put(sk); return 0; } static int bnep_sock_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg) { struct bnep_connlist_req cl; struct bnep_connadd_req ca; struct bnep_conndel_req cd; struct bnep_conninfo ci; struct socket *nsock; void __user *argp = (void __user *)arg; int err; BT_DBG("cmd %x arg %lx", cmd, arg); switch (cmd) { case BNEPCONNADD: if (!capable(CAP_NET_ADMIN)) return -EACCES; if (copy_from_user(&ca, argp, sizeof(ca))) return -EFAULT; nsock = sockfd_lookup(ca.sock, &err); if (!nsock) return err; if (nsock->sk->sk_state != BT_CONNECTED) { sockfd_put(nsock); return -EBADFD; } ca.device[sizeof(ca.device)-1] = 0; err = bnep_add_connection(&ca, nsock); if (!err) { if (copy_to_user(argp, &ca, sizeof(ca))) err = -EFAULT; } else sockfd_put(nsock); return err; case BNEPCONNDEL: if (!capable(CAP_NET_ADMIN)) return -EACCES; if (copy_from_user(&cd, argp, sizeof(cd))) return -EFAULT; return bnep_del_connection(&cd); case BNEPGETCONNLIST: if (copy_from_user(&cl, argp, sizeof(cl))) return -EFAULT; if (cl.cnum <= 0) return -EINVAL; err = bnep_get_connlist(&cl); if (!err && copy_to_user(argp, &cl, sizeof(cl))) return -EFAULT; return err; case BNEPGETCONNINFO: if (copy_from_user(&ci, argp, sizeof(ci))) return -EFAULT; err = bnep_get_conninfo(&ci); if (!err && copy_to_user(argp, &ci, sizeof(ci))) return -EFAULT; return err; default: return -EINVAL; } return 0; } #ifdef CONFIG_COMPAT static int bnep_sock_compat_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg) { if (cmd == BNEPGETCONNLIST) { struct bnep_connlist_req cl; uint32_t uci; int err; if (get_user(cl.cnum, (uint32_t __user *) arg) || get_user(uci, (u32 __user *) (arg + 4))) return -EFAULT; cl.ci = compat_ptr(uci); if (cl.cnum <= 0) return -EINVAL; err = bnep_get_connlist(&cl); if (!err && put_user(cl.cnum, (uint32_t __user *) arg)) err = -EFAULT; return err; } return bnep_sock_ioctl(sock, cmd, arg); } #endif static const struct proto_ops bnep_sock_ops = { .family = PF_BLUETOOTH, .owner = THIS_MODULE, .release = bnep_sock_release, .ioctl = bnep_sock_ioctl, #ifdef CONFIG_COMPAT .compat_ioctl = bnep_sock_compat_ioctl, #endif .bind = sock_no_bind, .getname = sock_no_getname, .sendmsg = sock_no_sendmsg, .recvmsg = sock_no_recvmsg, .poll = sock_no_poll, .listen = sock_no_listen, .shutdown = sock_no_shutdown, .setsockopt = sock_no_setsockopt, .getsockopt = sock_no_getsockopt, .connect = sock_no_connect, .socketpair = sock_no_socketpair, .accept = sock_no_accept, .mmap = sock_no_mmap }; static struct proto bnep_proto = { .name = "BNEP", .owner = THIS_MODULE, .obj_size = sizeof(struct bt_sock) }; static int bnep_sock_create(struct net *net, struct socket *sock, int protocol, int kern) { struct sock *sk; BT_DBG("sock %p", sock); if (sock->type != SOCK_RAW) return -ESOCKTNOSUPPORT; sk = sk_alloc(net, PF_BLUETOOTH, GFP_ATOMIC, &bnep_proto); if (!sk) return -ENOMEM; sock_init_data(sock, sk); sock->ops = &bnep_sock_ops; sock->state = SS_UNCONNECTED; sock_reset_flag(sk, SOCK_ZAPPED); sk->sk_protocol = protocol; sk->sk_state = BT_OPEN; return 0; } static const struct net_proto_family bnep_sock_family_ops = { .family = PF_BLUETOOTH, .owner = THIS_MODULE, .create = bnep_sock_create }; int __init bnep_sock_init(void) { int err; err = proto_register(&bnep_proto, 0); if (err < 0) return err; err = bt_sock_register(BTPROTO_BNEP, &bnep_sock_family_ops); if (err < 0) goto error; return 0; error: BT_ERR("Can't register BNEP socket"); proto_unregister(&bnep_proto); return err; } void __exit bnep_sock_cleanup(void) { if (bt_sock_unregister(BTPROTO_BNEP) < 0) BT_ERR("Can't unregister BNEP socket"); proto_unregister(&bnep_proto); }
./CrossVul/dataset_final_sorted/CWE-20/c/good_3442_0
crossvul-cpp_data_bad_5770_2
/* * SSLv3/TLSv1 shared functions * * Copyright (C) 2006-2012, Brainspark B.V. * * This file is part of PolarSSL (http://www.polarssl.org) * Lead Maintainer: Paul Bakker <polarssl_maintainer at polarssl.org> * * All rights reserved. * * 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., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ /* * The SSL 3.0 specification was drafted by Netscape in 1996, * and became an IETF standard in 1999. * * http://wp.netscape.com/eng/ssl3/ * http://www.ietf.org/rfc/rfc2246.txt * http://www.ietf.org/rfc/rfc4346.txt */ #include "polarssl/config.h" #if defined(POLARSSL_SSL_TLS_C) #include "polarssl/aes.h" #include "polarssl/arc4.h" #include "polarssl/camellia.h" #include "polarssl/des.h" #include "polarssl/debug.h" #include "polarssl/ssl.h" #include "polarssl/sha2.h" #if defined(POLARSSL_GCM_C) #include "polarssl/gcm.h" #endif #include <stdlib.h> #include <time.h> #if defined _MSC_VER && !defined strcasecmp #define strcasecmp _stricmp #endif #if defined(POLARSSL_SSL_HW_RECORD_ACCEL) int (*ssl_hw_record_init)(ssl_context *ssl, const unsigned char *key_enc, const unsigned char *key_dec, const unsigned char *iv_enc, const unsigned char *iv_dec, const unsigned char *mac_enc, const unsigned char *mac_dec) = NULL; int (*ssl_hw_record_reset)(ssl_context *ssl) = NULL; int (*ssl_hw_record_write)(ssl_context *ssl) = NULL; int (*ssl_hw_record_read)(ssl_context *ssl) = NULL; int (*ssl_hw_record_finish)(ssl_context *ssl) = NULL; #endif static int ssl_rsa_decrypt( void *ctx, int mode, size_t *olen, const unsigned char *input, unsigned char *output, size_t output_max_len ) { return rsa_pkcs1_decrypt( (rsa_context *) ctx, mode, olen, input, output, output_max_len ); } static int ssl_rsa_sign( void *ctx, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, int mode, int hash_id, unsigned int hashlen, const unsigned char *hash, unsigned char *sig ) { return rsa_pkcs1_sign( (rsa_context *) ctx, f_rng, p_rng, mode, hash_id, hashlen, hash, sig ); } static size_t ssl_rsa_key_len( void *ctx ) { return ( (rsa_context *) ctx )->len; } /* * Key material generation */ static int ssl3_prf( unsigned char *secret, size_t slen, char *label, unsigned char *random, size_t rlen, unsigned char *dstbuf, size_t dlen ) { size_t i; md5_context md5; sha1_context sha1; unsigned char padding[16]; unsigned char sha1sum[20]; ((void)label); /* * SSLv3: * block = * MD5( secret + SHA1( 'A' + secret + random ) ) + * MD5( secret + SHA1( 'BB' + secret + random ) ) + * MD5( secret + SHA1( 'CCC' + secret + random ) ) + * ... */ for( i = 0; i < dlen / 16; i++ ) { memset( padding, 'A' + i, 1 + i ); sha1_starts( &sha1 ); sha1_update( &sha1, padding, 1 + i ); sha1_update( &sha1, secret, slen ); sha1_update( &sha1, random, rlen ); sha1_finish( &sha1, sha1sum ); md5_starts( &md5 ); md5_update( &md5, secret, slen ); md5_update( &md5, sha1sum, 20 ); md5_finish( &md5, dstbuf + i * 16 ); } memset( &md5, 0, sizeof( md5 ) ); memset( &sha1, 0, sizeof( sha1 ) ); memset( padding, 0, sizeof( padding ) ); memset( sha1sum, 0, sizeof( sha1sum ) ); return( 0 ); } static int tls1_prf( unsigned char *secret, size_t slen, char *label, unsigned char *random, size_t rlen, unsigned char *dstbuf, size_t dlen ) { size_t nb, hs; size_t i, j, k; unsigned char *S1, *S2; unsigned char tmp[128]; unsigned char h_i[20]; if( sizeof( tmp ) < 20 + strlen( label ) + rlen ) return( POLARSSL_ERR_SSL_BAD_INPUT_DATA ); hs = ( slen + 1 ) / 2; S1 = secret; S2 = secret + slen - hs; nb = strlen( label ); memcpy( tmp + 20, label, nb ); memcpy( tmp + 20 + nb, random, rlen ); nb += rlen; /* * First compute P_md5(secret,label+random)[0..dlen] */ md5_hmac( S1, hs, tmp + 20, nb, 4 + tmp ); for( i = 0; i < dlen; i += 16 ) { md5_hmac( S1, hs, 4 + tmp, 16 + nb, h_i ); md5_hmac( S1, hs, 4 + tmp, 16, 4 + tmp ); k = ( i + 16 > dlen ) ? dlen % 16 : 16; for( j = 0; j < k; j++ ) dstbuf[i + j] = h_i[j]; } /* * XOR out with P_sha1(secret,label+random)[0..dlen] */ sha1_hmac( S2, hs, tmp + 20, nb, tmp ); for( i = 0; i < dlen; i += 20 ) { sha1_hmac( S2, hs, tmp, 20 + nb, h_i ); sha1_hmac( S2, hs, tmp, 20, tmp ); k = ( i + 20 > dlen ) ? dlen % 20 : 20; for( j = 0; j < k; j++ ) dstbuf[i + j] = (unsigned char)( dstbuf[i + j] ^ h_i[j] ); } memset( tmp, 0, sizeof( tmp ) ); memset( h_i, 0, sizeof( h_i ) ); return( 0 ); } static int tls_prf_sha256( unsigned char *secret, size_t slen, char *label, unsigned char *random, size_t rlen, unsigned char *dstbuf, size_t dlen ) { size_t nb; size_t i, j, k; unsigned char tmp[128]; unsigned char h_i[32]; if( sizeof( tmp ) < 32 + strlen( label ) + rlen ) return( POLARSSL_ERR_SSL_BAD_INPUT_DATA ); nb = strlen( label ); memcpy( tmp + 32, label, nb ); memcpy( tmp + 32 + nb, random, rlen ); nb += rlen; /* * Compute P_<hash>(secret, label + random)[0..dlen] */ sha2_hmac( secret, slen, tmp + 32, nb, tmp, 0 ); for( i = 0; i < dlen; i += 32 ) { sha2_hmac( secret, slen, tmp, 32 + nb, h_i, 0 ); sha2_hmac( secret, slen, tmp, 32, tmp, 0 ); k = ( i + 32 > dlen ) ? dlen % 32 : 32; for( j = 0; j < k; j++ ) dstbuf[i + j] = h_i[j]; } memset( tmp, 0, sizeof( tmp ) ); memset( h_i, 0, sizeof( h_i ) ); return( 0 ); } #if defined(POLARSSL_SHA4_C) static int tls_prf_sha384( unsigned char *secret, size_t slen, char *label, unsigned char *random, size_t rlen, unsigned char *dstbuf, size_t dlen ) { size_t nb; size_t i, j, k; unsigned char tmp[128]; unsigned char h_i[48]; if( sizeof( tmp ) < 48 + strlen( label ) + rlen ) return( POLARSSL_ERR_SSL_BAD_INPUT_DATA ); nb = strlen( label ); memcpy( tmp + 48, label, nb ); memcpy( tmp + 48 + nb, random, rlen ); nb += rlen; /* * Compute P_<hash>(secret, label + random)[0..dlen] */ sha4_hmac( secret, slen, tmp + 48, nb, tmp, 1 ); for( i = 0; i < dlen; i += 48 ) { sha4_hmac( secret, slen, tmp, 48 + nb, h_i, 1 ); sha4_hmac( secret, slen, tmp, 48, tmp, 1 ); k = ( i + 48 > dlen ) ? dlen % 48 : 48; for( j = 0; j < k; j++ ) dstbuf[i + j] = h_i[j]; } memset( tmp, 0, sizeof( tmp ) ); memset( h_i, 0, sizeof( h_i ) ); return( 0 ); } #endif static void ssl_update_checksum_start(ssl_context *, unsigned char *, size_t); static void ssl_update_checksum_md5sha1(ssl_context *, unsigned char *, size_t); static void ssl_update_checksum_sha256(ssl_context *, unsigned char *, size_t); static void ssl_calc_verify_ssl(ssl_context *,unsigned char *); static void ssl_calc_verify_tls(ssl_context *,unsigned char *); static void ssl_calc_verify_tls_sha256(ssl_context *,unsigned char *); static void ssl_calc_finished_ssl(ssl_context *,unsigned char *,int); static void ssl_calc_finished_tls(ssl_context *,unsigned char *,int); static void ssl_calc_finished_tls_sha256(ssl_context *,unsigned char *,int); #if defined(POLARSSL_SHA4_C) static void ssl_update_checksum_sha384(ssl_context *, unsigned char *, size_t); static void ssl_calc_verify_tls_sha384(ssl_context *,unsigned char *); static void ssl_calc_finished_tls_sha384(ssl_context *,unsigned char *,int); #endif int ssl_derive_keys( ssl_context *ssl ) { unsigned char tmp[64]; unsigned char keyblk[256]; unsigned char *key1; unsigned char *key2; unsigned int iv_copy_len; ssl_session *session = ssl->session_negotiate; ssl_transform *transform = ssl->transform_negotiate; ssl_handshake_params *handshake = ssl->handshake; SSL_DEBUG_MSG( 2, ( "=> derive keys" ) ); /* * Set appropriate PRF function and other SSL / TLS / TLS1.2 functions */ if( ssl->minor_ver == SSL_MINOR_VERSION_0 ) { handshake->tls_prf = ssl3_prf; handshake->calc_verify = ssl_calc_verify_ssl; handshake->calc_finished = ssl_calc_finished_ssl; } else if( ssl->minor_ver < SSL_MINOR_VERSION_3 ) { handshake->tls_prf = tls1_prf; handshake->calc_verify = ssl_calc_verify_tls; handshake->calc_finished = ssl_calc_finished_tls; } #if defined(POLARSSL_SHA4_C) else if( session->ciphersuite == TLS_RSA_WITH_AES_256_GCM_SHA384 || session->ciphersuite == TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 ) { handshake->tls_prf = tls_prf_sha384; handshake->calc_verify = ssl_calc_verify_tls_sha384; handshake->calc_finished = ssl_calc_finished_tls_sha384; } #endif else { handshake->tls_prf = tls_prf_sha256; handshake->calc_verify = ssl_calc_verify_tls_sha256; handshake->calc_finished = ssl_calc_finished_tls_sha256; } /* * SSLv3: * master = * MD5( premaster + SHA1( 'A' + premaster + randbytes ) ) + * MD5( premaster + SHA1( 'BB' + premaster + randbytes ) ) + * MD5( premaster + SHA1( 'CCC' + premaster + randbytes ) ) * * TLSv1: * master = PRF( premaster, "master secret", randbytes )[0..47] */ if( handshake->resume == 0 ) { SSL_DEBUG_BUF( 3, "premaster secret", handshake->premaster, handshake->pmslen ); handshake->tls_prf( handshake->premaster, handshake->pmslen, "master secret", handshake->randbytes, 64, session->master, 48 ); memset( handshake->premaster, 0, sizeof( handshake->premaster ) ); } else SSL_DEBUG_MSG( 3, ( "no premaster (session resumed)" ) ); /* * Swap the client and server random values. */ memcpy( tmp, handshake->randbytes, 64 ); memcpy( handshake->randbytes, tmp + 32, 32 ); memcpy( handshake->randbytes + 32, tmp, 32 ); memset( tmp, 0, sizeof( tmp ) ); /* * SSLv3: * key block = * MD5( master + SHA1( 'A' + master + randbytes ) ) + * MD5( master + SHA1( 'BB' + master + randbytes ) ) + * MD5( master + SHA1( 'CCC' + master + randbytes ) ) + * MD5( master + SHA1( 'DDDD' + master + randbytes ) ) + * ... * * TLSv1: * key block = PRF( master, "key expansion", randbytes ) */ handshake->tls_prf( session->master, 48, "key expansion", handshake->randbytes, 64, keyblk, 256 ); SSL_DEBUG_MSG( 3, ( "ciphersuite = %s", ssl_get_ciphersuite_name( session->ciphersuite ) ) ); SSL_DEBUG_BUF( 3, "master secret", session->master, 48 ); SSL_DEBUG_BUF( 4, "random bytes", handshake->randbytes, 64 ); SSL_DEBUG_BUF( 4, "key block", keyblk, 256 ); memset( handshake->randbytes, 0, sizeof( handshake->randbytes ) ); /* * Determine the appropriate key, IV and MAC length. */ switch( session->ciphersuite ) { #if defined(POLARSSL_ARC4_C) case TLS_RSA_WITH_RC4_128_MD5: transform->keylen = 16; transform->minlen = 16; transform->ivlen = 0; transform->maclen = 16; break; case TLS_RSA_WITH_RC4_128_SHA: transform->keylen = 16; transform->minlen = 20; transform->ivlen = 0; transform->maclen = 20; break; #endif #if defined(POLARSSL_DES_C) case TLS_RSA_WITH_3DES_EDE_CBC_SHA: case TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA: transform->keylen = 24; transform->minlen = 24; transform->ivlen = 8; transform->maclen = 20; break; #endif #if defined(POLARSSL_AES_C) case TLS_RSA_WITH_AES_128_CBC_SHA: case TLS_DHE_RSA_WITH_AES_128_CBC_SHA: transform->keylen = 16; transform->minlen = 32; transform->ivlen = 16; transform->maclen = 20; break; case TLS_RSA_WITH_AES_256_CBC_SHA: case TLS_DHE_RSA_WITH_AES_256_CBC_SHA: transform->keylen = 32; transform->minlen = 32; transform->ivlen = 16; transform->maclen = 20; break; #if defined(POLARSSL_SHA2_C) case TLS_RSA_WITH_AES_128_CBC_SHA256: case TLS_DHE_RSA_WITH_AES_128_CBC_SHA256: transform->keylen = 16; transform->minlen = 32; transform->ivlen = 16; transform->maclen = 32; break; case TLS_RSA_WITH_AES_256_CBC_SHA256: case TLS_DHE_RSA_WITH_AES_256_CBC_SHA256: transform->keylen = 32; transform->minlen = 32; transform->ivlen = 16; transform->maclen = 32; break; #endif #if defined(POLARSSL_GCM_C) case TLS_RSA_WITH_AES_128_GCM_SHA256: case TLS_DHE_RSA_WITH_AES_128_GCM_SHA256: transform->keylen = 16; transform->minlen = 1; transform->ivlen = 12; transform->maclen = 0; transform->fixed_ivlen = 4; break; case TLS_RSA_WITH_AES_256_GCM_SHA384: case TLS_DHE_RSA_WITH_AES_256_GCM_SHA384: transform->keylen = 32; transform->minlen = 1; transform->ivlen = 12; transform->maclen = 0; transform->fixed_ivlen = 4; break; #endif #endif #if defined(POLARSSL_CAMELLIA_C) case TLS_RSA_WITH_CAMELLIA_128_CBC_SHA: case TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA: transform->keylen = 16; transform->minlen = 32; transform->ivlen = 16; transform->maclen = 20; break; case TLS_RSA_WITH_CAMELLIA_256_CBC_SHA: case TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA: transform->keylen = 32; transform->minlen = 32; transform->ivlen = 16; transform->maclen = 20; break; #if defined(POLARSSL_SHA2_C) case TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256: case TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256: transform->keylen = 16; transform->minlen = 32; transform->ivlen = 16; transform->maclen = 32; break; case TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256: case TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256: transform->keylen = 32; transform->minlen = 32; transform->ivlen = 16; transform->maclen = 32; break; #endif #endif #if defined(POLARSSL_ENABLE_WEAK_CIPHERSUITES) #if defined(POLARSSL_CIPHER_NULL_CIPHER) case TLS_RSA_WITH_NULL_MD5: transform->keylen = 0; transform->minlen = 0; transform->ivlen = 0; transform->maclen = 16; break; case TLS_RSA_WITH_NULL_SHA: transform->keylen = 0; transform->minlen = 0; transform->ivlen = 0; transform->maclen = 20; break; case TLS_RSA_WITH_NULL_SHA256: transform->keylen = 0; transform->minlen = 0; transform->ivlen = 0; transform->maclen = 32; break; #endif /* defined(POLARSSL_CIPHER_NULL_CIPHER) */ #if defined(POLARSSL_DES_C) case TLS_RSA_WITH_DES_CBC_SHA: case TLS_DHE_RSA_WITH_DES_CBC_SHA: transform->keylen = 8; transform->minlen = 8; transform->ivlen = 8; transform->maclen = 20; break; #endif #endif /* defined(POLARSSL_ENABLE_WEAK_CIPHERSUITES) */ default: SSL_DEBUG_MSG( 1, ( "ciphersuite %s is not available", ssl_get_ciphersuite_name( session->ciphersuite ) ) ); return( POLARSSL_ERR_SSL_FEATURE_UNAVAILABLE ); } SSL_DEBUG_MSG( 3, ( "keylen: %d, minlen: %d, ivlen: %d, maclen: %d", transform->keylen, transform->minlen, transform->ivlen, transform->maclen ) ); /* * Finally setup the cipher contexts, IVs and MAC secrets. */ if( ssl->endpoint == SSL_IS_CLIENT ) { key1 = keyblk + transform->maclen * 2; key2 = keyblk + transform->maclen * 2 + transform->keylen; memcpy( transform->mac_enc, keyblk, transform->maclen ); memcpy( transform->mac_dec, keyblk + transform->maclen, transform->maclen ); /* * This is not used in TLS v1.1. */ iv_copy_len = ( transform->fixed_ivlen ) ? transform->fixed_ivlen : transform->ivlen; memcpy( transform->iv_enc, key2 + transform->keylen, iv_copy_len ); memcpy( transform->iv_dec, key2 + transform->keylen + iv_copy_len, iv_copy_len ); } else { key1 = keyblk + transform->maclen * 2 + transform->keylen; key2 = keyblk + transform->maclen * 2; memcpy( transform->mac_dec, keyblk, transform->maclen ); memcpy( transform->mac_enc, keyblk + transform->maclen, transform->maclen ); /* * This is not used in TLS v1.1. */ iv_copy_len = ( transform->fixed_ivlen ) ? transform->fixed_ivlen : transform->ivlen; memcpy( transform->iv_dec, key1 + transform->keylen, iv_copy_len ); memcpy( transform->iv_enc, key1 + transform->keylen + iv_copy_len, iv_copy_len ); } #if defined(POLARSSL_SSL_HW_RECORD_ACCEL) if( ssl_hw_record_init != NULL) { int ret = 0; SSL_DEBUG_MSG( 2, ( "going for ssl_hw_record_init()" ) ); if( ( ret = ssl_hw_record_init( ssl, key1, key2, transform->iv_enc, transform->iv_dec, transform->mac_enc, transform->mac_dec ) ) != 0 ) { SSL_DEBUG_RET( 1, "ssl_hw_record_init", ret ); return POLARSSL_ERR_SSL_HW_ACCEL_FAILED; } } #endif switch( session->ciphersuite ) { #if defined(POLARSSL_ARC4_C) case TLS_RSA_WITH_RC4_128_MD5: case TLS_RSA_WITH_RC4_128_SHA: arc4_setup( (arc4_context *) transform->ctx_enc, key1, transform->keylen ); arc4_setup( (arc4_context *) transform->ctx_dec, key2, transform->keylen ); break; #endif #if defined(POLARSSL_DES_C) case TLS_RSA_WITH_3DES_EDE_CBC_SHA: case TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA: des3_set3key_enc( (des3_context *) transform->ctx_enc, key1 ); des3_set3key_dec( (des3_context *) transform->ctx_dec, key2 ); break; #endif #if defined(POLARSSL_AES_C) case TLS_RSA_WITH_AES_128_CBC_SHA: case TLS_DHE_RSA_WITH_AES_128_CBC_SHA: case TLS_RSA_WITH_AES_128_CBC_SHA256: case TLS_DHE_RSA_WITH_AES_128_CBC_SHA256: aes_setkey_enc( (aes_context *) transform->ctx_enc, key1, 128 ); aes_setkey_dec( (aes_context *) transform->ctx_dec, key2, 128 ); break; case TLS_RSA_WITH_AES_256_CBC_SHA: case TLS_DHE_RSA_WITH_AES_256_CBC_SHA: case TLS_RSA_WITH_AES_256_CBC_SHA256: case TLS_DHE_RSA_WITH_AES_256_CBC_SHA256: aes_setkey_enc( (aes_context *) transform->ctx_enc, key1, 256 ); aes_setkey_dec( (aes_context *) transform->ctx_dec, key2, 256 ); break; #if defined(POLARSSL_GCM_C) case TLS_RSA_WITH_AES_128_GCM_SHA256: case TLS_DHE_RSA_WITH_AES_128_GCM_SHA256: gcm_init( (gcm_context *) transform->ctx_enc, key1, 128 ); gcm_init( (gcm_context *) transform->ctx_dec, key2, 128 ); break; case TLS_RSA_WITH_AES_256_GCM_SHA384: case TLS_DHE_RSA_WITH_AES_256_GCM_SHA384: gcm_init( (gcm_context *) transform->ctx_enc, key1, 256 ); gcm_init( (gcm_context *) transform->ctx_dec, key2, 256 ); break; #endif #endif #if defined(POLARSSL_CAMELLIA_C) case TLS_RSA_WITH_CAMELLIA_128_CBC_SHA: case TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA: case TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256: case TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256: camellia_setkey_enc( (camellia_context *) transform->ctx_enc, key1, 128 ); camellia_setkey_dec( (camellia_context *) transform->ctx_dec, key2, 128 ); break; case TLS_RSA_WITH_CAMELLIA_256_CBC_SHA: case TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA: case TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256: case TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256: camellia_setkey_enc( (camellia_context *) transform->ctx_enc, key1, 256 ); camellia_setkey_dec( (camellia_context *) transform->ctx_dec, key2, 256 ); break; #endif #if defined(POLARSSL_ENABLE_WEAK_CIPHERSUITES) #if defined(POLARSSL_CIPHER_NULL_CIPHER) case TLS_RSA_WITH_NULL_MD5: case TLS_RSA_WITH_NULL_SHA: case TLS_RSA_WITH_NULL_SHA256: break; #endif /* defined(POLARSSL_CIPHER_NULL_CIPHER) */ #if defined(POLARSSL_DES_C) case TLS_RSA_WITH_DES_CBC_SHA: case TLS_DHE_RSA_WITH_DES_CBC_SHA: des_setkey_enc( (des_context *) transform->ctx_enc, key1 ); des_setkey_dec( (des_context *) transform->ctx_dec, key2 ); break; #endif #endif /* defined(POLARSSL_ENABLE_WEAK_CIPHERSUITES) */ default: return( POLARSSL_ERR_SSL_FEATURE_UNAVAILABLE ); } memset( keyblk, 0, sizeof( keyblk ) ); #if defined(POLARSSL_ZLIB_SUPPORT) // Initialize compression // if( session->compression == SSL_COMPRESS_DEFLATE ) { SSL_DEBUG_MSG( 3, ( "Initializing zlib states" ) ); memset( &transform->ctx_deflate, 0, sizeof( transform->ctx_deflate ) ); memset( &transform->ctx_inflate, 0, sizeof( transform->ctx_inflate ) ); if( deflateInit( &transform->ctx_deflate, Z_DEFAULT_COMPRESSION ) != Z_OK || inflateInit( &transform->ctx_inflate ) != Z_OK ) { SSL_DEBUG_MSG( 1, ( "Failed to initialize compression" ) ); return( POLARSSL_ERR_SSL_COMPRESSION_FAILED ); } } #endif /* POLARSSL_ZLIB_SUPPORT */ SSL_DEBUG_MSG( 2, ( "<= derive keys" ) ); return( 0 ); } void ssl_calc_verify_ssl( ssl_context *ssl, unsigned char hash[36] ) { md5_context md5; sha1_context sha1; unsigned char pad_1[48]; unsigned char pad_2[48]; SSL_DEBUG_MSG( 2, ( "=> calc verify ssl" ) ); memcpy( &md5 , &ssl->handshake->fin_md5 , sizeof(md5_context) ); memcpy( &sha1, &ssl->handshake->fin_sha1, sizeof(sha1_context) ); memset( pad_1, 0x36, 48 ); memset( pad_2, 0x5C, 48 ); md5_update( &md5, ssl->session_negotiate->master, 48 ); md5_update( &md5, pad_1, 48 ); md5_finish( &md5, hash ); md5_starts( &md5 ); md5_update( &md5, ssl->session_negotiate->master, 48 ); md5_update( &md5, pad_2, 48 ); md5_update( &md5, hash, 16 ); md5_finish( &md5, hash ); sha1_update( &sha1, ssl->session_negotiate->master, 48 ); sha1_update( &sha1, pad_1, 40 ); sha1_finish( &sha1, hash + 16 ); sha1_starts( &sha1 ); sha1_update( &sha1, ssl->session_negotiate->master, 48 ); sha1_update( &sha1, pad_2, 40 ); sha1_update( &sha1, hash + 16, 20 ); sha1_finish( &sha1, hash + 16 ); SSL_DEBUG_BUF( 3, "calculated verify result", hash, 36 ); SSL_DEBUG_MSG( 2, ( "<= calc verify" ) ); return; } void ssl_calc_verify_tls( ssl_context *ssl, unsigned char hash[36] ) { md5_context md5; sha1_context sha1; SSL_DEBUG_MSG( 2, ( "=> calc verify tls" ) ); memcpy( &md5 , &ssl->handshake->fin_md5 , sizeof(md5_context) ); memcpy( &sha1, &ssl->handshake->fin_sha1, sizeof(sha1_context) ); md5_finish( &md5, hash ); sha1_finish( &sha1, hash + 16 ); SSL_DEBUG_BUF( 3, "calculated verify result", hash, 36 ); SSL_DEBUG_MSG( 2, ( "<= calc verify" ) ); return; } void ssl_calc_verify_tls_sha256( ssl_context *ssl, unsigned char hash[32] ) { sha2_context sha2; SSL_DEBUG_MSG( 2, ( "=> calc verify sha256" ) ); memcpy( &sha2, &ssl->handshake->fin_sha2, sizeof(sha2_context) ); sha2_finish( &sha2, hash ); SSL_DEBUG_BUF( 3, "calculated verify result", hash, 32 ); SSL_DEBUG_MSG( 2, ( "<= calc verify" ) ); return; } #if defined(POLARSSL_SHA4_C) void ssl_calc_verify_tls_sha384( ssl_context *ssl, unsigned char hash[48] ) { sha4_context sha4; SSL_DEBUG_MSG( 2, ( "=> calc verify sha384" ) ); memcpy( &sha4, &ssl->handshake->fin_sha4, sizeof(sha4_context) ); sha4_finish( &sha4, hash ); SSL_DEBUG_BUF( 3, "calculated verify result", hash, 48 ); SSL_DEBUG_MSG( 2, ( "<= calc verify" ) ); return; } #endif /* * SSLv3.0 MAC functions */ static void ssl_mac_md5( unsigned char *secret, unsigned char *buf, size_t len, unsigned char *ctr, int type ) { unsigned char header[11]; unsigned char padding[48]; md5_context md5; memcpy( header, ctr, 8 ); header[ 8] = (unsigned char) type; header[ 9] = (unsigned char)( len >> 8 ); header[10] = (unsigned char)( len ); memset( padding, 0x36, 48 ); md5_starts( &md5 ); md5_update( &md5, secret, 16 ); md5_update( &md5, padding, 48 ); md5_update( &md5, header, 11 ); md5_update( &md5, buf, len ); md5_finish( &md5, buf + len ); memset( padding, 0x5C, 48 ); md5_starts( &md5 ); md5_update( &md5, secret, 16 ); md5_update( &md5, padding, 48 ); md5_update( &md5, buf + len, 16 ); md5_finish( &md5, buf + len ); } static void ssl_mac_sha1( unsigned char *secret, unsigned char *buf, size_t len, unsigned char *ctr, int type ) { unsigned char header[11]; unsigned char padding[40]; sha1_context sha1; memcpy( header, ctr, 8 ); header[ 8] = (unsigned char) type; header[ 9] = (unsigned char)( len >> 8 ); header[10] = (unsigned char)( len ); memset( padding, 0x36, 40 ); sha1_starts( &sha1 ); sha1_update( &sha1, secret, 20 ); sha1_update( &sha1, padding, 40 ); sha1_update( &sha1, header, 11 ); sha1_update( &sha1, buf, len ); sha1_finish( &sha1, buf + len ); memset( padding, 0x5C, 40 ); sha1_starts( &sha1 ); sha1_update( &sha1, secret, 20 ); sha1_update( &sha1, padding, 40 ); sha1_update( &sha1, buf + len, 20 ); sha1_finish( &sha1, buf + len ); } static void ssl_mac_sha2( unsigned char *secret, unsigned char *buf, size_t len, unsigned char *ctr, int type ) { unsigned char header[11]; unsigned char padding[32]; sha2_context sha2; memcpy( header, ctr, 8 ); header[ 8] = (unsigned char) type; header[ 9] = (unsigned char)( len >> 8 ); header[10] = (unsigned char)( len ); memset( padding, 0x36, 32 ); sha2_starts( &sha2, 0 ); sha2_update( &sha2, secret, 32 ); sha2_update( &sha2, padding, 32 ); sha2_update( &sha2, header, 11 ); sha2_update( &sha2, buf, len ); sha2_finish( &sha2, buf + len ); memset( padding, 0x5C, 32 ); sha2_starts( &sha2, 0 ); sha2_update( &sha2, secret, 32 ); sha2_update( &sha2, padding, 32 ); sha2_update( &sha2, buf + len, 32 ); sha2_finish( &sha2, buf + len ); } /* * Encryption/decryption functions */ static int ssl_encrypt_buf( ssl_context *ssl ) { size_t i, padlen; SSL_DEBUG_MSG( 2, ( "=> encrypt buf" ) ); /* * Add MAC then encrypt */ if( ssl->minor_ver == SSL_MINOR_VERSION_0 ) { if( ssl->transform_out->maclen == 16 ) ssl_mac_md5( ssl->transform_out->mac_enc, ssl->out_msg, ssl->out_msglen, ssl->out_ctr, ssl->out_msgtype ); else if( ssl->transform_out->maclen == 20 ) ssl_mac_sha1( ssl->transform_out->mac_enc, ssl->out_msg, ssl->out_msglen, ssl->out_ctr, ssl->out_msgtype ); else if( ssl->transform_out->maclen == 32 ) ssl_mac_sha2( ssl->transform_out->mac_enc, ssl->out_msg, ssl->out_msglen, ssl->out_ctr, ssl->out_msgtype ); else if( ssl->transform_out->maclen != 0 ) { SSL_DEBUG_MSG( 1, ( "invalid MAC len: %d", ssl->transform_out->maclen ) ); return( POLARSSL_ERR_SSL_FEATURE_UNAVAILABLE ); } } else { if( ssl->transform_out->maclen == 16 ) { md5_context ctx; md5_hmac_starts( &ctx, ssl->transform_out->mac_enc, 16 ); md5_hmac_update( &ctx, ssl->out_ctr, 13 ); md5_hmac_update( &ctx, ssl->out_msg, ssl->out_msglen ); md5_hmac_finish( &ctx, ssl->out_msg + ssl->out_msglen ); memset( &ctx, 0, sizeof(md5_context)); } else if( ssl->transform_out->maclen == 20 ) { sha1_context ctx; sha1_hmac_starts( &ctx, ssl->transform_out->mac_enc, 20 ); sha1_hmac_update( &ctx, ssl->out_ctr, 13 ); sha1_hmac_update( &ctx, ssl->out_msg, ssl->out_msglen ); sha1_hmac_finish( &ctx, ssl->out_msg + ssl->out_msglen ); memset( &ctx, 0, sizeof(sha1_context)); } else if( ssl->transform_out->maclen == 32 ) { sha2_context ctx; sha2_hmac_starts( &ctx, ssl->transform_out->mac_enc, 32, 0 ); sha2_hmac_update( &ctx, ssl->out_ctr, 13 ); sha2_hmac_update( &ctx, ssl->out_msg, ssl->out_msglen ); sha2_hmac_finish( &ctx, ssl->out_msg + ssl->out_msglen ); memset( &ctx, 0, sizeof(sha2_context)); } else if( ssl->transform_out->maclen != 0 ) { SSL_DEBUG_MSG( 1, ( "invalid MAC len: %d", ssl->transform_out->maclen ) ); return( POLARSSL_ERR_SSL_FEATURE_UNAVAILABLE ); } } SSL_DEBUG_BUF( 4, "computed mac", ssl->out_msg + ssl->out_msglen, ssl->transform_out->maclen ); ssl->out_msglen += ssl->transform_out->maclen; if( ssl->transform_out->ivlen == 0 ) { padlen = 0; SSL_DEBUG_MSG( 3, ( "before encrypt: msglen = %d, " "including %d bytes of padding", ssl->out_msglen, 0 ) ); SSL_DEBUG_BUF( 4, "before encrypt: output payload", ssl->out_msg, ssl->out_msglen ); #if defined(POLARSSL_ARC4_C) if( ssl->session_out->ciphersuite == TLS_RSA_WITH_RC4_128_MD5 || ssl->session_out->ciphersuite == TLS_RSA_WITH_RC4_128_SHA ) { arc4_crypt( (arc4_context *) ssl->transform_out->ctx_enc, ssl->out_msglen, ssl->out_msg, ssl->out_msg ); } else #endif #if defined(POLARSSL_CIPHER_NULL_CIPHER) if( ssl->session_out->ciphersuite == TLS_RSA_WITH_NULL_MD5 || ssl->session_out->ciphersuite == TLS_RSA_WITH_NULL_SHA || ssl->session_out->ciphersuite == TLS_RSA_WITH_NULL_SHA256 ) { } else #endif return( POLARSSL_ERR_SSL_FEATURE_UNAVAILABLE ); } else if( ssl->transform_out->ivlen == 12 ) { size_t enc_msglen; unsigned char *enc_msg; unsigned char add_data[13]; int ret = POLARSSL_ERR_SSL_FEATURE_UNAVAILABLE; padlen = 0; enc_msglen = ssl->out_msglen; memcpy( add_data, ssl->out_ctr, 8 ); add_data[8] = ssl->out_msgtype; add_data[9] = ssl->major_ver; add_data[10] = ssl->minor_ver; add_data[11] = ( ssl->out_msglen >> 8 ) & 0xFF; add_data[12] = ssl->out_msglen & 0xFF; SSL_DEBUG_BUF( 4, "additional data used for AEAD", add_data, 13 ); #if defined(POLARSSL_AES_C) && defined(POLARSSL_GCM_C) if( ssl->session_out->ciphersuite == TLS_RSA_WITH_AES_128_GCM_SHA256 || ssl->session_out->ciphersuite == TLS_RSA_WITH_AES_256_GCM_SHA384 || ssl->session_out->ciphersuite == TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 || ssl->session_out->ciphersuite == TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 ) { /* * Generate IV */ ret = ssl->f_rng( ssl->p_rng, ssl->transform_out->iv_enc + ssl->transform_out->fixed_ivlen, ssl->transform_out->ivlen - ssl->transform_out->fixed_ivlen ); if( ret != 0 ) return( ret ); /* * Shift message for ivlen bytes and prepend IV */ memmove( ssl->out_msg + ssl->transform_out->ivlen - ssl->transform_out->fixed_ivlen, ssl->out_msg, ssl->out_msglen ); memcpy( ssl->out_msg, ssl->transform_out->iv_enc + ssl->transform_out->fixed_ivlen, ssl->transform_out->ivlen - ssl->transform_out->fixed_ivlen ); /* * Fix pointer positions and message length with added IV */ enc_msg = ssl->out_msg + ssl->transform_out->ivlen - ssl->transform_out->fixed_ivlen; enc_msglen = ssl->out_msglen; ssl->out_msglen += ssl->transform_out->ivlen - ssl->transform_out->fixed_ivlen; SSL_DEBUG_MSG( 3, ( "before encrypt: msglen = %d, " "including %d bytes of padding", ssl->out_msglen, 0 ) ); SSL_DEBUG_BUF( 4, "before encrypt: output payload", ssl->out_msg, ssl->out_msglen ); /* * Adjust for tag */ ssl->out_msglen += 16; gcm_crypt_and_tag( (gcm_context *) ssl->transform_out->ctx_enc, GCM_ENCRYPT, enc_msglen, ssl->transform_out->iv_enc, ssl->transform_out->ivlen, add_data, 13, enc_msg, enc_msg, 16, enc_msg + enc_msglen ); SSL_DEBUG_BUF( 4, "after encrypt: tag", enc_msg + enc_msglen, 16 ); } else #endif return( ret ); } else { unsigned char *enc_msg; size_t enc_msglen; padlen = ssl->transform_out->ivlen - ( ssl->out_msglen + 1 ) % ssl->transform_out->ivlen; if( padlen == ssl->transform_out->ivlen ) padlen = 0; for( i = 0; i <= padlen; i++ ) ssl->out_msg[ssl->out_msglen + i] = (unsigned char) padlen; ssl->out_msglen += padlen + 1; enc_msglen = ssl->out_msglen; enc_msg = ssl->out_msg; /* * Prepend per-record IV for block cipher in TLS v1.1 and up as per * Method 1 (6.2.3.2. in RFC4346 and RFC5246) */ if( ssl->minor_ver >= SSL_MINOR_VERSION_2 ) { /* * Generate IV */ int ret = ssl->f_rng( ssl->p_rng, ssl->transform_out->iv_enc, ssl->transform_out->ivlen ); if( ret != 0 ) return( ret ); /* * Shift message for ivlen bytes and prepend IV */ memmove( ssl->out_msg + ssl->transform_out->ivlen, ssl->out_msg, ssl->out_msglen ); memcpy( ssl->out_msg, ssl->transform_out->iv_enc, ssl->transform_out->ivlen ); /* * Fix pointer positions and message length with added IV */ enc_msg = ssl->out_msg + ssl->transform_out->ivlen; enc_msglen = ssl->out_msglen; ssl->out_msglen += ssl->transform_out->ivlen; } SSL_DEBUG_MSG( 3, ( "before encrypt: msglen = %d, " "including %d bytes of IV and %d bytes of padding", ssl->out_msglen, ssl->transform_out->ivlen, padlen + 1 ) ); SSL_DEBUG_BUF( 4, "before encrypt: output payload", ssl->out_msg, ssl->out_msglen ); switch( ssl->transform_out->ivlen ) { #if defined(POLARSSL_DES_C) case 8: #if defined(POLARSSL_ENABLE_WEAK_CIPHERSUITES) if( ssl->session_out->ciphersuite == TLS_RSA_WITH_DES_CBC_SHA || ssl->session_out->ciphersuite == TLS_DHE_RSA_WITH_DES_CBC_SHA ) { des_crypt_cbc( (des_context *) ssl->transform_out->ctx_enc, DES_ENCRYPT, enc_msglen, ssl->transform_out->iv_enc, enc_msg, enc_msg ); } else #endif des3_crypt_cbc( (des3_context *) ssl->transform_out->ctx_enc, DES_ENCRYPT, enc_msglen, ssl->transform_out->iv_enc, enc_msg, enc_msg ); break; #endif case 16: #if defined(POLARSSL_AES_C) if ( ssl->session_out->ciphersuite == TLS_RSA_WITH_AES_128_CBC_SHA || ssl->session_out->ciphersuite == TLS_DHE_RSA_WITH_AES_128_CBC_SHA || ssl->session_out->ciphersuite == TLS_RSA_WITH_AES_256_CBC_SHA || ssl->session_out->ciphersuite == TLS_DHE_RSA_WITH_AES_256_CBC_SHA || ssl->session_out->ciphersuite == TLS_RSA_WITH_AES_128_CBC_SHA256 || ssl->session_out->ciphersuite == TLS_RSA_WITH_AES_256_CBC_SHA256 || ssl->session_out->ciphersuite == TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 || ssl->session_out->ciphersuite == TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 ) { aes_crypt_cbc( (aes_context *) ssl->transform_out->ctx_enc, AES_ENCRYPT, enc_msglen, ssl->transform_out->iv_enc, enc_msg, enc_msg); break; } #endif #if defined(POLARSSL_CAMELLIA_C) if ( ssl->session_out->ciphersuite == TLS_RSA_WITH_CAMELLIA_128_CBC_SHA || ssl->session_out->ciphersuite == TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA || ssl->session_out->ciphersuite == TLS_RSA_WITH_CAMELLIA_256_CBC_SHA || ssl->session_out->ciphersuite == TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA || ssl->session_out->ciphersuite == TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256 || ssl->session_out->ciphersuite == TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 || ssl->session_out->ciphersuite == TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256 || ssl->session_out->ciphersuite == TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256 ) { camellia_crypt_cbc( (camellia_context *) ssl->transform_out->ctx_enc, CAMELLIA_ENCRYPT, enc_msglen, ssl->transform_out->iv_enc, enc_msg, enc_msg ); break; } #endif default: return( POLARSSL_ERR_SSL_FEATURE_UNAVAILABLE ); } } for( i = 8; i > 0; i-- ) if( ++ssl->out_ctr[i - 1] != 0 ) break; SSL_DEBUG_MSG( 2, ( "<= encrypt buf" ) ); return( 0 ); } /* * TODO: Use digest version when integrated! */ #define POLARSSL_SSL_MAX_MAC_SIZE 32 static int ssl_decrypt_buf( ssl_context *ssl ) { size_t i, padlen = 0, correct = 1; unsigned char tmp[POLARSSL_SSL_MAX_MAC_SIZE]; SSL_DEBUG_MSG( 2, ( "=> decrypt buf" ) ); if( ssl->in_msglen < ssl->transform_in->minlen ) { SSL_DEBUG_MSG( 1, ( "in_msglen (%d) < minlen (%d)", ssl->in_msglen, ssl->transform_in->minlen ) ); return( POLARSSL_ERR_SSL_INVALID_MAC ); } if( ssl->transform_in->ivlen == 0 ) { #if defined(POLARSSL_ARC4_C) if( ssl->session_in->ciphersuite == TLS_RSA_WITH_RC4_128_MD5 || ssl->session_in->ciphersuite == TLS_RSA_WITH_RC4_128_SHA ) { arc4_crypt( (arc4_context *) ssl->transform_in->ctx_dec, ssl->in_msglen, ssl->in_msg, ssl->in_msg ); } else #endif #if defined(POLARSSL_CIPHER_NULL_CIPHER) if( ssl->session_in->ciphersuite == TLS_RSA_WITH_NULL_MD5 || ssl->session_in->ciphersuite == TLS_RSA_WITH_NULL_SHA || ssl->session_in->ciphersuite == TLS_RSA_WITH_NULL_SHA256 ) { } else #endif return( POLARSSL_ERR_SSL_FEATURE_UNAVAILABLE ); } else if( ssl->transform_in->ivlen == 12 ) { unsigned char *dec_msg; unsigned char *dec_msg_result; size_t dec_msglen; unsigned char add_data[13]; int ret = POLARSSL_ERR_SSL_FEATURE_UNAVAILABLE; #if defined(POLARSSL_AES_C) && defined(POLARSSL_GCM_C) if( ssl->session_in->ciphersuite == TLS_RSA_WITH_AES_128_GCM_SHA256 || ssl->session_in->ciphersuite == TLS_RSA_WITH_AES_256_GCM_SHA384 || ssl->session_in->ciphersuite == TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 || ssl->session_in->ciphersuite == TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 ) { dec_msglen = ssl->in_msglen - ( ssl->transform_in->ivlen - ssl->transform_in->fixed_ivlen ); dec_msglen -= 16; dec_msg = ssl->in_msg + ( ssl->transform_in->ivlen - ssl->transform_in->fixed_ivlen ); dec_msg_result = ssl->in_msg; ssl->in_msglen = dec_msglen; memcpy( add_data, ssl->in_ctr, 8 ); add_data[8] = ssl->in_msgtype; add_data[9] = ssl->major_ver; add_data[10] = ssl->minor_ver; add_data[11] = ( ssl->in_msglen >> 8 ) & 0xFF; add_data[12] = ssl->in_msglen & 0xFF; SSL_DEBUG_BUF( 4, "additional data used for AEAD", add_data, 13 ); memcpy( ssl->transform_in->iv_dec + ssl->transform_in->fixed_ivlen, ssl->in_msg, ssl->transform_in->ivlen - ssl->transform_in->fixed_ivlen ); SSL_DEBUG_BUF( 4, "IV used", ssl->transform_in->iv_dec, ssl->transform_in->ivlen ); SSL_DEBUG_BUF( 4, "TAG used", dec_msg + dec_msglen, 16 ); memcpy( ssl->transform_in->iv_dec + ssl->transform_in->fixed_ivlen, ssl->in_msg, ssl->transform_in->ivlen - ssl->transform_in->fixed_ivlen ); ret = gcm_auth_decrypt( (gcm_context *) ssl->transform_in->ctx_dec, dec_msglen, ssl->transform_in->iv_dec, ssl->transform_in->ivlen, add_data, 13, dec_msg + dec_msglen, 16, dec_msg, dec_msg_result ); if( ret != 0 ) { SSL_DEBUG_MSG( 1, ( "AEAD decrypt failed on validation (ret = -0x%02x)", -ret ) ); return( POLARSSL_ERR_SSL_INVALID_MAC ); } } else #endif return( ret ); } else { /* * Decrypt and check the padding */ unsigned char *dec_msg; unsigned char *dec_msg_result; size_t dec_msglen; size_t minlen = 0; /* * Check immediate ciphertext sanity */ if( ssl->in_msglen % ssl->transform_in->ivlen != 0 ) { SSL_DEBUG_MSG( 1, ( "msglen (%d) %% ivlen (%d) != 0", ssl->in_msglen, ssl->transform_in->ivlen ) ); return( POLARSSL_ERR_SSL_INVALID_MAC ); } if( ssl->minor_ver >= SSL_MINOR_VERSION_2 ) minlen += ssl->transform_in->ivlen; if( ssl->in_msglen < minlen + ssl->transform_in->ivlen || ssl->in_msglen < minlen + ssl->transform_in->maclen + 1 ) { SSL_DEBUG_MSG( 1, ( "msglen (%d) < max( ivlen(%d), maclen (%d) + 1 ) ( + expl IV )", ssl->in_msglen, ssl->transform_in->ivlen, ssl->transform_in->maclen ) ); return( POLARSSL_ERR_SSL_INVALID_MAC ); } dec_msglen = ssl->in_msglen; dec_msg = ssl->in_msg; dec_msg_result = ssl->in_msg; /* * Initialize for prepended IV for block cipher in TLS v1.1 and up */ if( ssl->minor_ver >= SSL_MINOR_VERSION_2 ) { dec_msg += ssl->transform_in->ivlen; dec_msglen -= ssl->transform_in->ivlen; ssl->in_msglen -= ssl->transform_in->ivlen; for( i = 0; i < ssl->transform_in->ivlen; i++ ) ssl->transform_in->iv_dec[i] = ssl->in_msg[i]; } switch( ssl->transform_in->ivlen ) { #if defined(POLARSSL_DES_C) case 8: #if defined(POLARSSL_ENABLE_WEAK_CIPHERSUITES) if( ssl->session_in->ciphersuite == TLS_RSA_WITH_DES_CBC_SHA || ssl->session_in->ciphersuite == TLS_DHE_RSA_WITH_DES_CBC_SHA ) { des_crypt_cbc( (des_context *) ssl->transform_in->ctx_dec, DES_DECRYPT, dec_msglen, ssl->transform_in->iv_dec, dec_msg, dec_msg_result ); } else #endif des3_crypt_cbc( (des3_context *) ssl->transform_in->ctx_dec, DES_DECRYPT, dec_msglen, ssl->transform_in->iv_dec, dec_msg, dec_msg_result ); break; #endif case 16: #if defined(POLARSSL_AES_C) if ( ssl->session_in->ciphersuite == TLS_RSA_WITH_AES_128_CBC_SHA || ssl->session_in->ciphersuite == TLS_DHE_RSA_WITH_AES_128_CBC_SHA || ssl->session_in->ciphersuite == TLS_RSA_WITH_AES_256_CBC_SHA || ssl->session_in->ciphersuite == TLS_DHE_RSA_WITH_AES_256_CBC_SHA || ssl->session_in->ciphersuite == TLS_RSA_WITH_AES_128_CBC_SHA256 || ssl->session_in->ciphersuite == TLS_RSA_WITH_AES_256_CBC_SHA256 || ssl->session_in->ciphersuite == TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 || ssl->session_in->ciphersuite == TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 ) { aes_crypt_cbc( (aes_context *) ssl->transform_in->ctx_dec, AES_DECRYPT, dec_msglen, ssl->transform_in->iv_dec, dec_msg, dec_msg_result ); break; } #endif #if defined(POLARSSL_CAMELLIA_C) if ( ssl->session_in->ciphersuite == TLS_RSA_WITH_CAMELLIA_128_CBC_SHA || ssl->session_in->ciphersuite == TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA || ssl->session_in->ciphersuite == TLS_RSA_WITH_CAMELLIA_256_CBC_SHA || ssl->session_in->ciphersuite == TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA || ssl->session_in->ciphersuite == TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256 || ssl->session_in->ciphersuite == TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 || ssl->session_in->ciphersuite == TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256 || ssl->session_in->ciphersuite == TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256 ) { camellia_crypt_cbc( (camellia_context *) ssl->transform_in->ctx_dec, CAMELLIA_DECRYPT, dec_msglen, ssl->transform_in->iv_dec, dec_msg, dec_msg_result ); break; } #endif default: return( POLARSSL_ERR_SSL_FEATURE_UNAVAILABLE ); } padlen = 1 + ssl->in_msg[ssl->in_msglen - 1]; if( ssl->in_msglen < ssl->transform_in->maclen + padlen ) { #if defined(POLARSSL_SSL_DEBUG_ALL) SSL_DEBUG_MSG( 1, ( "msglen (%d) < maclen (%d) + padlen (%d)", ssl->in_msglen, ssl->transform_in->maclen, padlen ) ); #endif padlen = 0; correct = 0; } if( ssl->minor_ver == SSL_MINOR_VERSION_0 ) { if( padlen > ssl->transform_in->ivlen ) { #if defined(POLARSSL_SSL_DEBUG_ALL) SSL_DEBUG_MSG( 1, ( "bad padding length: is %d, " "should be no more than %d", padlen, ssl->transform_in->ivlen ) ); #endif correct = 0; } } else { /* * TLSv1+: always check the padding up to the first failure * and fake check up to 256 bytes of padding */ size_t pad_count = 0, fake_pad_count = 0; size_t padding_idx = ssl->in_msglen - padlen - 1; for( i = 1; i <= padlen; i++ ) pad_count += ( ssl->in_msg[padding_idx + i] == padlen - 1 ); for( ; i <= 256; i++ ) fake_pad_count += ( ssl->in_msg[padding_idx + i] == padlen - 1 ); correct &= ( pad_count == padlen ); /* Only 1 on correct padding */ correct &= ( pad_count + fake_pad_count < 512 ); /* Always 1 */ #if defined(POLARSSL_SSL_DEBUG_ALL) if( padlen > 0 && correct == 0) SSL_DEBUG_MSG( 1, ( "bad padding byte detected" ) ); #endif padlen &= correct * 0x1FF; } } SSL_DEBUG_BUF( 4, "raw buffer after decryption", ssl->in_msg, ssl->in_msglen ); /* * Always compute the MAC (RFC4346, CBCTIME). */ ssl->in_msglen -= ( ssl->transform_in->maclen + padlen ); ssl->in_hdr[3] = (unsigned char)( ssl->in_msglen >> 8 ); ssl->in_hdr[4] = (unsigned char)( ssl->in_msglen ); memcpy( tmp, ssl->in_msg + ssl->in_msglen, ssl->transform_in->maclen ); if( ssl->minor_ver == SSL_MINOR_VERSION_0 ) { if( ssl->transform_in->maclen == 16 ) ssl_mac_md5( ssl->transform_in->mac_dec, ssl->in_msg, ssl->in_msglen, ssl->in_ctr, ssl->in_msgtype ); else if( ssl->transform_in->maclen == 20 ) ssl_mac_sha1( ssl->transform_in->mac_dec, ssl->in_msg, ssl->in_msglen, ssl->in_ctr, ssl->in_msgtype ); else if( ssl->transform_in->maclen == 32 ) ssl_mac_sha2( ssl->transform_in->mac_dec, ssl->in_msg, ssl->in_msglen, ssl->in_ctr, ssl->in_msgtype ); else if( ssl->transform_in->maclen != 0 ) { SSL_DEBUG_MSG( 1, ( "invalid MAC len: %d", ssl->transform_in->maclen ) ); return( POLARSSL_ERR_SSL_FEATURE_UNAVAILABLE ); } } else { /* * Process MAC and always update for padlen afterwards to make * total time independent of padlen * * extra_run compensates MAC check for padlen * * Known timing attacks: * - Lucky Thirteen (http://www.isg.rhul.ac.uk/tls/TLStiming.pdf) * * We use ( ( Lx + 8 ) / 64 ) to handle 'negative Lx' values * correctly. (We round down instead of up, so -56 is the correct * value for our calculations instead of -55) */ int j, extra_run = 0; extra_run = ( 13 + ssl->in_msglen + padlen + 8 ) / 64 - ( 13 + ssl->in_msglen + 8 ) / 64; extra_run &= correct * 0xFF; if( ssl->transform_in->maclen == 16 ) { md5_context ctx; md5_hmac_starts( &ctx, ssl->transform_in->mac_dec, 16 ); md5_hmac_update( &ctx, ssl->in_ctr, ssl->in_msglen + 13 ); md5_hmac_finish( &ctx, ssl->in_msg + ssl->in_msglen ); for( j = 0; j < extra_run; j++ ) md5_process( &ctx, ssl->in_msg ); } else if( ssl->transform_in->maclen == 20 ) { sha1_context ctx; sha1_hmac_starts( &ctx, ssl->transform_in->mac_dec, 20 ); sha1_hmac_update( &ctx, ssl->in_ctr, ssl->in_msglen + 13 ); sha1_hmac_finish( &ctx, ssl->in_msg + ssl->in_msglen ); for( j = 0; j < extra_run; j++ ) sha1_process( &ctx, ssl->in_msg ); } else if( ssl->transform_in->maclen == 32 ) { sha2_context ctx; sha2_hmac_starts( &ctx, ssl->transform_in->mac_dec, 32, 0 ); sha2_hmac_update( &ctx, ssl->in_ctr, ssl->in_msglen + 13 ); sha2_hmac_finish( &ctx, ssl->in_msg + ssl->in_msglen ); for( j = 0; j < extra_run; j++ ) sha2_process( &ctx, ssl->in_msg ); } else if( ssl->transform_in->maclen != 0 ) { SSL_DEBUG_MSG( 1, ( "invalid MAC len: %d", ssl->transform_in->maclen ) ); return( POLARSSL_ERR_SSL_FEATURE_UNAVAILABLE ); } } SSL_DEBUG_BUF( 4, "message mac", tmp, ssl->transform_in->maclen ); SSL_DEBUG_BUF( 4, "computed mac", ssl->in_msg + ssl->in_msglen, ssl->transform_in->maclen ); if( memcmp( tmp, ssl->in_msg + ssl->in_msglen, ssl->transform_in->maclen ) != 0 ) { #if defined(POLARSSL_SSL_DEBUG_ALL) SSL_DEBUG_MSG( 1, ( "message mac does not match" ) ); #endif correct = 0; } /* * Finally check the correct flag */ if( correct == 0 ) return( POLARSSL_ERR_SSL_INVALID_MAC ); if( ssl->in_msglen == 0 ) { ssl->nb_zero++; /* * Three or more empty messages may be a DoS attack * (excessive CPU consumption). */ if( ssl->nb_zero > 3 ) { SSL_DEBUG_MSG( 1, ( "received four consecutive empty " "messages, possible DoS attack" ) ); return( POLARSSL_ERR_SSL_INVALID_MAC ); } } else ssl->nb_zero = 0; for( i = 8; i > 0; i-- ) if( ++ssl->in_ctr[i - 1] != 0 ) break; SSL_DEBUG_MSG( 2, ( "<= decrypt buf" ) ); return( 0 ); } #if defined(POLARSSL_ZLIB_SUPPORT) /* * Compression/decompression functions */ static int ssl_compress_buf( ssl_context *ssl ) { int ret; unsigned char *msg_post = ssl->out_msg; size_t len_pre = ssl->out_msglen; unsigned char *msg_pre; SSL_DEBUG_MSG( 2, ( "=> compress buf" ) ); msg_pre = (unsigned char*) malloc( len_pre ); if( msg_pre == NULL ) { SSL_DEBUG_MSG( 1, ( "malloc(%d bytes) failed", len_pre ) ); return( POLARSSL_ERR_SSL_MALLOC_FAILED ); } memcpy( msg_pre, ssl->out_msg, len_pre ); SSL_DEBUG_MSG( 3, ( "before compression: msglen = %d, ", ssl->out_msglen ) ); SSL_DEBUG_BUF( 4, "before compression: output payload", ssl->out_msg, ssl->out_msglen ); ssl->transform_out->ctx_deflate.next_in = msg_pre; ssl->transform_out->ctx_deflate.avail_in = len_pre; ssl->transform_out->ctx_deflate.next_out = msg_post; ssl->transform_out->ctx_deflate.avail_out = SSL_BUFFER_LEN; ret = deflate( &ssl->transform_out->ctx_deflate, Z_SYNC_FLUSH ); if( ret != Z_OK ) { SSL_DEBUG_MSG( 1, ( "failed to perform compression (%d)", ret ) ); return( POLARSSL_ERR_SSL_COMPRESSION_FAILED ); } ssl->out_msglen = SSL_BUFFER_LEN - ssl->transform_out->ctx_deflate.avail_out; free( msg_pre ); SSL_DEBUG_MSG( 3, ( "after compression: msglen = %d, ", ssl->out_msglen ) ); SSL_DEBUG_BUF( 4, "after compression: output payload", ssl->out_msg, ssl->out_msglen ); SSL_DEBUG_MSG( 2, ( "<= compress buf" ) ); return( 0 ); } static int ssl_decompress_buf( ssl_context *ssl ) { int ret; unsigned char *msg_post = ssl->in_msg; size_t len_pre = ssl->in_msglen; unsigned char *msg_pre; SSL_DEBUG_MSG( 2, ( "=> decompress buf" ) ); msg_pre = (unsigned char*) malloc( len_pre ); if( msg_pre == NULL ) { SSL_DEBUG_MSG( 1, ( "malloc(%d bytes) failed", len_pre ) ); return( POLARSSL_ERR_SSL_MALLOC_FAILED ); } memcpy( msg_pre, ssl->in_msg, len_pre ); SSL_DEBUG_MSG( 3, ( "before decompression: msglen = %d, ", ssl->in_msglen ) ); SSL_DEBUG_BUF( 4, "before decompression: input payload", ssl->in_msg, ssl->in_msglen ); ssl->transform_in->ctx_inflate.next_in = msg_pre; ssl->transform_in->ctx_inflate.avail_in = len_pre; ssl->transform_in->ctx_inflate.next_out = msg_post; ssl->transform_in->ctx_inflate.avail_out = SSL_MAX_CONTENT_LEN; ret = inflate( &ssl->transform_in->ctx_inflate, Z_SYNC_FLUSH ); if( ret != Z_OK ) { SSL_DEBUG_MSG( 1, ( "failed to perform decompression (%d)", ret ) ); return( POLARSSL_ERR_SSL_COMPRESSION_FAILED ); } ssl->in_msglen = SSL_MAX_CONTENT_LEN - ssl->transform_in->ctx_inflate.avail_out; free( msg_pre ); SSL_DEBUG_MSG( 3, ( "after decompression: msglen = %d, ", ssl->in_msglen ) ); SSL_DEBUG_BUF( 4, "after decompression: input payload", ssl->in_msg, ssl->in_msglen ); SSL_DEBUG_MSG( 2, ( "<= decompress buf" ) ); return( 0 ); } #endif /* POLARSSL_ZLIB_SUPPORT */ /* * Fill the input message buffer */ int ssl_fetch_input( ssl_context *ssl, size_t nb_want ) { int ret; size_t len; SSL_DEBUG_MSG( 2, ( "=> fetch input" ) ); while( ssl->in_left < nb_want ) { len = nb_want - ssl->in_left; ret = ssl->f_recv( ssl->p_recv, ssl->in_hdr + ssl->in_left, len ); SSL_DEBUG_MSG( 2, ( "in_left: %d, nb_want: %d", ssl->in_left, nb_want ) ); SSL_DEBUG_RET( 2, "ssl->f_recv", ret ); if( ret == 0 ) return( POLARSSL_ERR_SSL_CONN_EOF ); if( ret < 0 ) return( ret ); ssl->in_left += ret; } SSL_DEBUG_MSG( 2, ( "<= fetch input" ) ); return( 0 ); } /* * Flush any data not yet written */ int ssl_flush_output( ssl_context *ssl ) { int ret; unsigned char *buf; SSL_DEBUG_MSG( 2, ( "=> flush output" ) ); while( ssl->out_left > 0 ) { SSL_DEBUG_MSG( 2, ( "message length: %d, out_left: %d", 5 + ssl->out_msglen, ssl->out_left ) ); if( ssl->out_msglen < ssl->out_left ) { size_t header_left = ssl->out_left - ssl->out_msglen; buf = ssl->out_hdr + 5 - header_left; ret = ssl->f_send( ssl->p_send, buf, header_left ); SSL_DEBUG_RET( 2, "ssl->f_send (header)", ret ); if( ret <= 0 ) return( ret ); ssl->out_left -= ret; } buf = ssl->out_msg + ssl->out_msglen - ssl->out_left; ret = ssl->f_send( ssl->p_send, buf, ssl->out_left ); SSL_DEBUG_RET( 2, "ssl->f_send", ret ); if( ret <= 0 ) return( ret ); ssl->out_left -= ret; } SSL_DEBUG_MSG( 2, ( "<= flush output" ) ); return( 0 ); } /* * Record layer functions */ int ssl_write_record( ssl_context *ssl ) { int ret, done = 0; size_t len = ssl->out_msglen; SSL_DEBUG_MSG( 2, ( "=> write record" ) ); if( ssl->out_msgtype == SSL_MSG_HANDSHAKE ) { ssl->out_msg[1] = (unsigned char)( ( len - 4 ) >> 16 ); ssl->out_msg[2] = (unsigned char)( ( len - 4 ) >> 8 ); ssl->out_msg[3] = (unsigned char)( ( len - 4 ) ); ssl->handshake->update_checksum( ssl, ssl->out_msg, len ); } #if defined(POLARSSL_ZLIB_SUPPORT) if( ssl->transform_out != NULL && ssl->session_out->compression == SSL_COMPRESS_DEFLATE ) { if( ( ret = ssl_compress_buf( ssl ) ) != 0 ) { SSL_DEBUG_RET( 1, "ssl_compress_buf", ret ); return( ret ); } len = ssl->out_msglen; } #endif /*POLARSSL_ZLIB_SUPPORT */ #if defined(POLARSSL_SSL_HW_RECORD_ACCEL) if( ssl_hw_record_write != NULL) { SSL_DEBUG_MSG( 2, ( "going for ssl_hw_record_write()" ) ); ret = ssl_hw_record_write( ssl ); if( ret != 0 && ret != POLARSSL_ERR_SSL_HW_ACCEL_FALLTHROUGH ) { SSL_DEBUG_RET( 1, "ssl_hw_record_write", ret ); return POLARSSL_ERR_SSL_HW_ACCEL_FAILED; } done = 1; } #endif if( !done ) { ssl->out_hdr[0] = (unsigned char) ssl->out_msgtype; ssl->out_hdr[1] = (unsigned char) ssl->major_ver; ssl->out_hdr[2] = (unsigned char) ssl->minor_ver; ssl->out_hdr[3] = (unsigned char)( len >> 8 ); ssl->out_hdr[4] = (unsigned char)( len ); if( ssl->transform_out != NULL ) { if( ( ret = ssl_encrypt_buf( ssl ) ) != 0 ) { SSL_DEBUG_RET( 1, "ssl_encrypt_buf", ret ); return( ret ); } len = ssl->out_msglen; ssl->out_hdr[3] = (unsigned char)( len >> 8 ); ssl->out_hdr[4] = (unsigned char)( len ); } ssl->out_left = 5 + ssl->out_msglen; SSL_DEBUG_MSG( 3, ( "output record: msgtype = %d, " "version = [%d:%d], msglen = %d", ssl->out_hdr[0], ssl->out_hdr[1], ssl->out_hdr[2], ( ssl->out_hdr[3] << 8 ) | ssl->out_hdr[4] ) ); SSL_DEBUG_BUF( 4, "output record header sent to network", ssl->out_hdr, 5 ); SSL_DEBUG_BUF( 4, "output record sent to network", ssl->out_hdr + 32, ssl->out_msglen ); } if( ( ret = ssl_flush_output( ssl ) ) != 0 ) { SSL_DEBUG_RET( 1, "ssl_flush_output", ret ); return( ret ); } SSL_DEBUG_MSG( 2, ( "<= write record" ) ); return( 0 ); } int ssl_read_record( ssl_context *ssl ) { int ret, done = 0; SSL_DEBUG_MSG( 2, ( "=> read record" ) ); if( ssl->in_hslen != 0 && ssl->in_hslen < ssl->in_msglen ) { /* * Get next Handshake message in the current record */ ssl->in_msglen -= ssl->in_hslen; memmove( ssl->in_msg, ssl->in_msg + ssl->in_hslen, ssl->in_msglen ); ssl->in_hslen = 4; ssl->in_hslen += ( ssl->in_msg[2] << 8 ) | ssl->in_msg[3]; SSL_DEBUG_MSG( 3, ( "handshake message: msglen =" " %d, type = %d, hslen = %d", ssl->in_msglen, ssl->in_msg[0], ssl->in_hslen ) ); if( ssl->in_msglen < 4 || ssl->in_msg[1] != 0 ) { SSL_DEBUG_MSG( 1, ( "bad handshake length" ) ); return( POLARSSL_ERR_SSL_INVALID_RECORD ); } if( ssl->in_msglen < ssl->in_hslen ) { SSL_DEBUG_MSG( 1, ( "bad handshake length" ) ); return( POLARSSL_ERR_SSL_INVALID_RECORD ); } ssl->handshake->update_checksum( ssl, ssl->in_msg, ssl->in_hslen ); return( 0 ); } ssl->in_hslen = 0; /* * Read the record header and validate it */ if( ( ret = ssl_fetch_input( ssl, 5 ) ) != 0 ) { SSL_DEBUG_RET( 1, "ssl_fetch_input", ret ); return( ret ); } ssl->in_msgtype = ssl->in_hdr[0]; ssl->in_msglen = ( ssl->in_hdr[3] << 8 ) | ssl->in_hdr[4]; SSL_DEBUG_MSG( 3, ( "input record: msgtype = %d, " "version = [%d:%d], msglen = %d", ssl->in_hdr[0], ssl->in_hdr[1], ssl->in_hdr[2], ( ssl->in_hdr[3] << 8 ) | ssl->in_hdr[4] ) ); if( ssl->in_hdr[1] != ssl->major_ver ) { SSL_DEBUG_MSG( 1, ( "major version mismatch" ) ); return( POLARSSL_ERR_SSL_INVALID_RECORD ); } if( ssl->in_hdr[2] > ssl->max_minor_ver ) { SSL_DEBUG_MSG( 1, ( "minor version mismatch" ) ); return( POLARSSL_ERR_SSL_INVALID_RECORD ); } /* * Make sure the message length is acceptable */ if( ssl->transform_in == NULL ) { if( ssl->in_msglen < 1 || ssl->in_msglen > SSL_MAX_CONTENT_LEN ) { SSL_DEBUG_MSG( 1, ( "bad message length" ) ); return( POLARSSL_ERR_SSL_INVALID_RECORD ); } } else { if( ssl->in_msglen < ssl->transform_in->minlen ) { SSL_DEBUG_MSG( 1, ( "bad message length" ) ); return( POLARSSL_ERR_SSL_INVALID_RECORD ); } if( ssl->minor_ver == SSL_MINOR_VERSION_0 && ssl->in_msglen > ssl->transform_in->minlen + SSL_MAX_CONTENT_LEN ) { SSL_DEBUG_MSG( 1, ( "bad message length" ) ); return( POLARSSL_ERR_SSL_INVALID_RECORD ); } /* * TLS encrypted messages can have up to 256 bytes of padding */ if( ssl->minor_ver >= SSL_MINOR_VERSION_1 && ssl->in_msglen > ssl->transform_in->minlen + SSL_MAX_CONTENT_LEN + 256 ) { SSL_DEBUG_MSG( 1, ( "bad message length" ) ); return( POLARSSL_ERR_SSL_INVALID_RECORD ); } } /* * Read and optionally decrypt the message contents */ if( ( ret = ssl_fetch_input( ssl, 5 + ssl->in_msglen ) ) != 0 ) { SSL_DEBUG_RET( 1, "ssl_fetch_input", ret ); return( ret ); } SSL_DEBUG_BUF( 4, "input record from network", ssl->in_hdr, 5 + ssl->in_msglen ); #if defined(POLARSSL_SSL_HW_RECORD_ACCEL) if( ssl_hw_record_read != NULL) { SSL_DEBUG_MSG( 2, ( "going for ssl_hw_record_read()" ) ); ret = ssl_hw_record_read( ssl ); if( ret != 0 && ret != POLARSSL_ERR_SSL_HW_ACCEL_FALLTHROUGH ) { SSL_DEBUG_RET( 1, "ssl_hw_record_read", ret ); return POLARSSL_ERR_SSL_HW_ACCEL_FAILED; } done = 1; } #endif if( !done && ssl->transform_in != NULL ) { if( ( ret = ssl_decrypt_buf( ssl ) ) != 0 ) { #if defined(POLARSSL_SSL_ALERT_MESSAGES) if( ret == POLARSSL_ERR_SSL_INVALID_MAC ) { ssl_send_alert_message( ssl, SSL_ALERT_LEVEL_FATAL, SSL_ALERT_MSG_BAD_RECORD_MAC ); } #endif SSL_DEBUG_RET( 1, "ssl_decrypt_buf", ret ); return( ret ); } SSL_DEBUG_BUF( 4, "input payload after decrypt", ssl->in_msg, ssl->in_msglen ); if( ssl->in_msglen > SSL_MAX_CONTENT_LEN ) { SSL_DEBUG_MSG( 1, ( "bad message length" ) ); return( POLARSSL_ERR_SSL_INVALID_RECORD ); } } #if defined(POLARSSL_ZLIB_SUPPORT) if( ssl->transform_in != NULL && ssl->session_in->compression == SSL_COMPRESS_DEFLATE ) { if( ( ret = ssl_decompress_buf( ssl ) ) != 0 ) { SSL_DEBUG_RET( 1, "ssl_decompress_buf", ret ); return( ret ); } ssl->in_hdr[3] = (unsigned char)( ssl->in_msglen >> 8 ); ssl->in_hdr[4] = (unsigned char)( ssl->in_msglen ); } #endif /* POLARSSL_ZLIB_SUPPORT */ if( ssl->in_msgtype != SSL_MSG_HANDSHAKE && ssl->in_msgtype != SSL_MSG_ALERT && ssl->in_msgtype != SSL_MSG_CHANGE_CIPHER_SPEC && ssl->in_msgtype != SSL_MSG_APPLICATION_DATA ) { SSL_DEBUG_MSG( 1, ( "unknown record type" ) ); if( ( ret = ssl_send_alert_message( ssl, SSL_ALERT_LEVEL_FATAL, SSL_ALERT_MSG_UNEXPECTED_MESSAGE ) ) != 0 ) { return( ret ); } return( POLARSSL_ERR_SSL_INVALID_RECORD ); } if( ssl->in_msgtype == SSL_MSG_HANDSHAKE ) { ssl->in_hslen = 4; ssl->in_hslen += ( ssl->in_msg[2] << 8 ) | ssl->in_msg[3]; SSL_DEBUG_MSG( 3, ( "handshake message: msglen =" " %d, type = %d, hslen = %d", ssl->in_msglen, ssl->in_msg[0], ssl->in_hslen ) ); /* * Additional checks to validate the handshake header */ if( ssl->in_msglen < 4 || ssl->in_msg[1] != 0 ) { SSL_DEBUG_MSG( 1, ( "bad handshake length" ) ); return( POLARSSL_ERR_SSL_INVALID_RECORD ); } if( ssl->in_msglen < ssl->in_hslen ) { SSL_DEBUG_MSG( 1, ( "bad handshake length" ) ); return( POLARSSL_ERR_SSL_INVALID_RECORD ); } if( ssl->state != SSL_HANDSHAKE_OVER ) ssl->handshake->update_checksum( ssl, ssl->in_msg, ssl->in_hslen ); } if( ssl->in_msgtype == SSL_MSG_ALERT ) { SSL_DEBUG_MSG( 2, ( "got an alert message, type: [%d:%d]", ssl->in_msg[0], ssl->in_msg[1] ) ); /* * Ignore non-fatal alerts, except close_notify */ if( ssl->in_msg[0] == SSL_ALERT_LEVEL_FATAL ) { SSL_DEBUG_MSG( 1, ( "is a fatal alert message (msg %d)", ssl->in_msg[1] ) ); /** * Subtract from error code as ssl->in_msg[1] is 7-bit positive * error identifier. */ return( POLARSSL_ERR_SSL_FATAL_ALERT_MESSAGE ); } if( ssl->in_msg[0] == SSL_ALERT_LEVEL_WARNING && ssl->in_msg[1] == SSL_ALERT_MSG_CLOSE_NOTIFY ) { SSL_DEBUG_MSG( 2, ( "is a close notify message" ) ); return( POLARSSL_ERR_SSL_PEER_CLOSE_NOTIFY ); } } ssl->in_left = 0; SSL_DEBUG_MSG( 2, ( "<= read record" ) ); return( 0 ); } int ssl_send_fatal_handshake_failure( ssl_context *ssl ) { int ret; if( ( ret = ssl_send_alert_message( ssl, SSL_ALERT_LEVEL_FATAL, SSL_ALERT_MSG_HANDSHAKE_FAILURE ) ) != 0 ) { return( ret ); } return( 0 ); } int ssl_send_alert_message( ssl_context *ssl, unsigned char level, unsigned char message ) { int ret; SSL_DEBUG_MSG( 2, ( "=> send alert message" ) ); ssl->out_msgtype = SSL_MSG_ALERT; ssl->out_msglen = 2; ssl->out_msg[0] = level; ssl->out_msg[1] = message; if( ( ret = ssl_write_record( ssl ) ) != 0 ) { SSL_DEBUG_RET( 1, "ssl_write_record", ret ); return( ret ); } SSL_DEBUG_MSG( 2, ( "<= send alert message" ) ); return( 0 ); } /* * Handshake functions */ int ssl_write_certificate( ssl_context *ssl ) { int ret; size_t i, n; const x509_cert *crt; SSL_DEBUG_MSG( 2, ( "=> write certificate" ) ); if( ssl->endpoint == SSL_IS_CLIENT ) { if( ssl->client_auth == 0 ) { SSL_DEBUG_MSG( 2, ( "<= skip write certificate" ) ); ssl->state++; return( 0 ); } /* * If using SSLv3 and got no cert, send an Alert message * (otherwise an empty Certificate message will be sent). */ if( ssl->own_cert == NULL && ssl->minor_ver == SSL_MINOR_VERSION_0 ) { ssl->out_msglen = 2; ssl->out_msgtype = SSL_MSG_ALERT; ssl->out_msg[0] = SSL_ALERT_LEVEL_WARNING; ssl->out_msg[1] = SSL_ALERT_MSG_NO_CERT; SSL_DEBUG_MSG( 2, ( "got no certificate to send" ) ); goto write_msg; } } else /* SSL_IS_SERVER */ { if( ssl->own_cert == NULL ) { SSL_DEBUG_MSG( 1, ( "got no certificate to send" ) ); return( POLARSSL_ERR_SSL_CERTIFICATE_REQUIRED ); } } SSL_DEBUG_CRT( 3, "own certificate", ssl->own_cert ); /* * 0 . 0 handshake type * 1 . 3 handshake length * 4 . 6 length of all certs * 7 . 9 length of cert. 1 * 10 . n-1 peer certificate * n . n+2 length of cert. 2 * n+3 . ... upper level cert, etc. */ i = 7; crt = ssl->own_cert; while( crt != NULL ) { n = crt->raw.len; if( i + 3 + n > SSL_MAX_CONTENT_LEN ) { SSL_DEBUG_MSG( 1, ( "certificate too large, %d > %d", i + 3 + n, SSL_MAX_CONTENT_LEN ) ); return( POLARSSL_ERR_SSL_CERTIFICATE_TOO_LARGE ); } ssl->out_msg[i ] = (unsigned char)( n >> 16 ); ssl->out_msg[i + 1] = (unsigned char)( n >> 8 ); ssl->out_msg[i + 2] = (unsigned char)( n ); i += 3; memcpy( ssl->out_msg + i, crt->raw.p, n ); i += n; crt = crt->next; } ssl->out_msg[4] = (unsigned char)( ( i - 7 ) >> 16 ); ssl->out_msg[5] = (unsigned char)( ( i - 7 ) >> 8 ); ssl->out_msg[6] = (unsigned char)( ( i - 7 ) ); ssl->out_msglen = i; ssl->out_msgtype = SSL_MSG_HANDSHAKE; ssl->out_msg[0] = SSL_HS_CERTIFICATE; write_msg: ssl->state++; if( ( ret = ssl_write_record( ssl ) ) != 0 ) { SSL_DEBUG_RET( 1, "ssl_write_record", ret ); return( ret ); } SSL_DEBUG_MSG( 2, ( "<= write certificate" ) ); return( 0 ); } int ssl_parse_certificate( ssl_context *ssl ) { int ret; size_t i, n; SSL_DEBUG_MSG( 2, ( "=> parse certificate" ) ); if( ssl->endpoint == SSL_IS_SERVER && ssl->authmode == SSL_VERIFY_NONE ) { ssl->verify_result = BADCERT_SKIP_VERIFY; SSL_DEBUG_MSG( 2, ( "<= skip parse certificate" ) ); ssl->state++; return( 0 ); } if( ( ret = ssl_read_record( ssl ) ) != 0 ) { SSL_DEBUG_RET( 1, "ssl_read_record", ret ); return( ret ); } ssl->state++; /* * Check if the client sent an empty certificate */ if( ssl->endpoint == SSL_IS_SERVER && ssl->minor_ver == SSL_MINOR_VERSION_0 ) { if( ssl->in_msglen == 2 && ssl->in_msgtype == SSL_MSG_ALERT && ssl->in_msg[0] == SSL_ALERT_LEVEL_WARNING && ssl->in_msg[1] == SSL_ALERT_MSG_NO_CERT ) { SSL_DEBUG_MSG( 1, ( "SSLv3 client has no certificate" ) ); ssl->verify_result = BADCERT_MISSING; if( ssl->authmode == SSL_VERIFY_OPTIONAL ) return( 0 ); else return( POLARSSL_ERR_SSL_NO_CLIENT_CERTIFICATE ); } } if( ssl->endpoint == SSL_IS_SERVER && ssl->minor_ver != SSL_MINOR_VERSION_0 ) { if( ssl->in_hslen == 7 && ssl->in_msgtype == SSL_MSG_HANDSHAKE && ssl->in_msg[0] == SSL_HS_CERTIFICATE && memcmp( ssl->in_msg + 4, "\0\0\0", 3 ) == 0 ) { SSL_DEBUG_MSG( 1, ( "TLSv1 client has no certificate" ) ); ssl->verify_result = BADCERT_MISSING; if( ssl->authmode == SSL_VERIFY_REQUIRED ) return( POLARSSL_ERR_SSL_NO_CLIENT_CERTIFICATE ); else return( 0 ); } } if( ssl->in_msgtype != SSL_MSG_HANDSHAKE ) { SSL_DEBUG_MSG( 1, ( "bad certificate message" ) ); return( POLARSSL_ERR_SSL_UNEXPECTED_MESSAGE ); } if( ssl->in_msg[0] != SSL_HS_CERTIFICATE || ssl->in_hslen < 10 ) { SSL_DEBUG_MSG( 1, ( "bad certificate message" ) ); return( POLARSSL_ERR_SSL_BAD_HS_CERTIFICATE ); } /* * Same message structure as in ssl_write_certificate() */ n = ( ssl->in_msg[5] << 8 ) | ssl->in_msg[6]; if( ssl->in_msg[4] != 0 || ssl->in_hslen != 7 + n ) { SSL_DEBUG_MSG( 1, ( "bad certificate message" ) ); return( POLARSSL_ERR_SSL_BAD_HS_CERTIFICATE ); } if( ( ssl->session_negotiate->peer_cert = (x509_cert *) malloc( sizeof( x509_cert ) ) ) == NULL ) { SSL_DEBUG_MSG( 1, ( "malloc(%d bytes) failed", sizeof( x509_cert ) ) ); return( POLARSSL_ERR_SSL_MALLOC_FAILED ); } memset( ssl->session_negotiate->peer_cert, 0, sizeof( x509_cert ) ); i = 7; while( i < ssl->in_hslen ) { if( ssl->in_msg[i] != 0 ) { SSL_DEBUG_MSG( 1, ( "bad certificate message" ) ); return( POLARSSL_ERR_SSL_BAD_HS_CERTIFICATE ); } n = ( (unsigned int) ssl->in_msg[i + 1] << 8 ) | (unsigned int) ssl->in_msg[i + 2]; i += 3; if( n < 128 || i + n > ssl->in_hslen ) { SSL_DEBUG_MSG( 1, ( "bad certificate message" ) ); return( POLARSSL_ERR_SSL_BAD_HS_CERTIFICATE ); } ret = x509parse_crt( ssl->session_negotiate->peer_cert, ssl->in_msg + i, n ); if( ret != 0 ) { SSL_DEBUG_RET( 1, " x509parse_crt", ret ); return( ret ); } i += n; } SSL_DEBUG_CRT( 3, "peer certificate", ssl->session_negotiate->peer_cert ); if( ssl->authmode != SSL_VERIFY_NONE ) { if( ssl->ca_chain == NULL ) { SSL_DEBUG_MSG( 1, ( "got no CA chain" ) ); return( POLARSSL_ERR_SSL_CA_CHAIN_REQUIRED ); } ret = x509parse_verify( ssl->session_negotiate->peer_cert, ssl->ca_chain, ssl->ca_crl, ssl->peer_cn, &ssl->verify_result, ssl->f_vrfy, ssl->p_vrfy ); if( ret != 0 ) SSL_DEBUG_RET( 1, "x509_verify_cert", ret ); if( ssl->authmode != SSL_VERIFY_REQUIRED ) ret = 0; } SSL_DEBUG_MSG( 2, ( "<= parse certificate" ) ); return( ret ); } int ssl_write_change_cipher_spec( ssl_context *ssl ) { int ret; SSL_DEBUG_MSG( 2, ( "=> write change cipher spec" ) ); ssl->out_msgtype = SSL_MSG_CHANGE_CIPHER_SPEC; ssl->out_msglen = 1; ssl->out_msg[0] = 1; ssl->state++; if( ( ret = ssl_write_record( ssl ) ) != 0 ) { SSL_DEBUG_RET( 1, "ssl_write_record", ret ); return( ret ); } SSL_DEBUG_MSG( 2, ( "<= write change cipher spec" ) ); return( 0 ); } int ssl_parse_change_cipher_spec( ssl_context *ssl ) { int ret; SSL_DEBUG_MSG( 2, ( "=> parse change cipher spec" ) ); if( ( ret = ssl_read_record( ssl ) ) != 0 ) { SSL_DEBUG_RET( 1, "ssl_read_record", ret ); return( ret ); } if( ssl->in_msgtype != SSL_MSG_CHANGE_CIPHER_SPEC ) { SSL_DEBUG_MSG( 1, ( "bad change cipher spec message" ) ); return( POLARSSL_ERR_SSL_UNEXPECTED_MESSAGE ); } if( ssl->in_msglen != 1 || ssl->in_msg[0] != 1 ) { SSL_DEBUG_MSG( 1, ( "bad change cipher spec message" ) ); return( POLARSSL_ERR_SSL_BAD_HS_CHANGE_CIPHER_SPEC ); } ssl->state++; SSL_DEBUG_MSG( 2, ( "<= parse change cipher spec" ) ); return( 0 ); } void ssl_optimize_checksum( ssl_context *ssl, int ciphersuite ) { #if !defined(POLARSSL_SHA4_C) ((void) ciphersuite); #endif if( ssl->minor_ver < SSL_MINOR_VERSION_3 ) ssl->handshake->update_checksum = ssl_update_checksum_md5sha1; #if defined(POLARSSL_SHA4_C) else if ( ciphersuite == TLS_RSA_WITH_AES_256_GCM_SHA384 || ciphersuite == TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 ) { ssl->handshake->update_checksum = ssl_update_checksum_sha384; } #endif else ssl->handshake->update_checksum = ssl_update_checksum_sha256; } static void ssl_update_checksum_start( ssl_context *ssl, unsigned char *buf, size_t len ) { md5_update( &ssl->handshake->fin_md5 , buf, len ); sha1_update( &ssl->handshake->fin_sha1, buf, len ); sha2_update( &ssl->handshake->fin_sha2, buf, len ); #if defined(POLARSSL_SHA4_C) sha4_update( &ssl->handshake->fin_sha4, buf, len ); #endif } static void ssl_update_checksum_md5sha1( ssl_context *ssl, unsigned char *buf, size_t len ) { md5_update( &ssl->handshake->fin_md5 , buf, len ); sha1_update( &ssl->handshake->fin_sha1, buf, len ); } static void ssl_update_checksum_sha256( ssl_context *ssl, unsigned char *buf, size_t len ) { sha2_update( &ssl->handshake->fin_sha2, buf, len ); } #if defined(POLARSSL_SHA4_C) static void ssl_update_checksum_sha384( ssl_context *ssl, unsigned char *buf, size_t len ) { sha4_update( &ssl->handshake->fin_sha4, buf, len ); } #endif static void ssl_calc_finished_ssl( ssl_context *ssl, unsigned char *buf, int from ) { const char *sender; md5_context md5; sha1_context sha1; unsigned char padbuf[48]; unsigned char md5sum[16]; unsigned char sha1sum[20]; ssl_session *session = ssl->session_negotiate; if( !session ) session = ssl->session; SSL_DEBUG_MSG( 2, ( "=> calc finished ssl" ) ); memcpy( &md5 , &ssl->handshake->fin_md5 , sizeof(md5_context) ); memcpy( &sha1, &ssl->handshake->fin_sha1, sizeof(sha1_context) ); /* * SSLv3: * hash = * MD5( master + pad2 + * MD5( handshake + sender + master + pad1 ) ) * + SHA1( master + pad2 + * SHA1( handshake + sender + master + pad1 ) ) */ SSL_DEBUG_BUF( 4, "finished md5 state", (unsigned char *) md5.state, sizeof( md5.state ) ); SSL_DEBUG_BUF( 4, "finished sha1 state", (unsigned char *) sha1.state, sizeof( sha1.state ) ); sender = ( from == SSL_IS_CLIENT ) ? "CLNT" : "SRVR"; memset( padbuf, 0x36, 48 ); md5_update( &md5, (const unsigned char *) sender, 4 ); md5_update( &md5, session->master, 48 ); md5_update( &md5, padbuf, 48 ); md5_finish( &md5, md5sum ); sha1_update( &sha1, (const unsigned char *) sender, 4 ); sha1_update( &sha1, session->master, 48 ); sha1_update( &sha1, padbuf, 40 ); sha1_finish( &sha1, sha1sum ); memset( padbuf, 0x5C, 48 ); md5_starts( &md5 ); md5_update( &md5, session->master, 48 ); md5_update( &md5, padbuf, 48 ); md5_update( &md5, md5sum, 16 ); md5_finish( &md5, buf ); sha1_starts( &sha1 ); sha1_update( &sha1, session->master, 48 ); sha1_update( &sha1, padbuf , 40 ); sha1_update( &sha1, sha1sum, 20 ); sha1_finish( &sha1, buf + 16 ); SSL_DEBUG_BUF( 3, "calc finished result", buf, 36 ); memset( &md5, 0, sizeof( md5_context ) ); memset( &sha1, 0, sizeof( sha1_context ) ); memset( padbuf, 0, sizeof( padbuf ) ); memset( md5sum, 0, sizeof( md5sum ) ); memset( sha1sum, 0, sizeof( sha1sum ) ); SSL_DEBUG_MSG( 2, ( "<= calc finished" ) ); } static void ssl_calc_finished_tls( ssl_context *ssl, unsigned char *buf, int from ) { int len = 12; const char *sender; md5_context md5; sha1_context sha1; unsigned char padbuf[36]; ssl_session *session = ssl->session_negotiate; if( !session ) session = ssl->session; SSL_DEBUG_MSG( 2, ( "=> calc finished tls" ) ); memcpy( &md5 , &ssl->handshake->fin_md5 , sizeof(md5_context) ); memcpy( &sha1, &ssl->handshake->fin_sha1, sizeof(sha1_context) ); /* * TLSv1: * hash = PRF( master, finished_label, * MD5( handshake ) + SHA1( handshake ) )[0..11] */ SSL_DEBUG_BUF( 4, "finished md5 state", (unsigned char *) md5.state, sizeof( md5.state ) ); SSL_DEBUG_BUF( 4, "finished sha1 state", (unsigned char *) sha1.state, sizeof( sha1.state ) ); sender = ( from == SSL_IS_CLIENT ) ? "client finished" : "server finished"; md5_finish( &md5, padbuf ); sha1_finish( &sha1, padbuf + 16 ); ssl->handshake->tls_prf( session->master, 48, (char *) sender, padbuf, 36, buf, len ); SSL_DEBUG_BUF( 3, "calc finished result", buf, len ); memset( &md5, 0, sizeof( md5_context ) ); memset( &sha1, 0, sizeof( sha1_context ) ); memset( padbuf, 0, sizeof( padbuf ) ); SSL_DEBUG_MSG( 2, ( "<= calc finished" ) ); } static void ssl_calc_finished_tls_sha256( ssl_context *ssl, unsigned char *buf, int from ) { int len = 12; const char *sender; sha2_context sha2; unsigned char padbuf[32]; ssl_session *session = ssl->session_negotiate; if( !session ) session = ssl->session; SSL_DEBUG_MSG( 2, ( "=> calc finished tls sha256" ) ); memcpy( &sha2, &ssl->handshake->fin_sha2, sizeof(sha2_context) ); /* * TLSv1.2: * hash = PRF( master, finished_label, * Hash( handshake ) )[0.11] */ SSL_DEBUG_BUF( 4, "finished sha2 state", (unsigned char *) sha2.state, sizeof( sha2.state ) ); sender = ( from == SSL_IS_CLIENT ) ? "client finished" : "server finished"; sha2_finish( &sha2, padbuf ); ssl->handshake->tls_prf( session->master, 48, (char *) sender, padbuf, 32, buf, len ); SSL_DEBUG_BUF( 3, "calc finished result", buf, len ); memset( &sha2, 0, sizeof( sha2_context ) ); memset( padbuf, 0, sizeof( padbuf ) ); SSL_DEBUG_MSG( 2, ( "<= calc finished" ) ); } #if defined(POLARSSL_SHA4_C) static void ssl_calc_finished_tls_sha384( ssl_context *ssl, unsigned char *buf, int from ) { int len = 12; const char *sender; sha4_context sha4; unsigned char padbuf[48]; ssl_session *session = ssl->session_negotiate; if( !session ) session = ssl->session; SSL_DEBUG_MSG( 2, ( "=> calc finished tls sha384" ) ); memcpy( &sha4, &ssl->handshake->fin_sha4, sizeof(sha4_context) ); /* * TLSv1.2: * hash = PRF( master, finished_label, * Hash( handshake ) )[0.11] */ SSL_DEBUG_BUF( 4, "finished sha4 state", (unsigned char *) sha4.state, sizeof( sha4.state ) ); sender = ( from == SSL_IS_CLIENT ) ? "client finished" : "server finished"; sha4_finish( &sha4, padbuf ); ssl->handshake->tls_prf( session->master, 48, (char *) sender, padbuf, 48, buf, len ); SSL_DEBUG_BUF( 3, "calc finished result", buf, len ); memset( &sha4, 0, sizeof( sha4_context ) ); memset( padbuf, 0, sizeof( padbuf ) ); SSL_DEBUG_MSG( 2, ( "<= calc finished" ) ); } #endif void ssl_handshake_wrapup( ssl_context *ssl ) { SSL_DEBUG_MSG( 3, ( "=> handshake wrapup" ) ); /* * Free our handshake params */ ssl_handshake_free( ssl->handshake ); free( ssl->handshake ); ssl->handshake = NULL; /* * Switch in our now active transform context */ if( ssl->transform ) { ssl_transform_free( ssl->transform ); free( ssl->transform ); } ssl->transform = ssl->transform_negotiate; ssl->transform_negotiate = NULL; if( ssl->session ) { ssl_session_free( ssl->session ); free( ssl->session ); } ssl->session = ssl->session_negotiate; ssl->session_negotiate = NULL; /* * Add cache entry */ if( ssl->f_set_cache != NULL ) if( ssl->f_set_cache( ssl->p_set_cache, ssl->session ) != 0 ) SSL_DEBUG_MSG( 1, ( "cache did not store session" ) ); ssl->state++; SSL_DEBUG_MSG( 3, ( "<= handshake wrapup" ) ); } int ssl_write_finished( ssl_context *ssl ) { int ret, hash_len; SSL_DEBUG_MSG( 2, ( "=> write finished" ) ); ssl->handshake->calc_finished( ssl, ssl->out_msg + 4, ssl->endpoint ); // TODO TLS/1.2 Hash length is determined by cipher suite (Page 63) hash_len = ( ssl->minor_ver == SSL_MINOR_VERSION_0 ) ? 36 : 12; ssl->verify_data_len = hash_len; memcpy( ssl->own_verify_data, ssl->out_msg + 4, hash_len ); ssl->out_msglen = 4 + hash_len; ssl->out_msgtype = SSL_MSG_HANDSHAKE; ssl->out_msg[0] = SSL_HS_FINISHED; /* * In case of session resuming, invert the client and server * ChangeCipherSpec messages order. */ if( ssl->handshake->resume != 0 ) { if( ssl->endpoint == SSL_IS_CLIENT ) ssl->state = SSL_HANDSHAKE_WRAPUP; else ssl->state = SSL_CLIENT_CHANGE_CIPHER_SPEC; } else ssl->state++; /* * Switch to our negotiated transform and session parameters for outbound data. */ SSL_DEBUG_MSG( 3, ( "switching to new transform spec for outbound data" ) ); ssl->transform_out = ssl->transform_negotiate; ssl->session_out = ssl->session_negotiate; memset( ssl->out_ctr, 0, 8 ); if( ( ret = ssl_write_record( ssl ) ) != 0 ) { SSL_DEBUG_RET( 1, "ssl_write_record", ret ); return( ret ); } SSL_DEBUG_MSG( 2, ( "<= write finished" ) ); return( 0 ); } int ssl_parse_finished( ssl_context *ssl ) { int ret; unsigned int hash_len; unsigned char buf[36]; SSL_DEBUG_MSG( 2, ( "=> parse finished" ) ); ssl->handshake->calc_finished( ssl, buf, ssl->endpoint ^ 1 ); /* * Switch to our negotiated transform and session parameters for inbound data. */ SSL_DEBUG_MSG( 3, ( "switching to new transform spec for inbound data" ) ); ssl->transform_in = ssl->transform_negotiate; ssl->session_in = ssl->session_negotiate; memset( ssl->in_ctr, 0, 8 ); if( ( ret = ssl_read_record( ssl ) ) != 0 ) { SSL_DEBUG_RET( 1, "ssl_read_record", ret ); return( ret ); } if( ssl->in_msgtype != SSL_MSG_HANDSHAKE ) { SSL_DEBUG_MSG( 1, ( "bad finished message" ) ); return( POLARSSL_ERR_SSL_UNEXPECTED_MESSAGE ); } // TODO TLS/1.2 Hash length is determined by cipher suite (Page 63) hash_len = ( ssl->minor_ver == SSL_MINOR_VERSION_0 ) ? 36 : 12; if( ssl->in_msg[0] != SSL_HS_FINISHED || ssl->in_hslen != 4 + hash_len ) { SSL_DEBUG_MSG( 1, ( "bad finished message" ) ); return( POLARSSL_ERR_SSL_BAD_HS_FINISHED ); } if( memcmp( ssl->in_msg + 4, buf, hash_len ) != 0 ) { SSL_DEBUG_MSG( 1, ( "bad finished message" ) ); return( POLARSSL_ERR_SSL_BAD_HS_FINISHED ); } ssl->verify_data_len = hash_len; memcpy( ssl->peer_verify_data, buf, hash_len ); if( ssl->handshake->resume != 0 ) { if( ssl->endpoint == SSL_IS_CLIENT ) ssl->state = SSL_CLIENT_CHANGE_CIPHER_SPEC; if( ssl->endpoint == SSL_IS_SERVER ) ssl->state = SSL_HANDSHAKE_WRAPUP; } else ssl->state++; SSL_DEBUG_MSG( 2, ( "<= parse finished" ) ); return( 0 ); } int ssl_handshake_init( ssl_context *ssl ) { if( ssl->transform_negotiate ) ssl_transform_free( ssl->transform_negotiate ); else ssl->transform_negotiate = malloc( sizeof(ssl_transform) ); if( ssl->session_negotiate ) ssl_session_free( ssl->session_negotiate ); else ssl->session_negotiate = malloc( sizeof(ssl_session) ); if( ssl->handshake ) ssl_handshake_free( ssl->handshake ); else ssl->handshake = malloc( sizeof(ssl_handshake_params) ); if( ssl->handshake == NULL || ssl->transform_negotiate == NULL || ssl->session_negotiate == NULL ) { SSL_DEBUG_MSG( 1, ( "malloc() of ssl sub-contexts failed" ) ); return( POLARSSL_ERR_SSL_MALLOC_FAILED ); } memset( ssl->handshake, 0, sizeof(ssl_handshake_params) ); memset( ssl->transform_negotiate, 0, sizeof(ssl_transform) ); memset( ssl->session_negotiate, 0, sizeof(ssl_session) ); md5_starts( &ssl->handshake->fin_md5 ); sha1_starts( &ssl->handshake->fin_sha1 ); sha2_starts( &ssl->handshake->fin_sha2, 0 ); #if defined(POLARSSL_SHA4_C) sha4_starts( &ssl->handshake->fin_sha4, 1 ); #endif ssl->handshake->update_checksum = ssl_update_checksum_start; ssl->handshake->sig_alg = SSL_HASH_SHA1; return( 0 ); } /* * Initialize an SSL context */ int ssl_init( ssl_context *ssl ) { int ret; int len = SSL_BUFFER_LEN; memset( ssl, 0, sizeof( ssl_context ) ); /* * Sane defaults */ ssl->rsa_decrypt = ssl_rsa_decrypt; ssl->rsa_sign = ssl_rsa_sign; ssl->rsa_key_len = ssl_rsa_key_len; ssl->min_major_ver = SSL_MAJOR_VERSION_3; ssl->min_minor_ver = SSL_MINOR_VERSION_0; ssl->ciphersuites = malloc( sizeof(int *) * 4 ); ssl_set_ciphersuites( ssl, ssl_default_ciphersuites ); #if defined(POLARSSL_DHM_C) if( ( ret = mpi_read_string( &ssl->dhm_P, 16, POLARSSL_DHM_RFC5114_MODP_1024_P) ) != 0 || ( ret = mpi_read_string( &ssl->dhm_G, 16, POLARSSL_DHM_RFC5114_MODP_1024_G) ) != 0 ) { SSL_DEBUG_RET( 1, "mpi_read_string", ret ); return( ret ); } #endif /* * Prepare base structures */ ssl->in_ctr = (unsigned char *) malloc( len ); ssl->in_hdr = ssl->in_ctr + 8; ssl->in_msg = ssl->in_ctr + 13; if( ssl->in_ctr == NULL ) { SSL_DEBUG_MSG( 1, ( "malloc(%d bytes) failed", len ) ); return( POLARSSL_ERR_SSL_MALLOC_FAILED ); } ssl->out_ctr = (unsigned char *) malloc( len ); ssl->out_hdr = ssl->out_ctr + 8; ssl->out_msg = ssl->out_ctr + 40; if( ssl->out_ctr == NULL ) { SSL_DEBUG_MSG( 1, ( "malloc(%d bytes) failed", len ) ); free( ssl-> in_ctr ); return( POLARSSL_ERR_SSL_MALLOC_FAILED ); } memset( ssl-> in_ctr, 0, SSL_BUFFER_LEN ); memset( ssl->out_ctr, 0, SSL_BUFFER_LEN ); ssl->hostname = NULL; ssl->hostname_len = 0; if( ( ret = ssl_handshake_init( ssl ) ) != 0 ) return( ret ); return( 0 ); } /* * Reset an initialized and used SSL context for re-use while retaining * all application-set variables, function pointers and data. */ int ssl_session_reset( ssl_context *ssl ) { int ret; ssl->state = SSL_HELLO_REQUEST; ssl->renegotiation = SSL_INITIAL_HANDSHAKE; ssl->secure_renegotiation = SSL_LEGACY_RENEGOTIATION; ssl->verify_data_len = 0; memset( ssl->own_verify_data, 0, 36 ); memset( ssl->peer_verify_data, 0, 36 ); ssl->in_offt = NULL; ssl->in_msgtype = 0; ssl->in_msglen = 0; ssl->in_left = 0; ssl->in_hslen = 0; ssl->nb_zero = 0; ssl->out_msgtype = 0; ssl->out_msglen = 0; ssl->out_left = 0; ssl->transform_in = NULL; ssl->transform_out = NULL; memset( ssl->out_ctr, 0, SSL_BUFFER_LEN ); memset( ssl->in_ctr, 0, SSL_BUFFER_LEN ); #if defined(POLARSSL_SSL_HW_RECORD_ACCEL) if( ssl_hw_record_reset != NULL) { SSL_DEBUG_MSG( 2, ( "going for ssl_hw_record_reset()" ) ); if( ssl_hw_record_reset( ssl ) != 0 ) { SSL_DEBUG_RET( 1, "ssl_hw_record_reset", ret ); return( POLARSSL_ERR_SSL_HW_ACCEL_FAILED ); } } #endif if( ssl->transform ) { ssl_transform_free( ssl->transform ); free( ssl->transform ); ssl->transform = NULL; } if( ssl->session ) { ssl_session_free( ssl->session ); free( ssl->session ); ssl->session = NULL; } if( ( ret = ssl_handshake_init( ssl ) ) != 0 ) return( ret ); return( 0 ); } /* * SSL set accessors */ void ssl_set_endpoint( ssl_context *ssl, int endpoint ) { ssl->endpoint = endpoint; } void ssl_set_authmode( ssl_context *ssl, int authmode ) { ssl->authmode = authmode; } void ssl_set_verify( ssl_context *ssl, int (*f_vrfy)(void *, x509_cert *, int, int *), void *p_vrfy ) { ssl->f_vrfy = f_vrfy; ssl->p_vrfy = p_vrfy; } void ssl_set_rng( ssl_context *ssl, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ) { ssl->f_rng = f_rng; ssl->p_rng = p_rng; } void ssl_set_dbg( ssl_context *ssl, void (*f_dbg)(void *, int, const char *), void *p_dbg ) { ssl->f_dbg = f_dbg; ssl->p_dbg = p_dbg; } void ssl_set_bio( ssl_context *ssl, int (*f_recv)(void *, unsigned char *, size_t), void *p_recv, int (*f_send)(void *, const unsigned char *, size_t), void *p_send ) { ssl->f_recv = f_recv; ssl->f_send = f_send; ssl->p_recv = p_recv; ssl->p_send = p_send; } void ssl_set_session_cache( ssl_context *ssl, int (*f_get_cache)(void *, ssl_session *), void *p_get_cache, int (*f_set_cache)(void *, const ssl_session *), void *p_set_cache ) { ssl->f_get_cache = f_get_cache; ssl->p_get_cache = p_get_cache; ssl->f_set_cache = f_set_cache; ssl->p_set_cache = p_set_cache; } void ssl_set_session( ssl_context *ssl, const ssl_session *session ) { memcpy( ssl->session_negotiate, session, sizeof(ssl_session) ); ssl->handshake->resume = 1; } void ssl_set_ciphersuites( ssl_context *ssl, const int *ciphersuites ) { ssl->ciphersuites[SSL_MINOR_VERSION_0] = ciphersuites; ssl->ciphersuites[SSL_MINOR_VERSION_1] = ciphersuites; ssl->ciphersuites[SSL_MINOR_VERSION_2] = ciphersuites; ssl->ciphersuites[SSL_MINOR_VERSION_3] = ciphersuites; } void ssl_set_ciphersuites_for_version( ssl_context *ssl, const int *ciphersuites, int major, int minor ) { if( major != SSL_MAJOR_VERSION_3 ) return; if( minor < SSL_MINOR_VERSION_0 || minor > SSL_MINOR_VERSION_3 ) return; ssl->ciphersuites[minor] = ciphersuites; } void ssl_set_ca_chain( ssl_context *ssl, x509_cert *ca_chain, x509_crl *ca_crl, const char *peer_cn ) { ssl->ca_chain = ca_chain; ssl->ca_crl = ca_crl; ssl->peer_cn = peer_cn; } void ssl_set_own_cert( ssl_context *ssl, x509_cert *own_cert, rsa_context *rsa_key ) { ssl->own_cert = own_cert; ssl->rsa_key = rsa_key; } void ssl_set_own_cert_alt( ssl_context *ssl, x509_cert *own_cert, void *rsa_key, rsa_decrypt_func rsa_decrypt, rsa_sign_func rsa_sign, rsa_key_len_func rsa_key_len ) { ssl->own_cert = own_cert; ssl->rsa_key = rsa_key; ssl->rsa_decrypt = rsa_decrypt; ssl->rsa_sign = rsa_sign; ssl->rsa_key_len = rsa_key_len; } #if defined(POLARSSL_DHM_C) int ssl_set_dh_param( ssl_context *ssl, const char *dhm_P, const char *dhm_G ) { int ret; if( ( ret = mpi_read_string( &ssl->dhm_P, 16, dhm_P ) ) != 0 ) { SSL_DEBUG_RET( 1, "mpi_read_string", ret ); return( ret ); } if( ( ret = mpi_read_string( &ssl->dhm_G, 16, dhm_G ) ) != 0 ) { SSL_DEBUG_RET( 1, "mpi_read_string", ret ); return( ret ); } return( 0 ); } int ssl_set_dh_param_ctx( ssl_context *ssl, dhm_context *dhm_ctx ) { int ret; if( ( ret = mpi_copy(&ssl->dhm_P, &dhm_ctx->P) ) != 0 ) { SSL_DEBUG_RET( 1, "mpi_copy", ret ); return( ret ); } if( ( ret = mpi_copy(&ssl->dhm_G, &dhm_ctx->G) ) != 0 ) { SSL_DEBUG_RET( 1, "mpi_copy", ret ); return( ret ); } return( 0 ); } #endif /* POLARSSL_DHM_C */ int ssl_set_hostname( ssl_context *ssl, const char *hostname ) { if( hostname == NULL ) return( POLARSSL_ERR_SSL_BAD_INPUT_DATA ); ssl->hostname_len = strlen( hostname ); ssl->hostname = (unsigned char *) malloc( ssl->hostname_len + 1 ); if( ssl->hostname == NULL ) return( POLARSSL_ERR_SSL_MALLOC_FAILED ); memcpy( ssl->hostname, (const unsigned char *) hostname, ssl->hostname_len ); ssl->hostname[ssl->hostname_len] = '\0'; return( 0 ); } void ssl_set_sni( ssl_context *ssl, int (*f_sni)(void *, ssl_context *, const unsigned char *, size_t), void *p_sni ) { ssl->f_sni = f_sni; ssl->p_sni = p_sni; } void ssl_set_max_version( ssl_context *ssl, int major, int minor ) { ssl->max_major_ver = major; ssl->max_minor_ver = minor; } void ssl_set_min_version( ssl_context *ssl, int major, int minor ) { ssl->min_major_ver = major; ssl->min_minor_ver = minor; } void ssl_set_renegotiation( ssl_context *ssl, int renegotiation ) { ssl->disable_renegotiation = renegotiation; } void ssl_legacy_renegotiation( ssl_context *ssl, int allow_legacy ) { ssl->allow_legacy_renegotiation = allow_legacy; } /* * SSL get accessors */ size_t ssl_get_bytes_avail( const ssl_context *ssl ) { return( ssl->in_offt == NULL ? 0 : ssl->in_msglen ); } int ssl_get_verify_result( const ssl_context *ssl ) { return( ssl->verify_result ); } const char *ssl_get_ciphersuite_name( const int ciphersuite_id ) { switch( ciphersuite_id ) { #if defined(POLARSSL_ARC4_C) case TLS_RSA_WITH_RC4_128_MD5: return( "TLS-RSA-WITH-RC4-128-MD5" ); case TLS_RSA_WITH_RC4_128_SHA: return( "TLS-RSA-WITH-RC4-128-SHA" ); #endif #if defined(POLARSSL_DES_C) case TLS_RSA_WITH_3DES_EDE_CBC_SHA: return( "TLS-RSA-WITH-3DES-EDE-CBC-SHA" ); case TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA: return( "TLS-DHE-RSA-WITH-3DES-EDE-CBC-SHA" ); #endif #if defined(POLARSSL_AES_C) case TLS_RSA_WITH_AES_128_CBC_SHA: return( "TLS-RSA-WITH-AES-128-CBC-SHA" ); case TLS_DHE_RSA_WITH_AES_128_CBC_SHA: return( "TLS-DHE-RSA-WITH-AES-128-CBC-SHA" ); case TLS_RSA_WITH_AES_256_CBC_SHA: return( "TLS-RSA-WITH-AES-256-CBC-SHA" ); case TLS_DHE_RSA_WITH_AES_256_CBC_SHA: return( "TLS-DHE-RSA-WITH-AES-256-CBC-SHA" ); #if defined(POLARSSL_SHA2_C) case TLS_RSA_WITH_AES_128_CBC_SHA256: return( "TLS-RSA-WITH-AES-128-CBC-SHA256" ); case TLS_RSA_WITH_AES_256_CBC_SHA256: return( "TLS-RSA-WITH-AES-256-CBC-SHA256" ); case TLS_DHE_RSA_WITH_AES_128_CBC_SHA256: return( "TLS-DHE-RSA-WITH-AES-128-CBC-SHA256" ); case TLS_DHE_RSA_WITH_AES_256_CBC_SHA256: return( "TLS-DHE-RSA-WITH-AES-256-CBC-SHA256" ); #endif #if defined(POLARSSL_GCM_C) && defined(POLARSSL_SHA2_C) case TLS_RSA_WITH_AES_128_GCM_SHA256: return( "TLS-RSA-WITH-AES-128-GCM-SHA256" ); case TLS_RSA_WITH_AES_256_GCM_SHA384: return( "TLS-RSA-WITH-AES-256-GCM-SHA384" ); #endif #if defined(POLARSSL_GCM_C) && defined(POLARSSL_SHA4_C) case TLS_DHE_RSA_WITH_AES_128_GCM_SHA256: return( "TLS-DHE-RSA-WITH-AES-128-GCM-SHA256" ); case TLS_DHE_RSA_WITH_AES_256_GCM_SHA384: return( "TLS-DHE-RSA-WITH-AES-256-GCM-SHA384" ); #endif #endif /* POLARSSL_AES_C */ #if defined(POLARSSL_CAMELLIA_C) case TLS_RSA_WITH_CAMELLIA_128_CBC_SHA: return( "TLS-RSA-WITH-CAMELLIA-128-CBC-SHA" ); case TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA: return( "TLS-DHE-RSA-WITH-CAMELLIA-128-CBC-SHA" ); case TLS_RSA_WITH_CAMELLIA_256_CBC_SHA: return( "TLS-RSA-WITH-CAMELLIA-256-CBC-SHA" ); case TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA: return( "TLS-DHE-RSA-WITH-CAMELLIA-256-CBC-SHA" ); #if defined(POLARSSL_SHA2_C) case TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256: return( "TLS-RSA-WITH-CAMELLIA-128-CBC-SHA256" ); case TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256: return( "TLS-DHE-RSA-WITH-CAMELLIA-128-CBC-SHA256" ); case TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256: return( "TLS-RSA-WITH-CAMELLIA-256-CBC-SHA256" ); case TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256: return( "TLS-DHE-RSA-WITH-CAMELLIA-256-CBC-SHA256" ); #endif #endif #if defined(POLARSSL_ENABLE_WEAK_CIPHERSUITES) #if defined(POLARSSL_CIPHER_NULL_CIPHER) case TLS_RSA_WITH_NULL_MD5: return( "TLS-RSA-WITH-NULL-MD5" ); case TLS_RSA_WITH_NULL_SHA: return( "TLS-RSA-WITH-NULL-SHA" ); case TLS_RSA_WITH_NULL_SHA256: return( "TLS-RSA-WITH-NULL-SHA256" ); #endif /* defined(POLARSSL_CIPHER_NULL_CIPHER) */ #if defined(POLARSSL_DES_C) case TLS_RSA_WITH_DES_CBC_SHA: return( "TLS-RSA-WITH-DES-CBC-SHA" ); case TLS_DHE_RSA_WITH_DES_CBC_SHA: return( "TLS-DHE-RSA-WITH-DES-CBC-SHA" ); #endif #endif /* defined(POLARSSL_ENABLE_WEAK_CIPHERSUITES) */ default: break; } return( "unknown" ); } int ssl_get_ciphersuite_id( const char *ciphersuite_name ) { #if defined(POLARSSL_ARC4_C) if (0 == strcasecmp(ciphersuite_name, "TLS-RSA-WITH-RC4-128-MD5")) return( TLS_RSA_WITH_RC4_128_MD5 ); if (0 == strcasecmp(ciphersuite_name, "TLS-RSA-WITH-RC4-128-SHA")) return( TLS_RSA_WITH_RC4_128_SHA ); #endif #if defined(POLARSSL_DES_C) if (0 == strcasecmp(ciphersuite_name, "TLS-RSA-WITH-3DES-EDE-CBC-SHA")) return( TLS_RSA_WITH_3DES_EDE_CBC_SHA ); if (0 == strcasecmp(ciphersuite_name, "TLS-DHE-RSA-WITH-3DES-EDE-CBC-SHA")) return( TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA ); #endif #if defined(POLARSSL_AES_C) if (0 == strcasecmp(ciphersuite_name, "TLS-RSA-WITH-AES-128-CBC-SHA")) return( TLS_RSA_WITH_AES_128_CBC_SHA ); if (0 == strcasecmp(ciphersuite_name, "TLS-DHE-RSA-WITH-AES-128-CBC-SHA")) return( TLS_DHE_RSA_WITH_AES_128_CBC_SHA ); if (0 == strcasecmp(ciphersuite_name, "TLS-RSA-WITH-AES-256-CBC-SHA")) return( TLS_RSA_WITH_AES_256_CBC_SHA ); if (0 == strcasecmp(ciphersuite_name, "TLS-DHE-RSA-WITH-AES-256-CBC-SHA")) return( TLS_DHE_RSA_WITH_AES_256_CBC_SHA ); #if defined(POLARSSL_SHA2_C) if (0 == strcasecmp(ciphersuite_name, "TLS-RSA-WITH-AES-128-CBC-SHA256")) return( TLS_RSA_WITH_AES_128_CBC_SHA256 ); if (0 == strcasecmp(ciphersuite_name, "TLS-RSA-WITH-AES-256-CBC-SHA256")) return( TLS_RSA_WITH_AES_256_CBC_SHA256 ); if (0 == strcasecmp(ciphersuite_name, "TLS-DHE-RSA-WITH-AES-128-CBC-SHA256")) return( TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 ); if (0 == strcasecmp(ciphersuite_name, "TLS-DHE-RSA-WITH-AES-256-CBC-SHA256")) return( TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 ); #endif #if defined(POLARSSL_GCM_C) && defined(POLARSSL_SHA2_C) if (0 == strcasecmp(ciphersuite_name, "TLS-RSA-WITH-AES-128-GCM-SHA256")) return( TLS_RSA_WITH_AES_128_GCM_SHA256 ); if (0 == strcasecmp(ciphersuite_name, "TLS-RSA-WITH-AES-256-GCM-SHA384")) return( TLS_RSA_WITH_AES_256_GCM_SHA384 ); #endif #if defined(POLARSSL_GCM_C) && defined(POLARSSL_SHA2_C) if (0 == strcasecmp(ciphersuite_name, "TLS-DHE-RSA-WITH-AES-128-GCM-SHA256")) return( TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 ); if (0 == strcasecmp(ciphersuite_name, "TLS-DHE-RSA-WITH-AES-256-GCM-SHA384")) return( TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 ); #endif #endif #if defined(POLARSSL_CAMELLIA_C) if (0 == strcasecmp(ciphersuite_name, "TLS-RSA-WITH-CAMELLIA-128-CBC-SHA")) return( TLS_RSA_WITH_CAMELLIA_128_CBC_SHA ); if (0 == strcasecmp(ciphersuite_name, "TLS-DHE-RSA-WITH-CAMELLIA-128-CBC-SHA")) return( TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA ); if (0 == strcasecmp(ciphersuite_name, "TLS-RSA-WITH-CAMELLIA-256-CBC-SHA")) return( TLS_RSA_WITH_CAMELLIA_256_CBC_SHA ); if (0 == strcasecmp(ciphersuite_name, "TLS-DHE-RSA-WITH-CAMELLIA-256-CBC-SHA")) return( TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA ); #if defined(POLARSSL_SHA2_C) if (0 == strcasecmp(ciphersuite_name, "TLS-RSA-WITH-CAMELLIA-128-CBC-SHA256")) return( TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256 ); if (0 == strcasecmp(ciphersuite_name, "TLS-DHE-RSA-WITH-CAMELLIA-128-CBC-SHA256")) return( TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 ); if (0 == strcasecmp(ciphersuite_name, "TLS-RSA-WITH-CAMELLIA-256-CBC-SHA256")) return( TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256 ); if (0 == strcasecmp(ciphersuite_name, "TLS-DHE-RSA-WITH-CAMELLIA-256-CBC-SHA256")) return( TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256 ); #endif #endif #if defined(POLARSSL_ENABLE_WEAK_CIPHERSUITES) #if defined(POLARSSL_CIPHER_NULL_CIPHER) if (0 == strcasecmp(ciphersuite_name, "TLS-RSA-WITH-NULL-MD5")) return( TLS_RSA_WITH_NULL_MD5 ); if (0 == strcasecmp(ciphersuite_name, "TLS-RSA-WITH-NULL-SHA")) return( TLS_RSA_WITH_NULL_SHA ); if (0 == strcasecmp(ciphersuite_name, "TLS-RSA-WITH-NULL-SHA256")) return( TLS_RSA_WITH_NULL_SHA256 ); #endif /* defined(POLARSSL_CIPHER_NULL_CIPHER) */ #if defined(POLARSSL_DES_C) if (0 == strcasecmp(ciphersuite_name, "TLS-RSA-WITH-DES-CBC-SHA")) return( TLS_RSA_WITH_DES_CBC_SHA ); if (0 == strcasecmp(ciphersuite_name, "TLS-DHE-RSA-WITH-DES-CBC-SHA")) return( TLS_DHE_RSA_WITH_DES_CBC_SHA ); #endif #endif /* defined(POLARSSL_ENABLE_WEAK_CIPHERSUITES) */ return( 0 ); } const char *ssl_get_ciphersuite( const ssl_context *ssl ) { if( ssl == NULL || ssl->session == NULL ) return NULL; return ssl_get_ciphersuite_name( ssl->session->ciphersuite ); } const char *ssl_get_version( const ssl_context *ssl ) { switch( ssl->minor_ver ) { case SSL_MINOR_VERSION_0: return( "SSLv3.0" ); case SSL_MINOR_VERSION_1: return( "TLSv1.0" ); case SSL_MINOR_VERSION_2: return( "TLSv1.1" ); case SSL_MINOR_VERSION_3: return( "TLSv1.2" ); default: break; } return( "unknown" ); } const x509_cert *ssl_get_peer_cert( const ssl_context *ssl ) { if( ssl == NULL || ssl->session == NULL ) return NULL; return ssl->session->peer_cert; } const int ssl_default_ciphersuites[] = { #if defined(POLARSSL_DHM_C) #if defined(POLARSSL_AES_C) #if defined(POLARSSL_SHA2_C) TLS_DHE_RSA_WITH_AES_256_CBC_SHA256, #endif /* POLARSSL_SHA2_C */ #if defined(POLARSSL_GCM_C) && defined(POLARSSL_SHA4_C) TLS_DHE_RSA_WITH_AES_256_GCM_SHA384, #endif TLS_DHE_RSA_WITH_AES_256_CBC_SHA, #if defined(POLARSSL_SHA2_C) TLS_DHE_RSA_WITH_AES_128_CBC_SHA256, #endif #if defined(POLARSSL_GCM_C) && defined(POLARSSL_SHA2_C) TLS_DHE_RSA_WITH_AES_128_GCM_SHA256, #endif TLS_DHE_RSA_WITH_AES_128_CBC_SHA, #endif #if defined(POLARSSL_CAMELLIA_C) #if defined(POLARSSL_SHA2_C) TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256, #endif /* POLARSSL_SHA2_C */ TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA, #if defined(POLARSSL_SHA2_C) TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256, #endif /* POLARSSL_SHA2_C */ TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA, #endif #if defined(POLARSSL_DES_C) TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA, #endif #endif #if defined(POLARSSL_AES_C) #if defined(POLARSSL_SHA2_C) TLS_RSA_WITH_AES_256_CBC_SHA256, #endif /* POLARSSL_SHA2_C */ #if defined(POLARSSL_GCM_C) && defined(POLARSSL_SHA4_C) TLS_RSA_WITH_AES_256_GCM_SHA384, #endif /* POLARSSL_SHA2_C */ TLS_RSA_WITH_AES_256_CBC_SHA, #endif #if defined(POLARSSL_CAMELLIA_C) #if defined(POLARSSL_SHA2_C) TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256, #endif /* POLARSSL_SHA2_C */ TLS_RSA_WITH_CAMELLIA_256_CBC_SHA, #endif #if defined(POLARSSL_AES_C) #if defined(POLARSSL_SHA2_C) TLS_RSA_WITH_AES_128_CBC_SHA256, #endif /* POLARSSL_SHA2_C */ #if defined(POLARSSL_GCM_C) && defined(POLARSSL_SHA2_C) TLS_RSA_WITH_AES_128_GCM_SHA256, #endif /* POLARSSL_SHA2_C */ TLS_RSA_WITH_AES_128_CBC_SHA, #endif #if defined(POLARSSL_CAMELLIA_C) #if defined(POLARSSL_SHA2_C) TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256, #endif /* POLARSSL_SHA2_C */ TLS_RSA_WITH_CAMELLIA_128_CBC_SHA, #endif #if defined(POLARSSL_DES_C) TLS_RSA_WITH_3DES_EDE_CBC_SHA, #endif #if defined(POLARSSL_ARC4_C) TLS_RSA_WITH_RC4_128_SHA, TLS_RSA_WITH_RC4_128_MD5, #endif 0 }; /* * Perform a single step of the SSL handshake */ int ssl_handshake_step( ssl_context *ssl ) { int ret = POLARSSL_ERR_SSL_FEATURE_UNAVAILABLE; #if defined(POLARSSL_SSL_CLI_C) if( ssl->endpoint == SSL_IS_CLIENT ) ret = ssl_handshake_client_step( ssl ); #endif #if defined(POLARSSL_SSL_SRV_C) if( ssl->endpoint == SSL_IS_SERVER ) ret = ssl_handshake_server_step( ssl ); #endif return( ret ); } /* * Perform the SSL handshake */ int ssl_handshake( ssl_context *ssl ) { int ret = 0; SSL_DEBUG_MSG( 2, ( "=> handshake" ) ); while( ssl->state != SSL_HANDSHAKE_OVER ) { ret = ssl_handshake_step( ssl ); if( ret != 0 ) break; } SSL_DEBUG_MSG( 2, ( "<= handshake" ) ); return( ret ); } /* * Renegotiate current connection */ int ssl_renegotiate( ssl_context *ssl ) { int ret; SSL_DEBUG_MSG( 2, ( "=> renegotiate" ) ); if( ssl->state != SSL_HANDSHAKE_OVER ) return( POLARSSL_ERR_SSL_BAD_INPUT_DATA ); ssl->state = SSL_HELLO_REQUEST; ssl->renegotiation = SSL_RENEGOTIATION; if( ( ret = ssl_handshake_init( ssl ) ) != 0 ) return( ret ); if( ( ret = ssl_handshake( ssl ) ) != 0 ) { SSL_DEBUG_RET( 1, "ssl_handshake", ret ); return( ret ); } SSL_DEBUG_MSG( 2, ( "<= renegotiate" ) ); return( 0 ); } /* * Receive application data decrypted from the SSL layer */ int ssl_read( ssl_context *ssl, unsigned char *buf, size_t len ) { int ret; size_t n; SSL_DEBUG_MSG( 2, ( "=> read" ) ); if( ssl->state != SSL_HANDSHAKE_OVER ) { if( ( ret = ssl_handshake( ssl ) ) != 0 ) { SSL_DEBUG_RET( 1, "ssl_handshake", ret ); return( ret ); } } if( ssl->in_offt == NULL ) { if( ( ret = ssl_read_record( ssl ) ) != 0 ) { if( ret == POLARSSL_ERR_SSL_CONN_EOF ) return( 0 ); SSL_DEBUG_RET( 1, "ssl_read_record", ret ); return( ret ); } if( ssl->in_msglen == 0 && ssl->in_msgtype == SSL_MSG_APPLICATION_DATA ) { /* * OpenSSL sends empty messages to randomize the IV */ if( ( ret = ssl_read_record( ssl ) ) != 0 ) { if( ret == POLARSSL_ERR_SSL_CONN_EOF ) return( 0 ); SSL_DEBUG_RET( 1, "ssl_read_record", ret ); return( ret ); } } if( ssl->in_msgtype == SSL_MSG_HANDSHAKE ) { SSL_DEBUG_MSG( 1, ( "received handshake message" ) ); if( ssl->endpoint == SSL_IS_CLIENT && ( ssl->in_msg[0] != SSL_HS_HELLO_REQUEST || ssl->in_hslen != 4 ) ) { SSL_DEBUG_MSG( 1, ( "handshake received (not HelloRequest)" ) ); return( POLARSSL_ERR_SSL_UNEXPECTED_MESSAGE ); } if( ssl->disable_renegotiation == SSL_RENEGOTIATION_DISABLED || ( ssl->secure_renegotiation == SSL_LEGACY_RENEGOTIATION && ssl->allow_legacy_renegotiation == SSL_LEGACY_NO_RENEGOTIATION ) ) { SSL_DEBUG_MSG( 3, ( "ignoring renegotiation, sending alert" ) ); if( ssl->minor_ver == SSL_MINOR_VERSION_0 ) { /* * SSLv3 does not have a "no_renegotiation" alert */ if( ( ret = ssl_send_fatal_handshake_failure( ssl ) ) != 0 ) return( ret ); } else { if( ( ret = ssl_send_alert_message( ssl, SSL_ALERT_LEVEL_WARNING, SSL_ALERT_MSG_NO_RENEGOTIATION ) ) != 0 ) { return( ret ); } } } else { if( ( ret = ssl_renegotiate( ssl ) ) != 0 ) { SSL_DEBUG_RET( 1, "ssl_renegotiate", ret ); return( ret ); } return( POLARSSL_ERR_NET_WANT_READ ); } } else if( ssl->in_msgtype != SSL_MSG_APPLICATION_DATA ) { SSL_DEBUG_MSG( 1, ( "bad application data message" ) ); return( POLARSSL_ERR_SSL_UNEXPECTED_MESSAGE ); } ssl->in_offt = ssl->in_msg; } n = ( len < ssl->in_msglen ) ? len : ssl->in_msglen; memcpy( buf, ssl->in_offt, n ); ssl->in_msglen -= n; if( ssl->in_msglen == 0 ) /* all bytes consumed */ ssl->in_offt = NULL; else /* more data available */ ssl->in_offt += n; SSL_DEBUG_MSG( 2, ( "<= read" ) ); return( (int) n ); } /* * Send application data to be encrypted by the SSL layer */ int ssl_write( ssl_context *ssl, const unsigned char *buf, size_t len ) { int ret; size_t n; SSL_DEBUG_MSG( 2, ( "=> write" ) ); if( ssl->state != SSL_HANDSHAKE_OVER ) { if( ( ret = ssl_handshake( ssl ) ) != 0 ) { SSL_DEBUG_RET( 1, "ssl_handshake", ret ); return( ret ); } } n = ( len < SSL_MAX_CONTENT_LEN ) ? len : SSL_MAX_CONTENT_LEN; if( ssl->out_left != 0 ) { if( ( ret = ssl_flush_output( ssl ) ) != 0 ) { SSL_DEBUG_RET( 1, "ssl_flush_output", ret ); return( ret ); } } else { ssl->out_msglen = n; ssl->out_msgtype = SSL_MSG_APPLICATION_DATA; memcpy( ssl->out_msg, buf, n ); if( ( ret = ssl_write_record( ssl ) ) != 0 ) { SSL_DEBUG_RET( 1, "ssl_write_record", ret ); return( ret ); } } SSL_DEBUG_MSG( 2, ( "<= write" ) ); return( (int) n ); } /* * Notify the peer that the connection is being closed */ int ssl_close_notify( ssl_context *ssl ) { int ret; SSL_DEBUG_MSG( 2, ( "=> write close notify" ) ); if( ( ret = ssl_flush_output( ssl ) ) != 0 ) { SSL_DEBUG_RET( 1, "ssl_flush_output", ret ); return( ret ); } if( ssl->state == SSL_HANDSHAKE_OVER ) { if( ( ret = ssl_send_alert_message( ssl, SSL_ALERT_LEVEL_WARNING, SSL_ALERT_MSG_CLOSE_NOTIFY ) ) != 0 ) { return( ret ); } } SSL_DEBUG_MSG( 2, ( "<= write close notify" ) ); return( ret ); } void ssl_transform_free( ssl_transform *transform ) { #if defined(POLARSSL_ZLIB_SUPPORT) deflateEnd( &transform->ctx_deflate ); inflateEnd( &transform->ctx_inflate ); #endif memset( transform, 0, sizeof( ssl_transform ) ); } void ssl_handshake_free( ssl_handshake_params *handshake ) { #if defined(POLARSSL_DHM_C) dhm_free( &handshake->dhm_ctx ); #endif memset( handshake, 0, sizeof( ssl_handshake_params ) ); } void ssl_session_free( ssl_session *session ) { if( session->peer_cert != NULL ) { x509_free( session->peer_cert ); free( session->peer_cert ); } memset( session, 0, sizeof( ssl_session ) ); } /* * Free an SSL context */ void ssl_free( ssl_context *ssl ) { SSL_DEBUG_MSG( 2, ( "=> free" ) ); free( ssl->ciphersuites ); if( ssl->out_ctr != NULL ) { memset( ssl->out_ctr, 0, SSL_BUFFER_LEN ); free( ssl->out_ctr ); } if( ssl->in_ctr != NULL ) { memset( ssl->in_ctr, 0, SSL_BUFFER_LEN ); free( ssl->in_ctr ); } #if defined(POLARSSL_DHM_C) mpi_free( &ssl->dhm_P ); mpi_free( &ssl->dhm_G ); #endif if( ssl->transform ) { ssl_transform_free( ssl->transform ); free( ssl->transform ); } if( ssl->handshake ) { ssl_handshake_free( ssl->handshake ); ssl_transform_free( ssl->transform_negotiate ); ssl_session_free( ssl->session_negotiate ); free( ssl->handshake ); free( ssl->transform_negotiate ); free( ssl->session_negotiate ); } if( ssl->session ) { ssl_session_free( ssl->session ); free( ssl->session ); } if ( ssl->hostname != NULL) { memset( ssl->hostname, 0, ssl->hostname_len ); free( ssl->hostname ); ssl->hostname_len = 0; } #if defined(POLARSSL_SSL_HW_RECORD_ACCEL) if( ssl_hw_record_finish != NULL ) { SSL_DEBUG_MSG( 2, ( "going for ssl_hw_record_finish()" ) ); ssl_hw_record_finish( ssl ); } #endif SSL_DEBUG_MSG( 2, ( "<= free" ) ); /* Actually clear after last debug message */ memset( ssl, 0, sizeof( ssl_context ) ); } #endif
./CrossVul/dataset_final_sorted/CWE-20/c/bad_5770_2
crossvul-cpp_data_good_2576_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M M PPPP CCCC % % MM MM P P C % % M M M PPPP C % % M M P C % % M M P CCCC % % % % % % Read/Write Magick Persistant Cache Image Format % % % % Software Design % % Cristy % % March 2000 % % % % % % Copyright 1999-2017 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://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/artifact.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/constitute.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/geometry.h" #include "magick/hashmap.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/magick.h" #include "magick/memory_.h" #include "magick/module.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/option.h" #include "magick/pixel-accessor.h" #include "magick/profile.h" #include "magick/property.h" #include "magick/quantum-private.h" #include "magick/resource_.h" #include "magick/static.h" #include "magick/statistic.h" #include "magick/string_.h" #include "magick/string-private.h" #include "magick/utility.h" #include "magick/version-private.h" /* Forward declarations. */ static MagickBooleanType WriteMPCImage(const ImageInfo *,Image *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s M P C % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsMPC() returns MagickTrue if the image format type, identified by the % magick string, is an Magick Persistent Cache image. % % The format of the IsMPC method is: % % MagickBooleanType IsMPC(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 IsMPC(const unsigned char *magick,const size_t length) { if (length < 14) return(MagickFalse); if (LocaleNCompare((const char *) magick,"id=MagickCache",14) == 0) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d C A C H E I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadMPCImage() reads an Magick Persistent Cache 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 ReadMPCImage method is: % % Image *ReadMPCImage(const ImageInfo *image_info,ExceptionInfo *exception) % % Decompression code contributed by Kyle Shorter. % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static Image *ReadMPCImage(const ImageInfo *image_info,ExceptionInfo *exception) { char cache_filename[MaxTextExtent], id[MaxTextExtent], keyword[MaxTextExtent], *options; const unsigned char *p; GeometryInfo geometry_info; Image *image; int c; LinkedListInfo *profiles; MagickBooleanType status; MagickOffsetType offset; MagickStatusType flags; register ssize_t i; size_t depth, length; ssize_t count; StringInfo *profile; unsigned int signature; /* 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); } (void) CopyMagickString(cache_filename,image->filename,MaxTextExtent); AppendImageFormat("cache",cache_filename); c=ReadBlobByte(image); if (c == EOF) { image=DestroyImage(image); return((Image *) NULL); } *id='\0'; (void) ResetMagickMemory(keyword,0,sizeof(keyword)); offset=0; do { /* Decode image header; header terminates one character beyond a ':'. */ profiles=(LinkedListInfo *) NULL; length=MaxTextExtent; options=AcquireString((char *) NULL); signature=GetMagickSignature((const StringInfo *) NULL); image->depth=8; image->compression=NoCompression; while ((isgraph(c) != MagickFalse) && (c != (int) ':')) { register char *p; if (c == (int) '{') { char *comment; /* Read comment-- any text between { }. */ length=MaxTextExtent; comment=AcquireString((char *) NULL); for (p=comment; comment != (char *) NULL; p++) { c=ReadBlobByte(image); if (c == (int) '\\') c=ReadBlobByte(image); else if ((c == EOF) || (c == (int) '}')) break; if ((size_t) (p-comment+1) >= length) { *p='\0'; length<<=1; comment=(char *) ResizeQuantumMemory(comment,length+ MaxTextExtent,sizeof(*comment)); if (comment == (char *) NULL) break; p=comment+strlen(comment); } *p=(char) c; } if (comment == (char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); *p='\0'; (void) SetImageProperty(image,"comment",comment); comment=DestroyString(comment); c=ReadBlobByte(image); } else if (isalnum(c) != MagickFalse) { /* Get the keyword. */ length=MaxTextExtent; p=keyword; do { if (c == (int) '=') break; if ((size_t) (p-keyword) < (MaxTextExtent-1)) *p++=(char) c; c=ReadBlobByte(image); } while (c != EOF); *p='\0'; p=options; while (isspace((int) ((unsigned char) c)) != 0) c=ReadBlobByte(image); if (c == (int) '=') { /* Get the keyword value. */ c=ReadBlobByte(image); while ((c != (int) '}') && (c != EOF)) { if ((size_t) (p-options+1) >= length) { *p='\0'; length<<=1; options=(char *) ResizeQuantumMemory(options,length+ MaxTextExtent,sizeof(*options)); if (options == (char *) NULL) break; p=options+strlen(options); } *p++=(char) c; c=ReadBlobByte(image); if (c == '\\') { c=ReadBlobByte(image); if (c == (int) '}') { *p++=(char) c; c=ReadBlobByte(image); } } if (*options != '{') if (isspace((int) ((unsigned char) c)) != 0) break; } if (options == (char *) NULL) ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } *p='\0'; if (*options == '{') (void) CopyMagickString(options,options+1,strlen(options)); /* Assign a value to the specified keyword. */ switch (*keyword) { case 'b': case 'B': { if (LocaleCompare(keyword,"background-color") == 0) { (void) QueryColorDatabase(options,&image->background_color, exception); break; } if (LocaleCompare(keyword,"blue-primary") == 0) { flags=ParseGeometry(options,&geometry_info); image->chromaticity.blue_primary.x=geometry_info.rho; image->chromaticity.blue_primary.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->chromaticity.blue_primary.y= image->chromaticity.blue_primary.x; break; } if (LocaleCompare(keyword,"border-color") == 0) { (void) QueryColorDatabase(options,&image->border_color, exception); break; } (void) SetImageProperty(image,keyword,options); break; } case 'c': case 'C': { if (LocaleCompare(keyword,"class") == 0) { ssize_t storage_class; storage_class=ParseCommandOption(MagickClassOptions, MagickFalse,options); if (storage_class < 0) break; image->storage_class=(ClassType) storage_class; break; } if (LocaleCompare(keyword,"colors") == 0) { image->colors=StringToUnsignedLong(options); break; } if (LocaleCompare(keyword,"colorspace") == 0) { ssize_t colorspace; colorspace=ParseCommandOption(MagickColorspaceOptions, MagickFalse,options); if (colorspace < 0) break; image->colorspace=(ColorspaceType) colorspace; break; } if (LocaleCompare(keyword,"compression") == 0) { ssize_t compression; compression=ParseCommandOption(MagickCompressOptions, MagickFalse,options); if (compression < 0) break; image->compression=(CompressionType) compression; break; } if (LocaleCompare(keyword,"columns") == 0) { image->columns=StringToUnsignedLong(options); break; } (void) SetImageProperty(image,keyword,options); break; } case 'd': case 'D': { if (LocaleCompare(keyword,"delay") == 0) { image->delay=StringToUnsignedLong(options); break; } if (LocaleCompare(keyword,"depth") == 0) { image->depth=StringToUnsignedLong(options); break; } if (LocaleCompare(keyword,"dispose") == 0) { ssize_t dispose; dispose=ParseCommandOption(MagickDisposeOptions,MagickFalse, options); if (dispose < 0) break; image->dispose=(DisposeType) dispose; break; } (void) SetImageProperty(image,keyword,options); break; } case 'e': case 'E': { if (LocaleCompare(keyword,"endian") == 0) { ssize_t endian; endian=ParseCommandOption(MagickEndianOptions,MagickFalse, options); if (endian < 0) break; image->endian=(EndianType) endian; break; } if (LocaleCompare(keyword,"error") == 0) { image->error.mean_error_per_pixel=StringToDouble(options, (char **) NULL); break; } (void) SetImageProperty(image,keyword,options); break; } case 'g': case 'G': { if (LocaleCompare(keyword,"gamma") == 0) { image->gamma=StringToDouble(options,(char **) NULL); break; } if (LocaleCompare(keyword,"green-primary") == 0) { flags=ParseGeometry(options,&geometry_info); image->chromaticity.green_primary.x=geometry_info.rho; image->chromaticity.green_primary.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->chromaticity.green_primary.y= image->chromaticity.green_primary.x; break; } (void) SetImageProperty(image,keyword,options); break; } case 'i': case 'I': { if (LocaleCompare(keyword,"id") == 0) { (void) CopyMagickString(id,options,MaxTextExtent); break; } if (LocaleCompare(keyword,"iterations") == 0) { image->iterations=StringToUnsignedLong(options); break; } (void) SetImageProperty(image,keyword,options); break; } case 'm': case 'M': { if (LocaleCompare(keyword,"magick-signature") == 0) { signature=(unsigned int) StringToUnsignedLong(options); break; } if (LocaleCompare(keyword,"matte") == 0) { ssize_t matte; matte=ParseCommandOption(MagickBooleanOptions,MagickFalse, options); if (matte < 0) break; image->matte=(MagickBooleanType) matte; break; } if (LocaleCompare(keyword,"matte-color") == 0) { (void) QueryColorDatabase(options,&image->matte_color, exception); break; } if (LocaleCompare(keyword,"maximum-error") == 0) { image->error.normalized_maximum_error=StringToDouble( options,(char **) NULL); break; } if (LocaleCompare(keyword,"mean-error") == 0) { image->error.normalized_mean_error=StringToDouble(options, (char **) NULL); break; } if (LocaleCompare(keyword,"montage") == 0) { (void) CloneString(&image->montage,options); break; } (void) SetImageProperty(image,keyword,options); break; } case 'o': case 'O': { if (LocaleCompare(keyword,"opaque") == 0) { ssize_t matte; matte=ParseCommandOption(MagickBooleanOptions,MagickFalse, options); if (matte < 0) break; image->matte=(MagickBooleanType) matte; break; } if (LocaleCompare(keyword,"orientation") == 0) { ssize_t orientation; orientation=ParseCommandOption(MagickOrientationOptions, MagickFalse,options); if (orientation < 0) break; image->orientation=(OrientationType) orientation; break; } (void) SetImageProperty(image,keyword,options); break; } case 'p': case 'P': { if (LocaleCompare(keyword,"page") == 0) { char *geometry; geometry=GetPageGeometry(options); (void) ParseAbsoluteGeometry(geometry,&image->page); geometry=DestroyString(geometry); break; } if (LocaleCompare(keyword,"pixel-intensity") == 0) { ssize_t intensity; intensity=ParseCommandOption(MagickPixelIntensityOptions, MagickFalse,options); if (intensity < 0) break; image->intensity=(PixelIntensityMethod) intensity; break; } if ((LocaleNCompare(keyword,"profile:",8) == 0) || (LocaleNCompare(keyword,"profile-",8) == 0)) { if (profiles == (LinkedListInfo *) NULL) profiles=NewLinkedList(0); (void) AppendValueToLinkedList(profiles, AcquireString(keyword+8)); profile=BlobToStringInfo((const void *) NULL,(size_t) StringToLong(options)); if (profile == (StringInfo *) NULL) ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); (void) SetImageProfile(image,keyword+8,profile); profile=DestroyStringInfo(profile); break; } (void) SetImageProperty(image,keyword,options); break; } case 'q': case 'Q': { if (LocaleCompare(keyword,"quality") == 0) { image->quality=StringToUnsignedLong(options); break; } (void) SetImageProperty(image,keyword,options); break; } case 'r': case 'R': { if (LocaleCompare(keyword,"red-primary") == 0) { flags=ParseGeometry(options,&geometry_info); image->chromaticity.red_primary.x=geometry_info.rho; if ((flags & SigmaValue) != 0) image->chromaticity.red_primary.y=geometry_info.sigma; break; } if (LocaleCompare(keyword,"rendering-intent") == 0) { ssize_t rendering_intent; rendering_intent=ParseCommandOption(MagickIntentOptions, MagickFalse,options); if (rendering_intent < 0) break; image->rendering_intent=(RenderingIntent) rendering_intent; break; } if (LocaleCompare(keyword,"resolution") == 0) { flags=ParseGeometry(options,&geometry_info); image->x_resolution=geometry_info.rho; image->y_resolution=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->y_resolution=image->x_resolution; break; } if (LocaleCompare(keyword,"rows") == 0) { image->rows=StringToUnsignedLong(options); break; } (void) SetImageProperty(image,keyword,options); break; } case 's': case 'S': { if (LocaleCompare(keyword,"scene") == 0) { image->scene=StringToUnsignedLong(options); break; } (void) SetImageProperty(image,keyword,options); break; } case 't': case 'T': { if (LocaleCompare(keyword,"ticks-per-second") == 0) { image->ticks_per_second=(ssize_t) StringToLong(options); break; } if (LocaleCompare(keyword,"tile-offset") == 0) { char *geometry; geometry=GetPageGeometry(options); (void) ParseAbsoluteGeometry(geometry,&image->tile_offset); geometry=DestroyString(geometry); } if (LocaleCompare(keyword,"type") == 0) { ssize_t type; type=ParseCommandOption(MagickTypeOptions,MagickFalse, options); if (type < 0) break; image->type=(ImageType) type; break; } (void) SetImageProperty(image,keyword,options); break; } case 'u': case 'U': { if (LocaleCompare(keyword,"units") == 0) { ssize_t units; units=ParseCommandOption(MagickResolutionOptions,MagickFalse, options); if (units < 0) break; image->units=(ResolutionType) units; break; } (void) SetImageProperty(image,keyword,options); break; } case 'w': case 'W': { if (LocaleCompare(keyword,"white-point") == 0) { flags=ParseGeometry(options,&geometry_info); image->chromaticity.white_point.x=geometry_info.rho; image->chromaticity.white_point.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->chromaticity.white_point.y= image->chromaticity.white_point.x; break; } (void) SetImageProperty(image,keyword,options); break; } default: { (void) SetImageProperty(image,keyword,options); break; } } } else c=ReadBlobByte(image); while (isspace((int) ((unsigned char) c)) != 0) c=ReadBlobByte(image); } options=DestroyString(options); (void) ReadBlobByte(image); /* Verify that required image information is defined. */ if ((LocaleCompare(id,"MagickCache") != 0) || (image->storage_class == UndefinedClass) || (image->compression == UndefinedCompression) || (image->columns == 0) || (image->rows == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (signature != GetMagickSignature((const StringInfo *) NULL)) ThrowReaderException(CacheError,"IncompatibleAPI"); if (image->montage != (char *) NULL) { register char *p; /* Image directory. */ length=MaxTextExtent; image->directory=AcquireString((char *) NULL); p=image->directory; do { *p='\0'; if ((strlen(image->directory)+MaxTextExtent) >= length) { /* Allocate more memory for the image directory. */ length<<=1; image->directory=(char *) ResizeQuantumMemory(image->directory, length+MaxTextExtent,sizeof(*image->directory)); if (image->directory == (char *) NULL) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); p=image->directory+strlen(image->directory); } c=ReadBlobByte(image); *p++=(char) c; } while (c != (int) '\0'); } if (profiles != (LinkedListInfo *) NULL) { const char *name; const StringInfo *profile; register unsigned char *p; /* Read image profiles. */ ResetLinkedListIterator(profiles); name=(const char *) GetNextValueInLinkedList(profiles); while (name != (const char *) NULL) { profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { p=GetStringInfoDatum(profile); (void) ReadBlob(image,GetStringInfoLength(profile),p); } name=(const char *) GetNextValueInLinkedList(profiles); } profiles=DestroyLinkedList(profiles,RelinquishMagickMemory); } depth=GetImageQuantumDepth(image,MagickFalse); if (image->storage_class == PseudoClass) { size_t packet_size; unsigned char *colormap; /* Create image colormap. */ packet_size=(size_t) (3UL*depth/8UL); if ((packet_size*image->colors) > GetBlobSize(image)) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); image->colormap=(PixelPacket *) AcquireQuantumMemory(image->colors+1, sizeof(*image->colormap)); if (image->colormap == (PixelPacket *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (image->colors != 0) { /* Read image colormap from file. */ colormap=(unsigned char *) AcquireQuantumMemory(image->colors, packet_size*sizeof(*colormap)); if (colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,packet_size*image->colors,colormap); if (count != (ssize_t) (packet_size*image->colors)) { colormap=(unsigned char *) RelinquishMagickMemory(colormap); ThrowReaderException(CorruptImageError, "InsufficientImageDataInFile"); } p=colormap; switch (depth) { default: colormap=(unsigned char *) RelinquishMagickMemory(colormap); ThrowReaderException(CorruptImageError, "ImageDepthNotSupported"); case 8: { unsigned char pixel; for (i=0; i < (ssize_t) image->colors; i++) { p=PushCharPixel(p,&pixel); image->colormap[i].red=ScaleCharToQuantum(pixel); p=PushCharPixel(p,&pixel); image->colormap[i].green=ScaleCharToQuantum(pixel); p=PushCharPixel(p,&pixel); image->colormap[i].blue=ScaleCharToQuantum(pixel); } break; } case 16: { unsigned short pixel; for (i=0; i < (ssize_t) image->colors; i++) { p=PushShortPixel(MSBEndian,p,&pixel); image->colormap[i].red=ScaleShortToQuantum(pixel); p=PushShortPixel(MSBEndian,p,&pixel); image->colormap[i].green=ScaleShortToQuantum(pixel); p=PushShortPixel(MSBEndian,p,&pixel); image->colormap[i].blue=ScaleShortToQuantum(pixel); } break; } case 32: { unsigned int pixel; for (i=0; i < (ssize_t) image->colors; i++) { p=PushLongPixel(MSBEndian,p,&pixel); image->colormap[i].red=ScaleLongToQuantum(pixel); p=PushLongPixel(MSBEndian,p,&pixel); image->colormap[i].green=ScaleLongToQuantum(pixel); p=PushLongPixel(MSBEndian,p,&pixel); image->colormap[i].blue=ScaleLongToQuantum(pixel); } break; } } colormap=(unsigned char *) RelinquishMagickMemory(colormap); } } if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; if ((AcquireMagickResource(WidthResource,image->columns) == MagickFalse) || (AcquireMagickResource(HeightResource,image->rows) == MagickFalse)) ThrowReaderException(ImageError,"WidthOrHeightExceedsLimit"); /* Attach persistent pixel cache. */ status=PersistPixelCache(image,cache_filename,MagickTrue,&offset,exception); if (status == MagickFalse) ThrowReaderException(CacheError,"UnableToPersistPixelCache"); /* Proceed to next image. */ do { c=ReadBlobByte(image); } while ((isgraph(c) == MagickFalse) && (c != EOF)); if (c != EOF) { /* 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 (c != EOF); (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r M P C I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterMPCImage() adds properties for the Cache 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 RegisterMPCImage method is: % % size_t RegisterMPCImage(void) % */ ModuleExport size_t RegisterMPCImage(void) { MagickInfo *entry; entry=SetMagickInfo("CACHE"); entry->description=ConstantString("Magick Persistent Cache image format"); entry->module=ConstantString("MPC"); entry->stealth=MagickTrue; (void) RegisterMagickInfo(entry); entry=SetMagickInfo("MPC"); entry->decoder=(DecodeImageHandler *) ReadMPCImage; entry->encoder=(EncodeImageHandler *) WriteMPCImage; entry->magick=(IsImageFormatHandler *) IsMPC; entry->description=ConstantString("Magick Persistent Cache image format"); entry->seekable_stream=MagickTrue; entry->module=ConstantString("MPC"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r M P C I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterMPCImage() removes format registrations made by the % MPC module from the list of supported formats. % % The format of the UnregisterMPCImage method is: % % UnregisterMPCImage(void) % */ ModuleExport void UnregisterMPCImage(void) { (void) UnregisterMagickInfo("CACHE"); (void) UnregisterMagickInfo("MPC"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e M P C I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteMPCImage() writes an Magick Persistent Cache image to a file. % % The format of the WriteMPCImage method is: % % MagickBooleanType WriteMPCImage(const ImageInfo *image_info,Image *image) % % A description of each parameter follows: % % o image_info: the image info. % % o image: the image. % */ static MagickBooleanType WriteMPCImage(const ImageInfo *image_info,Image *image) { char buffer[MaxTextExtent], cache_filename[MaxTextExtent]; const char *property, *value; MagickBooleanType status; MagickOffsetType offset, scene; register ssize_t i; size_t depth, one; /* Open persistent cache. */ 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) CopyMagickString(cache_filename,image->filename,MaxTextExtent); AppendImageFormat("cache",cache_filename); scene=0; offset=0; one=1; do { /* Write persistent cache meta-information. */ depth=GetImageQuantumDepth(image,MagickTrue); if ((image->storage_class == PseudoClass) && (image->colors > (one << depth))) image->storage_class=DirectClass; (void) WriteBlobString(image,"id=MagickCache\n"); (void) FormatLocaleString(buffer,MaxTextExtent,"magick-signature=%u\n", GetMagickSignature((const StringInfo *) NULL)); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent, "class=%s colors=%.20g matte=%s\n",CommandOptionToMnemonic( MagickClassOptions,image->storage_class),(double) image->colors, CommandOptionToMnemonic(MagickBooleanOptions,(ssize_t) image->matte)); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent, "columns=%.20g rows=%.20g depth=%.20g\n",(double) image->columns, (double) image->rows,(double) image->depth); (void) WriteBlobString(image,buffer); if (image->type != UndefinedType) { (void) FormatLocaleString(buffer,MaxTextExtent,"type=%s\n", CommandOptionToMnemonic(MagickTypeOptions,image->type)); (void) WriteBlobString(image,buffer); } if (image->colorspace != UndefinedColorspace) { (void) FormatLocaleString(buffer,MaxTextExtent,"colorspace=%s\n", CommandOptionToMnemonic(MagickColorspaceOptions,image->colorspace)); (void) WriteBlobString(image,buffer); } if (image->intensity != UndefinedPixelIntensityMethod) { (void) FormatLocaleString(buffer,MaxTextExtent,"pixel-intensity=%s\n", CommandOptionToMnemonic(MagickPixelIntensityOptions, image->intensity)); (void) WriteBlobString(image,buffer); } if (image->endian != UndefinedEndian) { (void) FormatLocaleString(buffer,MaxTextExtent,"endian=%s\n", CommandOptionToMnemonic(MagickEndianOptions,image->endian)); (void) WriteBlobString(image,buffer); } if (image->compression != UndefinedCompression) { (void) FormatLocaleString(buffer,MaxTextExtent, "compression=%s quality=%.20g\n",CommandOptionToMnemonic( MagickCompressOptions,image->compression),(double) image->quality); (void) WriteBlobString(image,buffer); } if (image->units != UndefinedResolution) { (void) FormatLocaleString(buffer,MaxTextExtent,"units=%s\n", CommandOptionToMnemonic(MagickResolutionOptions,image->units)); (void) WriteBlobString(image,buffer); } if ((image->x_resolution != 0) || (image->y_resolution != 0)) { (void) FormatLocaleString(buffer,MaxTextExtent, "resolution=%gx%g\n",image->x_resolution,image->y_resolution); (void) WriteBlobString(image,buffer); } if ((image->page.width != 0) || (image->page.height != 0)) { (void) FormatLocaleString(buffer,MaxTextExtent, "page=%.20gx%.20g%+.20g%+.20g\n",(double) image->page.width,(double) image->page.height,(double) image->page.x,(double) image->page.y); (void) WriteBlobString(image,buffer); } else if ((image->page.x != 0) || (image->page.y != 0)) { (void) FormatLocaleString(buffer,MaxTextExtent,"page=%+ld%+ld\n", (long) image->page.x,(long) image->page.y); (void) WriteBlobString(image,buffer); } if ((image->tile_offset.x != 0) || (image->tile_offset.y != 0)) { (void) FormatLocaleString(buffer,MaxTextExtent,"tile-offset=%+ld%+ld\n", (long) image->tile_offset.x,(long) image->tile_offset.y); (void) WriteBlobString(image,buffer); } if ((GetNextImageInList(image) != (Image *) NULL) || (GetPreviousImageInList(image) != (Image *) NULL)) { if (image->scene == 0) (void) FormatLocaleString(buffer,MaxTextExtent, "iterations=%.20g delay=%.20g ticks-per-second=%.20g\n",(double) image->iterations,(double) image->delay,(double) image->ticks_per_second); else (void) FormatLocaleString(buffer,MaxTextExtent,"scene=%.20g " "iterations=%.20g delay=%.20g ticks-per-second=%.20g\n", (double) image->scene,(double) image->iterations,(double) image->delay,(double) image->ticks_per_second); (void) WriteBlobString(image,buffer); } else { if (image->scene != 0) { (void) FormatLocaleString(buffer,MaxTextExtent,"scene=%.20g\n", (double) image->scene); (void) WriteBlobString(image,buffer); } if (image->iterations != 0) { (void) FormatLocaleString(buffer,MaxTextExtent,"iterations=%.20g\n", (double) image->iterations); (void) WriteBlobString(image,buffer); } if (image->delay != 0) { (void) FormatLocaleString(buffer,MaxTextExtent,"delay=%.20g\n", (double) image->delay); (void) WriteBlobString(image,buffer); } if (image->ticks_per_second != UndefinedTicksPerSecond) { (void) FormatLocaleString(buffer,MaxTextExtent, "ticks-per-second=%.20g\n",(double) image->ticks_per_second); (void) WriteBlobString(image,buffer); } } if (image->gravity != UndefinedGravity) { (void) FormatLocaleString(buffer,MaxTextExtent,"gravity=%s\n", CommandOptionToMnemonic(MagickGravityOptions,image->gravity)); (void) WriteBlobString(image,buffer); } if (image->dispose != UndefinedDispose) { (void) FormatLocaleString(buffer,MaxTextExtent,"dispose=%s\n", CommandOptionToMnemonic(MagickDisposeOptions,image->dispose)); (void) WriteBlobString(image,buffer); } if (image->rendering_intent != UndefinedIntent) { (void) FormatLocaleString(buffer,MaxTextExtent, "rendering-intent=%s\n",CommandOptionToMnemonic(MagickIntentOptions, image->rendering_intent)); (void) WriteBlobString(image,buffer); } if (image->gamma != 0.0) { (void) FormatLocaleString(buffer,MaxTextExtent,"gamma=%g\n", image->gamma); (void) WriteBlobString(image,buffer); } if (image->chromaticity.white_point.x != 0.0) { /* Note chomaticity points. */ (void) FormatLocaleString(buffer,MaxTextExtent,"red-primary=" "%g,%g green-primary=%g,%g blue-primary=%g,%g\n", image->chromaticity.red_primary.x,image->chromaticity.red_primary.y, image->chromaticity.green_primary.x, image->chromaticity.green_primary.y, image->chromaticity.blue_primary.x, image->chromaticity.blue_primary.y); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent, "white-point=%g,%g\n",image->chromaticity.white_point.x, image->chromaticity.white_point.y); (void) WriteBlobString(image,buffer); } if (image->orientation != UndefinedOrientation) { (void) FormatLocaleString(buffer,MaxTextExtent, "orientation=%s\n",CommandOptionToMnemonic(MagickOrientationOptions, image->orientation)); (void) WriteBlobString(image,buffer); } if (image->profiles != (void *) NULL) { const char *name; const StringInfo *profile; /* Generic profile. */ ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (const char *) NULL; ) { profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { (void) FormatLocaleString(buffer,MaxTextExtent, "profile:%s=%.20g\n",name,(double) GetStringInfoLength(profile)); (void) WriteBlobString(image,buffer); } name=GetNextImageProfile(image); } } if (image->montage != (char *) NULL) { (void) FormatLocaleString(buffer,MaxTextExtent,"montage=%s\n", image->montage); (void) WriteBlobString(image,buffer); } ResetImagePropertyIterator(image); property=GetNextImageProperty(image); while (property != (const char *) NULL) { (void) FormatLocaleString(buffer,MaxTextExtent,"%s=",property); (void) WriteBlobString(image,buffer); value=GetImageProperty(image,property); if (value != (const char *) NULL) { size_t length; length=strlen(value); for (i=0; i < (ssize_t) length; i++) if (isspace((int) ((unsigned char) value[i])) != 0) break; if ((i == (ssize_t) length) && (i != 0)) (void) WriteBlob(image,length,(const unsigned char *) value); else { (void) WriteBlobByte(image,'{'); if (strchr(value,'}') == (char *) NULL) (void) WriteBlob(image,length,(const unsigned char *) value); else for (i=0; i < (ssize_t) length; i++) { if (value[i] == (int) '}') (void) WriteBlobByte(image,'\\'); (void) WriteBlobByte(image,value[i]); } (void) WriteBlobByte(image,'}'); } } (void) WriteBlobByte(image,'\n'); property=GetNextImageProperty(image); } (void) WriteBlobString(image,"\f\n:\032"); if (image->montage != (char *) NULL) { /* Write montage tile directory. */ if (image->directory != (char *) NULL) (void) WriteBlobString(image,image->directory); (void) WriteBlobByte(image,'\0'); } if (image->profiles != 0) { const char *name; const StringInfo *profile; /* Write image profiles. */ ResetImageProfileIterator(image); name=GetNextImageProfile(image); while (name != (const char *) NULL) { profile=GetImageProfile(image,name); (void) WriteBlob(image,GetStringInfoLength(profile), GetStringInfoDatum(profile)); name=GetNextImageProfile(image); } } if (image->storage_class == PseudoClass) { size_t packet_size; unsigned char *colormap, *q; /* Allocate colormap. */ packet_size=(size_t) (3UL*depth/8UL); colormap=(unsigned char *) AcquireQuantumMemory(image->colors, packet_size*sizeof(*colormap)); if (colormap == (unsigned char *) NULL) return(MagickFalse); /* Write colormap to file. */ q=colormap; for (i=0; i < (ssize_t) image->colors; i++) { switch (depth) { default: ThrowWriterException(CorruptImageError,"ImageDepthNotSupported"); case 32: { unsigned int pixel; pixel=ScaleQuantumToLong(image->colormap[i].red); q=PopLongPixel(MSBEndian,pixel,q); pixel=ScaleQuantumToLong(image->colormap[i].green); q=PopLongPixel(MSBEndian,pixel,q); pixel=ScaleQuantumToLong(image->colormap[i].blue); q=PopLongPixel(MSBEndian,pixel,q); break; } case 16: { unsigned short pixel; pixel=ScaleQuantumToShort(image->colormap[i].red); q=PopShortPixel(MSBEndian,pixel,q); pixel=ScaleQuantumToShort(image->colormap[i].green); q=PopShortPixel(MSBEndian,pixel,q); pixel=ScaleQuantumToShort(image->colormap[i].blue); q=PopShortPixel(MSBEndian,pixel,q); break; } case 8: { unsigned char pixel; pixel=(unsigned char) ScaleQuantumToChar(image->colormap[i].red); q=PopCharPixel(pixel,q); pixel=(unsigned char) ScaleQuantumToChar( image->colormap[i].green); q=PopCharPixel(pixel,q); pixel=(unsigned char) ScaleQuantumToChar(image->colormap[i].blue); q=PopCharPixel(pixel,q); break; } } } (void) WriteBlob(image,packet_size*image->colors,colormap); colormap=(unsigned char *) RelinquishMagickMemory(colormap); } /* Initialize persistent pixel cache. */ status=PersistPixelCache(image,cache_filename,MagickFalse,&offset, &image->exception); if (status == MagickFalse) ThrowWriterException(CacheError,"UnableToPersistPixelCache"); if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); if (image->progress_monitor != (MagickProgressMonitor) NULL) { status=image->progress_monitor(SaveImagesTag,scene, GetImageListLength(image),image->client_data); if (status == MagickFalse) break; } scene++; } while (image_info->adjoin != MagickFalse); (void) CloseBlob(image); return(status); }
./CrossVul/dataset_final_sorted/CWE-20/c/good_2576_0
crossvul-cpp_data_bad_332_0
// SPDX-License-Identifier: GPL-2.0 /* * Driver for Meywa-Denki & KAYAC YUREX * * Copyright (C) 2010 Tomoki Sekiyama (tomoki.sekiyama@gmail.com) */ #include <linux/kernel.h> #include <linux/errno.h> #include <linux/slab.h> #include <linux/module.h> #include <linux/kref.h> #include <linux/mutex.h> #include <linux/uaccess.h> #include <linux/usb.h> #include <linux/hid.h> #define DRIVER_AUTHOR "Tomoki Sekiyama" #define DRIVER_DESC "Driver for Meywa-Denki & KAYAC YUREX" #define YUREX_VENDOR_ID 0x0c45 #define YUREX_PRODUCT_ID 0x1010 #define CMD_ACK '!' #define CMD_ANIMATE 'A' #define CMD_COUNT 'C' #define CMD_LED 'L' #define CMD_READ 'R' #define CMD_SET 'S' #define CMD_VERSION 'V' #define CMD_EOF 0x0d #define CMD_PADDING 0xff #define YUREX_BUF_SIZE 8 #define YUREX_WRITE_TIMEOUT (HZ*2) /* table of devices that work with this driver */ static struct usb_device_id yurex_table[] = { { USB_DEVICE(YUREX_VENDOR_ID, YUREX_PRODUCT_ID) }, { } /* Terminating entry */ }; MODULE_DEVICE_TABLE(usb, yurex_table); #ifdef CONFIG_USB_DYNAMIC_MINORS #define YUREX_MINOR_BASE 0 #else #define YUREX_MINOR_BASE 192 #endif /* Structure to hold all of our device specific stuff */ struct usb_yurex { struct usb_device *udev; struct usb_interface *interface; __u8 int_in_endpointAddr; struct urb *urb; /* URB for interrupt in */ unsigned char *int_buffer; /* buffer for intterupt in */ struct urb *cntl_urb; /* URB for control msg */ struct usb_ctrlrequest *cntl_req; /* req for control msg */ unsigned char *cntl_buffer; /* buffer for control msg */ struct kref kref; struct mutex io_mutex; struct fasync_struct *async_queue; wait_queue_head_t waitq; spinlock_t lock; __s64 bbu; /* BBU from device */ }; #define to_yurex_dev(d) container_of(d, struct usb_yurex, kref) static struct usb_driver yurex_driver; static const struct file_operations yurex_fops; static void yurex_control_callback(struct urb *urb) { struct usb_yurex *dev = urb->context; int status = urb->status; if (status) { dev_err(&urb->dev->dev, "%s - control failed: %d\n", __func__, status); wake_up_interruptible(&dev->waitq); return; } /* on success, sender woken up by CMD_ACK int in, or timeout */ } static void yurex_delete(struct kref *kref) { struct usb_yurex *dev = to_yurex_dev(kref); dev_dbg(&dev->interface->dev, "%s\n", __func__); usb_put_dev(dev->udev); if (dev->cntl_urb) { usb_kill_urb(dev->cntl_urb); kfree(dev->cntl_req); if (dev->cntl_buffer) usb_free_coherent(dev->udev, YUREX_BUF_SIZE, dev->cntl_buffer, dev->cntl_urb->transfer_dma); usb_free_urb(dev->cntl_urb); } if (dev->urb) { usb_kill_urb(dev->urb); if (dev->int_buffer) usb_free_coherent(dev->udev, YUREX_BUF_SIZE, dev->int_buffer, dev->urb->transfer_dma); usb_free_urb(dev->urb); } kfree(dev); } /* * usb class driver info in order to get a minor number from the usb core, * and to have the device registered with the driver core */ static struct usb_class_driver yurex_class = { .name = "yurex%d", .fops = &yurex_fops, .minor_base = YUREX_MINOR_BASE, }; static void yurex_interrupt(struct urb *urb) { struct usb_yurex *dev = urb->context; unsigned char *buf = dev->int_buffer; int status = urb->status; unsigned long flags; int retval, i; switch (status) { case 0: /*success*/ break; case -EOVERFLOW: dev_err(&dev->interface->dev, "%s - overflow with length %d, actual length is %d\n", __func__, YUREX_BUF_SIZE, dev->urb->actual_length); case -ECONNRESET: case -ENOENT: case -ESHUTDOWN: case -EILSEQ: /* The device is terminated, clean up */ return; default: dev_err(&dev->interface->dev, "%s - unknown status received: %d\n", __func__, status); goto exit; } /* handle received message */ switch (buf[0]) { case CMD_COUNT: case CMD_READ: if (buf[6] == CMD_EOF) { spin_lock_irqsave(&dev->lock, flags); dev->bbu = 0; for (i = 1; i < 6; i++) { dev->bbu += buf[i]; if (i != 5) dev->bbu <<= 8; } dev_dbg(&dev->interface->dev, "%s count: %lld\n", __func__, dev->bbu); spin_unlock_irqrestore(&dev->lock, flags); kill_fasync(&dev->async_queue, SIGIO, POLL_IN); } else dev_dbg(&dev->interface->dev, "data format error - no EOF\n"); break; case CMD_ACK: dev_dbg(&dev->interface->dev, "%s ack: %c\n", __func__, buf[1]); wake_up_interruptible(&dev->waitq); break; } exit: retval = usb_submit_urb(dev->urb, GFP_ATOMIC); if (retval) { dev_err(&dev->interface->dev, "%s - usb_submit_urb failed: %d\n", __func__, retval); } } static int yurex_probe(struct usb_interface *interface, const struct usb_device_id *id) { struct usb_yurex *dev; struct usb_host_interface *iface_desc; struct usb_endpoint_descriptor *endpoint; int retval = -ENOMEM; DEFINE_WAIT(wait); int res; /* allocate memory for our device state and initialize it */ dev = kzalloc(sizeof(*dev), GFP_KERNEL); if (!dev) goto error; kref_init(&dev->kref); mutex_init(&dev->io_mutex); spin_lock_init(&dev->lock); init_waitqueue_head(&dev->waitq); dev->udev = usb_get_dev(interface_to_usbdev(interface)); dev->interface = interface; /* set up the endpoint information */ iface_desc = interface->cur_altsetting; res = usb_find_int_in_endpoint(iface_desc, &endpoint); if (res) { dev_err(&interface->dev, "Could not find endpoints\n"); retval = res; goto error; } dev->int_in_endpointAddr = endpoint->bEndpointAddress; /* allocate control URB */ dev->cntl_urb = usb_alloc_urb(0, GFP_KERNEL); if (!dev->cntl_urb) goto error; /* allocate buffer for control req */ dev->cntl_req = kmalloc(YUREX_BUF_SIZE, GFP_KERNEL); if (!dev->cntl_req) goto error; /* allocate buffer for control msg */ dev->cntl_buffer = usb_alloc_coherent(dev->udev, YUREX_BUF_SIZE, GFP_KERNEL, &dev->cntl_urb->transfer_dma); if (!dev->cntl_buffer) { dev_err(&interface->dev, "Could not allocate cntl_buffer\n"); goto error; } /* configure control URB */ dev->cntl_req->bRequestType = USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE; dev->cntl_req->bRequest = HID_REQ_SET_REPORT; dev->cntl_req->wValue = cpu_to_le16((HID_OUTPUT_REPORT + 1) << 8); dev->cntl_req->wIndex = cpu_to_le16(iface_desc->desc.bInterfaceNumber); dev->cntl_req->wLength = cpu_to_le16(YUREX_BUF_SIZE); usb_fill_control_urb(dev->cntl_urb, dev->udev, usb_sndctrlpipe(dev->udev, 0), (void *)dev->cntl_req, dev->cntl_buffer, YUREX_BUF_SIZE, yurex_control_callback, dev); dev->cntl_urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP; /* allocate interrupt URB */ dev->urb = usb_alloc_urb(0, GFP_KERNEL); if (!dev->urb) goto error; /* allocate buffer for interrupt in */ dev->int_buffer = usb_alloc_coherent(dev->udev, YUREX_BUF_SIZE, GFP_KERNEL, &dev->urb->transfer_dma); if (!dev->int_buffer) { dev_err(&interface->dev, "Could not allocate int_buffer\n"); goto error; } /* configure interrupt URB */ usb_fill_int_urb(dev->urb, dev->udev, usb_rcvintpipe(dev->udev, dev->int_in_endpointAddr), dev->int_buffer, YUREX_BUF_SIZE, yurex_interrupt, dev, 1); dev->urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP; if (usb_submit_urb(dev->urb, GFP_KERNEL)) { retval = -EIO; dev_err(&interface->dev, "Could not submitting URB\n"); goto error; } /* save our data pointer in this interface device */ usb_set_intfdata(interface, dev); dev->bbu = -1; /* we can register the device now, as it is ready */ retval = usb_register_dev(interface, &yurex_class); if (retval) { dev_err(&interface->dev, "Not able to get a minor for this device.\n"); usb_set_intfdata(interface, NULL); goto error; } dev_info(&interface->dev, "USB YUREX device now attached to Yurex #%d\n", interface->minor); return 0; error: if (dev) /* this frees allocated memory */ kref_put(&dev->kref, yurex_delete); return retval; } static void yurex_disconnect(struct usb_interface *interface) { struct usb_yurex *dev; int minor = interface->minor; dev = usb_get_intfdata(interface); usb_set_intfdata(interface, NULL); /* give back our minor */ usb_deregister_dev(interface, &yurex_class); /* prevent more I/O from starting */ mutex_lock(&dev->io_mutex); dev->interface = NULL; mutex_unlock(&dev->io_mutex); /* wakeup waiters */ kill_fasync(&dev->async_queue, SIGIO, POLL_IN); wake_up_interruptible(&dev->waitq); /* decrement our usage count */ kref_put(&dev->kref, yurex_delete); dev_info(&interface->dev, "USB YUREX #%d now disconnected\n", minor); } static struct usb_driver yurex_driver = { .name = "yurex", .probe = yurex_probe, .disconnect = yurex_disconnect, .id_table = yurex_table, }; static int yurex_fasync(int fd, struct file *file, int on) { struct usb_yurex *dev; dev = file->private_data; return fasync_helper(fd, file, on, &dev->async_queue); } static int yurex_open(struct inode *inode, struct file *file) { struct usb_yurex *dev; struct usb_interface *interface; int subminor; int retval = 0; subminor = iminor(inode); interface = usb_find_interface(&yurex_driver, subminor); if (!interface) { printk(KERN_ERR "%s - error, can't find device for minor %d", __func__, subminor); retval = -ENODEV; goto exit; } dev = usb_get_intfdata(interface); if (!dev) { retval = -ENODEV; goto exit; } /* increment our usage count for the device */ kref_get(&dev->kref); /* save our object in the file's private structure */ mutex_lock(&dev->io_mutex); file->private_data = dev; mutex_unlock(&dev->io_mutex); exit: return retval; } static int yurex_release(struct inode *inode, struct file *file) { struct usb_yurex *dev; dev = file->private_data; if (dev == NULL) return -ENODEV; /* decrement the count on our device */ kref_put(&dev->kref, yurex_delete); return 0; } static ssize_t yurex_read(struct file *file, char __user *buffer, size_t count, loff_t *ppos) { struct usb_yurex *dev; int retval = 0; int bytes_read = 0; char in_buffer[20]; unsigned long flags; dev = file->private_data; mutex_lock(&dev->io_mutex); if (!dev->interface) { /* already disconnected */ retval = -ENODEV; goto exit; } spin_lock_irqsave(&dev->lock, flags); bytes_read = snprintf(in_buffer, 20, "%lld\n", dev->bbu); spin_unlock_irqrestore(&dev->lock, flags); if (*ppos < bytes_read) { if (copy_to_user(buffer, in_buffer + *ppos, bytes_read - *ppos)) retval = -EFAULT; else { retval = bytes_read - *ppos; *ppos += bytes_read; } } exit: mutex_unlock(&dev->io_mutex); return retval; } static ssize_t yurex_write(struct file *file, const char __user *user_buffer, size_t count, loff_t *ppos) { struct usb_yurex *dev; int i, set = 0, retval = 0; char buffer[16]; char *data = buffer; unsigned long long c, c2 = 0; signed long timeout = 0; DEFINE_WAIT(wait); count = min(sizeof(buffer), count); dev = file->private_data; /* verify that we actually have some data to write */ if (count == 0) goto error; mutex_lock(&dev->io_mutex); if (!dev->interface) { /* already disconnected */ mutex_unlock(&dev->io_mutex); retval = -ENODEV; goto error; } if (copy_from_user(buffer, user_buffer, count)) { mutex_unlock(&dev->io_mutex); retval = -EFAULT; goto error; } memset(dev->cntl_buffer, CMD_PADDING, YUREX_BUF_SIZE); switch (buffer[0]) { case CMD_ANIMATE: case CMD_LED: dev->cntl_buffer[0] = buffer[0]; dev->cntl_buffer[1] = buffer[1]; dev->cntl_buffer[2] = CMD_EOF; break; case CMD_READ: case CMD_VERSION: dev->cntl_buffer[0] = buffer[0]; dev->cntl_buffer[1] = 0x00; dev->cntl_buffer[2] = CMD_EOF; break; case CMD_SET: data++; /* FALL THROUGH */ case '0' ... '9': set = 1; c = c2 = simple_strtoull(data, NULL, 0); dev->cntl_buffer[0] = CMD_SET; for (i = 1; i < 6; i++) { dev->cntl_buffer[i] = (c>>32) & 0xff; c <<= 8; } buffer[6] = CMD_EOF; break; default: mutex_unlock(&dev->io_mutex); return -EINVAL; } /* send the data as the control msg */ prepare_to_wait(&dev->waitq, &wait, TASK_INTERRUPTIBLE); dev_dbg(&dev->interface->dev, "%s - submit %c\n", __func__, dev->cntl_buffer[0]); retval = usb_submit_urb(dev->cntl_urb, GFP_KERNEL); if (retval >= 0) timeout = schedule_timeout(YUREX_WRITE_TIMEOUT); finish_wait(&dev->waitq, &wait); mutex_unlock(&dev->io_mutex); if (retval < 0) { dev_err(&dev->interface->dev, "%s - failed to send bulk msg, error %d\n", __func__, retval); goto error; } if (set && timeout) dev->bbu = c2; return timeout ? count : -EIO; error: return retval; } static const struct file_operations yurex_fops = { .owner = THIS_MODULE, .read = yurex_read, .write = yurex_write, .open = yurex_open, .release = yurex_release, .fasync = yurex_fasync, .llseek = default_llseek, }; module_usb_driver(yurex_driver); MODULE_LICENSE("GPL");
./CrossVul/dataset_final_sorted/CWE-20/c/bad_332_0
crossvul-cpp_data_good_2891_4
/* Key garbage collector * * Copyright (C) 2009-2011 Red Hat, Inc. All Rights Reserved. * Written by David Howells (dhowells@redhat.com) * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public Licence * as published by the Free Software Foundation; either version * 2 of the Licence, or (at your option) any later version. */ #include <linux/module.h> #include <linux/slab.h> #include <linux/security.h> #include <keys/keyring-type.h> #include "internal.h" /* * Delay between key revocation/expiry in seconds */ unsigned key_gc_delay = 5 * 60; /* * Reaper for unused keys. */ static void key_garbage_collector(struct work_struct *work); DECLARE_WORK(key_gc_work, key_garbage_collector); /* * Reaper for links from keyrings to dead keys. */ static void key_gc_timer_func(unsigned long); static DEFINE_TIMER(key_gc_timer, key_gc_timer_func, 0, 0); static time_t key_gc_next_run = LONG_MAX; static struct key_type *key_gc_dead_keytype; static unsigned long key_gc_flags; #define KEY_GC_KEY_EXPIRED 0 /* A key expired and needs unlinking */ #define KEY_GC_REAP_KEYTYPE 1 /* A keytype is being unregistered */ #define KEY_GC_REAPING_KEYTYPE 2 /* Cleared when keytype reaped */ /* * Any key whose type gets unregistered will be re-typed to this if it can't be * immediately unlinked. */ struct key_type key_type_dead = { .name = ".dead", }; /* * Schedule a garbage collection run. * - time precision isn't particularly important */ void key_schedule_gc(time_t gc_at) { unsigned long expires; time_t now = current_kernel_time().tv_sec; kenter("%ld", gc_at - now); if (gc_at <= now || test_bit(KEY_GC_REAP_KEYTYPE, &key_gc_flags)) { kdebug("IMMEDIATE"); schedule_work(&key_gc_work); } else if (gc_at < key_gc_next_run) { kdebug("DEFERRED"); key_gc_next_run = gc_at; expires = jiffies + (gc_at - now) * HZ; mod_timer(&key_gc_timer, expires); } } /* * Schedule a dead links collection run. */ void key_schedule_gc_links(void) { set_bit(KEY_GC_KEY_EXPIRED, &key_gc_flags); schedule_work(&key_gc_work); } /* * Some key's cleanup time was met after it expired, so we need to get the * reaper to go through a cycle finding expired keys. */ static void key_gc_timer_func(unsigned long data) { kenter(""); key_gc_next_run = LONG_MAX; key_schedule_gc_links(); } /* * Reap keys of dead type. * * We use three flags to make sure we see three complete cycles of the garbage * collector: the first to mark keys of that type as being dead, the second to * collect dead links and the third to clean up the dead keys. We have to be * careful as there may already be a cycle in progress. * * The caller must be holding key_types_sem. */ void key_gc_keytype(struct key_type *ktype) { kenter("%s", ktype->name); key_gc_dead_keytype = ktype; set_bit(KEY_GC_REAPING_KEYTYPE, &key_gc_flags); smp_mb(); set_bit(KEY_GC_REAP_KEYTYPE, &key_gc_flags); kdebug("schedule"); schedule_work(&key_gc_work); kdebug("sleep"); wait_on_bit(&key_gc_flags, KEY_GC_REAPING_KEYTYPE, TASK_UNINTERRUPTIBLE); key_gc_dead_keytype = NULL; kleave(""); } /* * Garbage collect a list of unreferenced, detached keys */ static noinline void key_gc_unused_keys(struct list_head *keys) { while (!list_empty(keys)) { struct key *key = list_entry(keys->next, struct key, graveyard_link); short state = key->state; list_del(&key->graveyard_link); kdebug("- %u", key->serial); key_check(key); /* Throw away the key data if the key is instantiated */ if (state == KEY_IS_POSITIVE && key->type->destroy) key->type->destroy(key); security_key_free(key); /* deal with the user's key tracking and quota */ if (test_bit(KEY_FLAG_IN_QUOTA, &key->flags)) { spin_lock(&key->user->lock); key->user->qnkeys--; key->user->qnbytes -= key->quotalen; spin_unlock(&key->user->lock); } atomic_dec(&key->user->nkeys); if (state != KEY_IS_UNINSTANTIATED) atomic_dec(&key->user->nikeys); key_user_put(key->user); kfree(key->description); memzero_explicit(key, sizeof(*key)); kmem_cache_free(key_jar, key); } } /* * Garbage collector for unused keys. * * This is done in process context so that we don't have to disable interrupts * all over the place. key_put() schedules this rather than trying to do the * cleanup itself, which means key_put() doesn't have to sleep. */ static void key_garbage_collector(struct work_struct *work) { static LIST_HEAD(graveyard); static u8 gc_state; /* Internal persistent state */ #define KEY_GC_REAP_AGAIN 0x01 /* - Need another cycle */ #define KEY_GC_REAPING_LINKS 0x02 /* - We need to reap links */ #define KEY_GC_SET_TIMER 0x04 /* - We need to restart the timer */ #define KEY_GC_REAPING_DEAD_1 0x10 /* - We need to mark dead keys */ #define KEY_GC_REAPING_DEAD_2 0x20 /* - We need to reap dead key links */ #define KEY_GC_REAPING_DEAD_3 0x40 /* - We need to reap dead keys */ #define KEY_GC_FOUND_DEAD_KEY 0x80 /* - We found at least one dead key */ struct rb_node *cursor; struct key *key; time_t new_timer, limit; kenter("[%lx,%x]", key_gc_flags, gc_state); limit = current_kernel_time().tv_sec; if (limit > key_gc_delay) limit -= key_gc_delay; else limit = key_gc_delay; /* Work out what we're going to be doing in this pass */ gc_state &= KEY_GC_REAPING_DEAD_1 | KEY_GC_REAPING_DEAD_2; gc_state <<= 1; if (test_and_clear_bit(KEY_GC_KEY_EXPIRED, &key_gc_flags)) gc_state |= KEY_GC_REAPING_LINKS | KEY_GC_SET_TIMER; if (test_and_clear_bit(KEY_GC_REAP_KEYTYPE, &key_gc_flags)) gc_state |= KEY_GC_REAPING_DEAD_1; kdebug("new pass %x", gc_state); new_timer = LONG_MAX; /* As only this function is permitted to remove things from the key * serial tree, if cursor is non-NULL then it will always point to a * valid node in the tree - even if lock got dropped. */ spin_lock(&key_serial_lock); cursor = rb_first(&key_serial_tree); continue_scanning: while (cursor) { key = rb_entry(cursor, struct key, serial_node); cursor = rb_next(cursor); if (refcount_read(&key->usage) == 0) goto found_unreferenced_key; if (unlikely(gc_state & KEY_GC_REAPING_DEAD_1)) { if (key->type == key_gc_dead_keytype) { gc_state |= KEY_GC_FOUND_DEAD_KEY; set_bit(KEY_FLAG_DEAD, &key->flags); key->perm = 0; goto skip_dead_key; } else if (key->type == &key_type_keyring && key->restrict_link) { goto found_restricted_keyring; } } if (gc_state & KEY_GC_SET_TIMER) { if (key->expiry > limit && key->expiry < new_timer) { kdebug("will expire %x in %ld", key_serial(key), key->expiry - limit); new_timer = key->expiry; } } if (unlikely(gc_state & KEY_GC_REAPING_DEAD_2)) if (key->type == key_gc_dead_keytype) gc_state |= KEY_GC_FOUND_DEAD_KEY; if ((gc_state & KEY_GC_REAPING_LINKS) || unlikely(gc_state & KEY_GC_REAPING_DEAD_2)) { if (key->type == &key_type_keyring) goto found_keyring; } if (unlikely(gc_state & KEY_GC_REAPING_DEAD_3)) if (key->type == key_gc_dead_keytype) goto destroy_dead_key; skip_dead_key: if (spin_is_contended(&key_serial_lock) || need_resched()) goto contended; } contended: spin_unlock(&key_serial_lock); maybe_resched: if (cursor) { cond_resched(); spin_lock(&key_serial_lock); goto continue_scanning; } /* We've completed the pass. Set the timer if we need to and queue a * new cycle if necessary. We keep executing cycles until we find one * where we didn't reap any keys. */ kdebug("pass complete"); if (gc_state & KEY_GC_SET_TIMER && new_timer != (time_t)LONG_MAX) { new_timer += key_gc_delay; key_schedule_gc(new_timer); } if (unlikely(gc_state & KEY_GC_REAPING_DEAD_2) || !list_empty(&graveyard)) { /* Make sure that all pending keyring payload destructions are * fulfilled and that people aren't now looking at dead or * dying keys that they don't have a reference upon or a link * to. */ kdebug("gc sync"); synchronize_rcu(); } if (!list_empty(&graveyard)) { kdebug("gc keys"); key_gc_unused_keys(&graveyard); } if (unlikely(gc_state & (KEY_GC_REAPING_DEAD_1 | KEY_GC_REAPING_DEAD_2))) { if (!(gc_state & KEY_GC_FOUND_DEAD_KEY)) { /* No remaining dead keys: short circuit the remaining * keytype reap cycles. */ kdebug("dead short"); gc_state &= ~(KEY_GC_REAPING_DEAD_1 | KEY_GC_REAPING_DEAD_2); gc_state |= KEY_GC_REAPING_DEAD_3; } else { gc_state |= KEY_GC_REAP_AGAIN; } } if (unlikely(gc_state & KEY_GC_REAPING_DEAD_3)) { kdebug("dead wake"); smp_mb(); clear_bit(KEY_GC_REAPING_KEYTYPE, &key_gc_flags); wake_up_bit(&key_gc_flags, KEY_GC_REAPING_KEYTYPE); } if (gc_state & KEY_GC_REAP_AGAIN) schedule_work(&key_gc_work); kleave(" [end %x]", gc_state); return; /* We found an unreferenced key - once we've removed it from the tree, * we can safely drop the lock. */ found_unreferenced_key: kdebug("unrefd key %d", key->serial); rb_erase(&key->serial_node, &key_serial_tree); spin_unlock(&key_serial_lock); list_add_tail(&key->graveyard_link, &graveyard); gc_state |= KEY_GC_REAP_AGAIN; goto maybe_resched; /* We found a restricted keyring and need to update the restriction if * it is associated with the dead key type. */ found_restricted_keyring: spin_unlock(&key_serial_lock); keyring_restriction_gc(key, key_gc_dead_keytype); goto maybe_resched; /* We found a keyring and we need to check the payload for links to * dead or expired keys. We don't flag another reap immediately as we * have to wait for the old payload to be destroyed by RCU before we * can reap the keys to which it refers. */ found_keyring: spin_unlock(&key_serial_lock); keyring_gc(key, limit); goto maybe_resched; /* We found a dead key that is still referenced. Reset its type and * destroy its payload with its semaphore held. */ destroy_dead_key: spin_unlock(&key_serial_lock); kdebug("destroy key %d", key->serial); down_write(&key->sem); key->type = &key_type_dead; if (key_gc_dead_keytype->destroy) key_gc_dead_keytype->destroy(key); memset(&key->payload, KEY_DESTROY, sizeof(key->payload)); up_write(&key->sem); goto maybe_resched; }
./CrossVul/dataset_final_sorted/CWE-20/c/good_2891_4
crossvul-cpp_data_good_4900_2
/* vi:set ts=8 sts=4 sw=4 noet: * * VIM - Vi IMproved by Bram Moolenaar * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. * See README.txt for an overview of the Vim source code. */ #include "vim.h" #ifdef AMIGA # include <time.h> /* for time() */ #endif /* * Vim originated from Stevie version 3.6 (Fish disk 217) by GRWalter (Fred) * It has been changed beyond recognition since then. * * Differences between version 7.4 and 8.x can be found with ":help version8". * Differences between version 6.4 and 7.x can be found with ":help version7". * Differences between version 5.8 and 6.x can be found with ":help version6". * Differences between version 4.x and 5.x can be found with ":help version5". * Differences between version 3.0 and 4.x can be found with ":help version4". * All the remarks about older versions have been removed, they are not very * interesting. */ #include "version.h" char *Version = VIM_VERSION_SHORT; static char *mediumVersion = VIM_VERSION_MEDIUM; #if defined(HAVE_DATE_TIME) || defined(PROTO) # if (defined(VMS) && defined(VAXC)) || defined(PROTO) char longVersion[sizeof(VIM_VERSION_LONG_DATE) + sizeof(__DATE__) + sizeof(__TIME__) + 3]; void make_version(void) { /* * Construct the long version string. Necessary because * VAX C can't catenate strings in the preprocessor. */ strcpy(longVersion, VIM_VERSION_LONG_DATE); strcat(longVersion, __DATE__); strcat(longVersion, " "); strcat(longVersion, __TIME__); strcat(longVersion, ")"); } # else char *longVersion = VIM_VERSION_LONG_DATE __DATE__ " " __TIME__ ")"; # endif #else char *longVersion = VIM_VERSION_LONG; #endif static void list_features(void); static void version_msg(char *s); static char *(features[]) = { #ifdef HAVE_ACL "+acl", #else "-acl", #endif #ifdef AMIGA /* only for Amiga systems */ # ifdef FEAT_ARP "+ARP", # else "-ARP", # endif #endif #ifdef FEAT_ARABIC "+arabic", #else "-arabic", #endif #ifdef FEAT_AUTOCMD "+autocmd", #else "-autocmd", #endif #ifdef FEAT_BEVAL "+balloon_eval", #else "-balloon_eval", #endif #ifdef FEAT_BROWSE "+browse", #else "-browse", #endif #ifdef NO_BUILTIN_TCAPS "-builtin_terms", #endif #ifdef SOME_BUILTIN_TCAPS "+builtin_terms", #endif #ifdef ALL_BUILTIN_TCAPS "++builtin_terms", #endif #ifdef FEAT_BYTEOFF "+byte_offset", #else "-byte_offset", #endif #ifdef FEAT_JOB_CHANNEL "+channel", #else "-channel", #endif #ifdef FEAT_CINDENT "+cindent", #else "-cindent", #endif #ifdef FEAT_CLIENTSERVER "+clientserver", #else "-clientserver", #endif #ifdef FEAT_CLIPBOARD "+clipboard", #else "-clipboard", #endif #ifdef FEAT_CMDL_COMPL "+cmdline_compl", #else "-cmdline_compl", #endif #ifdef FEAT_CMDHIST "+cmdline_hist", #else "-cmdline_hist", #endif #ifdef FEAT_CMDL_INFO "+cmdline_info", #else "-cmdline_info", #endif #ifdef FEAT_COMMENTS "+comments", #else "-comments", #endif #ifdef FEAT_CONCEAL "+conceal", #else "-conceal", #endif #ifdef FEAT_CRYPT "+cryptv", #else "-cryptv", #endif #ifdef FEAT_CSCOPE "+cscope", #else "-cscope", #endif #ifdef FEAT_CURSORBIND "+cursorbind", #else "-cursorbind", #endif #ifdef CURSOR_SHAPE "+cursorshape", #else "-cursorshape", #endif #if defined(FEAT_CON_DIALOG) && defined(FEAT_GUI_DIALOG) "+dialog_con_gui", #else # if defined(FEAT_CON_DIALOG) "+dialog_con", # else # if defined(FEAT_GUI_DIALOG) "+dialog_gui", # else "-dialog", # endif # endif #endif #ifdef FEAT_DIFF "+diff", #else "-diff", #endif #ifdef FEAT_DIGRAPHS "+digraphs", #else "-digraphs", #endif #ifdef FEAT_GUI_W32 # ifdef FEAT_DIRECTX "+directx", # else "-directx", # endif #endif #ifdef FEAT_DND "+dnd", #else "-dnd", #endif #ifdef EBCDIC "+ebcdic", #else "-ebcdic", #endif #ifdef FEAT_EMACS_TAGS "+emacs_tags", #else "-emacs_tags", #endif #ifdef FEAT_EVAL "+eval", #else "-eval", #endif "+ex_extra", #ifdef FEAT_SEARCH_EXTRA "+extra_search", #else "-extra_search", #endif #ifdef FEAT_FKMAP "+farsi", #else "-farsi", #endif #ifdef FEAT_SEARCHPATH "+file_in_path", #else "-file_in_path", #endif #ifdef FEAT_FIND_ID "+find_in_path", #else "-find_in_path", #endif #ifdef FEAT_FLOAT "+float", #else "-float", #endif #ifdef FEAT_FOLDING "+folding", #else "-folding", #endif #ifdef FEAT_FOOTER "+footer", #else "-footer", #endif /* only interesting on Unix systems */ #if !defined(USE_SYSTEM) && defined(UNIX) "+fork()", #endif #ifdef FEAT_GETTEXT # ifdef DYNAMIC_GETTEXT "+gettext/dyn", # else "+gettext", # endif #else "-gettext", #endif #ifdef FEAT_HANGULIN "+hangul_input", #else "-hangul_input", #endif #if (defined(HAVE_ICONV_H) && defined(USE_ICONV)) || defined(DYNAMIC_ICONV) # ifdef DYNAMIC_ICONV "+iconv/dyn", # else "+iconv", # endif #else "-iconv", #endif #ifdef FEAT_INS_EXPAND "+insert_expand", #else "-insert_expand", #endif #ifdef FEAT_JOB_CHANNEL "+job", #else "-job", #endif #ifdef FEAT_JUMPLIST "+jumplist", #else "-jumplist", #endif #ifdef FEAT_KEYMAP "+keymap", #else "-keymap", #endif #ifdef FEAT_EVAL "+lambda", #else "-lambda", #endif #ifdef FEAT_LANGMAP "+langmap", #else "-langmap", #endif #ifdef FEAT_LIBCALL "+libcall", #else "-libcall", #endif #ifdef FEAT_LINEBREAK "+linebreak", #else "-linebreak", #endif #ifdef FEAT_LISP "+lispindent", #else "-lispindent", #endif #ifdef FEAT_LISTCMDS "+listcmds", #else "-listcmds", #endif #ifdef FEAT_LOCALMAP "+localmap", #else "-localmap", #endif #ifdef FEAT_LUA # ifdef DYNAMIC_LUA "+lua/dyn", # else "+lua", # endif #else "-lua", #endif #ifdef FEAT_MENU "+menu", #else "-menu", #endif #ifdef FEAT_SESSION "+mksession", #else "-mksession", #endif #ifdef FEAT_MODIFY_FNAME "+modify_fname", #else "-modify_fname", #endif #ifdef FEAT_MOUSE "+mouse", # ifdef FEAT_MOUSESHAPE "+mouseshape", # else "-mouseshape", # endif # else "-mouse", #endif #if defined(UNIX) || defined(VMS) # ifdef FEAT_MOUSE_DEC "+mouse_dec", # else "-mouse_dec", # endif # ifdef FEAT_MOUSE_GPM "+mouse_gpm", # else "-mouse_gpm", # endif # ifdef FEAT_MOUSE_JSB "+mouse_jsbterm", # else "-mouse_jsbterm", # endif # ifdef FEAT_MOUSE_NET "+mouse_netterm", # else "-mouse_netterm", # endif #endif #ifdef __QNX__ # ifdef FEAT_MOUSE_PTERM "+mouse_pterm", # else "-mouse_pterm", # endif #endif #if defined(UNIX) || defined(VMS) # ifdef FEAT_MOUSE_SGR "+mouse_sgr", # else "-mouse_sgr", # endif # ifdef FEAT_SYSMOUSE "+mouse_sysmouse", # else "-mouse_sysmouse", # endif # ifdef FEAT_MOUSE_URXVT "+mouse_urxvt", # else "-mouse_urxvt", # endif # ifdef FEAT_MOUSE_XTERM "+mouse_xterm", # else "-mouse_xterm", # endif #endif #ifdef FEAT_MBYTE_IME # ifdef DYNAMIC_IME "+multi_byte_ime/dyn", # else "+multi_byte_ime", # endif #else # ifdef FEAT_MBYTE "+multi_byte", # else "-multi_byte", # endif #endif #ifdef FEAT_MULTI_LANG "+multi_lang", #else "-multi_lang", #endif #ifdef FEAT_MZSCHEME # ifdef DYNAMIC_MZSCHEME "+mzscheme/dyn", # else "+mzscheme", # endif #else "-mzscheme", #endif #ifdef FEAT_NETBEANS_INTG "+netbeans_intg", #else "-netbeans_intg", #endif #ifdef FEAT_NUM64 "+num64", #else "-num64", #endif #ifdef FEAT_GUI_W32 # ifdef FEAT_OLE "+ole", # else "-ole", # endif #endif "+packages", #ifdef FEAT_PATH_EXTRA "+path_extra", #else "-path_extra", #endif #ifdef FEAT_PERL # ifdef DYNAMIC_PERL "+perl/dyn", # else "+perl", # endif #else "-perl", #endif #ifdef FEAT_PERSISTENT_UNDO "+persistent_undo", #else "-persistent_undo", #endif #ifdef FEAT_PRINTER # ifdef FEAT_POSTSCRIPT "+postscript", # else "-postscript", # endif "+printer", #else "-printer", #endif #ifdef FEAT_PROFILE "+profile", #else "-profile", #endif #ifdef FEAT_PYTHON # ifdef DYNAMIC_PYTHON "+python/dyn", # else "+python", # endif #else "-python", #endif #ifdef FEAT_PYTHON3 # ifdef DYNAMIC_PYTHON3 "+python3/dyn", # else "+python3", # endif #else "-python3", #endif #ifdef FEAT_QUICKFIX "+quickfix", #else "-quickfix", #endif #ifdef FEAT_RELTIME "+reltime", #else "-reltime", #endif #ifdef FEAT_RIGHTLEFT "+rightleft", #else "-rightleft", #endif #ifdef FEAT_RUBY # ifdef DYNAMIC_RUBY "+ruby/dyn", # else "+ruby", # endif #else "-ruby", #endif #ifdef FEAT_SCROLLBIND "+scrollbind", #else "-scrollbind", #endif #ifdef FEAT_SIGNS "+signs", #else "-signs", #endif #ifdef FEAT_SMARTINDENT "+smartindent", #else "-smartindent", #endif #ifdef STARTUPTIME "+startuptime", #else "-startuptime", #endif #ifdef FEAT_STL_OPT "+statusline", #else "-statusline", #endif #ifdef FEAT_SUN_WORKSHOP "+sun_workshop", #else "-sun_workshop", #endif #ifdef FEAT_SYN_HL "+syntax", #else "-syntax", #endif /* only interesting on Unix systems */ #if defined(USE_SYSTEM) && defined(UNIX) "+system()", #endif #ifdef FEAT_TAG_BINS "+tag_binary", #else "-tag_binary", #endif #ifdef FEAT_TAG_OLDSTATIC "+tag_old_static", #else "-tag_old_static", #endif #ifdef FEAT_TAG_ANYWHITE "+tag_any_white", #else "-tag_any_white", #endif #ifdef FEAT_TCL # ifdef DYNAMIC_TCL "+tcl/dyn", # else "+tcl", # endif #else "-tcl", #endif #ifdef FEAT_TERMGUICOLORS "+termguicolors", #else "-termguicolors", #endif #if defined(UNIX) /* only Unix can have terminfo instead of termcap */ # ifdef TERMINFO "+terminfo", # else "-terminfo", # endif #else /* unix always includes termcap support */ # ifdef HAVE_TGETENT "+tgetent", # else "-tgetent", # endif #endif #ifdef FEAT_TERMRESPONSE "+termresponse", #else "-termresponse", #endif #ifdef FEAT_TEXTOBJ "+textobjects", #else "-textobjects", #endif #ifdef FEAT_TIMERS "+timers", #else "-timers", #endif #ifdef FEAT_TITLE "+title", #else "-title", #endif #ifdef FEAT_TOOLBAR "+toolbar", #else "-toolbar", #endif #ifdef FEAT_USR_CMDS "+user_commands", #else "-user_commands", #endif #ifdef FEAT_WINDOWS "+vertsplit", #else "-vertsplit", #endif #ifdef FEAT_VIRTUALEDIT "+virtualedit", #else "-virtualedit", #endif "+visual", #ifdef FEAT_VISUALEXTRA "+visualextra", #else "-visualextra", #endif #ifdef FEAT_VIMINFO "+viminfo", #else "-viminfo", #endif #ifdef FEAT_VREPLACE "+vreplace", #else "-vreplace", #endif #ifdef FEAT_WILDIGN "+wildignore", #else "-wildignore", #endif #ifdef FEAT_WILDMENU "+wildmenu", #else "-wildmenu", #endif #ifdef FEAT_WINDOWS "+windows", #else "-windows", #endif #ifdef FEAT_WRITEBACKUP "+writebackup", #else "-writebackup", #endif #if defined(UNIX) || defined(VMS) # ifdef FEAT_X11 "+X11", # else "-X11", # endif #endif #ifdef FEAT_XFONTSET "+xfontset", #else "-xfontset", #endif #ifdef FEAT_XIM "+xim", #else "-xim", #endif #ifdef WIN3264 # ifdef FEAT_XPM_W32 "+xpm_w32", # else "-xpm_w32", # endif #else # ifdef HAVE_XPM "+xpm", # else "-xpm", # endif #endif #if defined(UNIX) || defined(VMS) # ifdef USE_XSMP_INTERACT "+xsmp_interact", # else # ifdef USE_XSMP "+xsmp", # else "-xsmp", # endif # endif # ifdef FEAT_XCLIPBOARD "+xterm_clipboard", # else "-xterm_clipboard", # endif #endif #ifdef FEAT_XTERM_SAVE "+xterm_save", #else "-xterm_save", #endif NULL }; static int included_patches[] = { /* Add new patch number below this line */ /**/ 56, /**/ 55, /**/ 54, /**/ 53, /**/ 52, /**/ 51, /**/ 50, /**/ 49, /**/ 48, /**/ 47, /**/ 46, /**/ 45, /**/ 44, /**/ 43, /**/ 42, /**/ 41, /**/ 40, /**/ 39, /**/ 38, /**/ 37, /**/ 36, /**/ 35, /**/ 34, /**/ 33, /**/ 32, /**/ 31, /**/ 30, /**/ 29, /**/ 28, /**/ 27, /**/ 26, /**/ 25, /**/ 24, /**/ 23, /**/ 22, /**/ 21, /**/ 20, /**/ 19, /**/ 18, /**/ 17, /**/ 16, /**/ 15, /**/ 14, /**/ 13, /**/ 12, /**/ 11, /**/ 10, /**/ 9, /**/ 8, /**/ 7, /**/ 6, /**/ 5, /**/ 4, /**/ 3, /**/ 2, /**/ 1, /**/ 0 }; /* * Place to put a short description when adding a feature with a patch. * Keep it short, e.g.,: "relative numbers", "persistent undo". * Also add a comment marker to separate the lines. * See the official Vim patches for the diff format: It must use a context of * one line only. Create it by hand or use "diff -C2" and edit the patch. */ static char *(extra_patches[]) = { /* Add your patch description below this line */ /**/ NULL }; int highest_patch(void) { int i; int h = 0; for (i = 0; included_patches[i] != 0; ++i) if (included_patches[i] > h) h = included_patches[i]; return h; } #if defined(FEAT_EVAL) || defined(PROTO) /* * Return TRUE if patch "n" has been included. */ int has_patch(int n) { int i; for (i = 0; included_patches[i] != 0; ++i) if (included_patches[i] == n) return TRUE; return FALSE; } #endif void ex_version(exarg_T *eap) { /* * Ignore a ":version 9.99" command. */ if (*eap->arg == NUL) { msg_putchar('\n'); list_version(); } } /* * List all features aligned in columns, dictionary style. */ static void list_features(void) { int i; int ncol; int nrow; int nfeat = 0; int width = 0; /* Find the length of the longest feature name, use that + 1 as the column * width */ for (i = 0; features[i] != NULL; ++i) { int l = (int)STRLEN(features[i]); if (l > width) width = l; ++nfeat; } width += 1; if (Columns < width) { /* Not enough screen columns - show one per line */ for (i = 0; features[i] != NULL; ++i) { version_msg(features[i]); if (msg_col > 0) msg_putchar('\n'); } return; } /* The rightmost column doesn't need a separator. * Sacrifice it to fit in one more column if possible. */ ncol = (int) (Columns + 1) / width; nrow = nfeat / ncol + (nfeat % ncol ? 1 : 0); /* i counts columns then rows. idx counts rows then columns. */ for (i = 0; !got_int && i < nrow * ncol; ++i) { int idx = (i / ncol) + (i % ncol) * nrow; if (idx < nfeat) { int last_col = (i + 1) % ncol == 0; msg_puts((char_u *)features[idx]); if (last_col) { if (msg_col > 0) msg_putchar('\n'); } else { while (msg_col % width) msg_putchar(' '); } } else { if (msg_col > 0) msg_putchar('\n'); } } } void list_version(void) { int i; int first; char *s = ""; /* * When adding features here, don't forget to update the list of * internal variables in eval.c! */ MSG(longVersion); #ifdef WIN3264 # ifdef FEAT_GUI_W32 # ifdef _WIN64 MSG_PUTS(_("\nMS-Windows 64-bit GUI version")); # else MSG_PUTS(_("\nMS-Windows 32-bit GUI version")); # endif # ifdef FEAT_OLE MSG_PUTS(_(" with OLE support")); # endif # else # ifdef _WIN64 MSG_PUTS(_("\nMS-Windows 64-bit console version")); # else MSG_PUTS(_("\nMS-Windows 32-bit console version")); # endif # endif #endif #ifdef MACOS # ifdef MACOS_X # ifdef MACOS_X_UNIX MSG_PUTS(_("\nMacOS X (unix) version")); # else MSG_PUTS(_("\nMacOS X version")); # endif #else MSG_PUTS(_("\nMacOS version")); # endif #endif #ifdef VMS MSG_PUTS(_("\nOpenVMS version")); # ifdef HAVE_PATHDEF if (*compiled_arch != NUL) { MSG_PUTS(" - "); MSG_PUTS(compiled_arch); } # endif #endif /* Print the list of patch numbers if there is at least one. */ /* Print a range when patches are consecutive: "1-10, 12, 15-40, 42-45" */ if (included_patches[0] != 0) { MSG_PUTS(_("\nIncluded patches: ")); first = -1; /* find last one */ for (i = 0; included_patches[i] != 0; ++i) ; while (--i >= 0) { if (first < 0) first = included_patches[i]; if (i == 0 || included_patches[i - 1] != included_patches[i] + 1) { MSG_PUTS(s); s = ", "; msg_outnum((long)first); if (first != included_patches[i]) { MSG_PUTS("-"); msg_outnum((long)included_patches[i]); } first = -1; } } } /* Print the list of extra patch descriptions if there is at least one. */ if (extra_patches[0] != NULL) { MSG_PUTS(_("\nExtra patches: ")); s = ""; for (i = 0; extra_patches[i] != NULL; ++i) { MSG_PUTS(s); s = ", "; MSG_PUTS(extra_patches[i]); } } #ifdef MODIFIED_BY MSG_PUTS("\n"); MSG_PUTS(_("Modified by ")); MSG_PUTS(MODIFIED_BY); #endif #ifdef HAVE_PATHDEF if (*compiled_user != NUL || *compiled_sys != NUL) { MSG_PUTS(_("\nCompiled ")); if (*compiled_user != NUL) { MSG_PUTS(_("by ")); MSG_PUTS(compiled_user); } if (*compiled_sys != NUL) { MSG_PUTS("@"); MSG_PUTS(compiled_sys); } } #endif #ifdef FEAT_HUGE MSG_PUTS(_("\nHuge version ")); #else # ifdef FEAT_BIG MSG_PUTS(_("\nBig version ")); # else # ifdef FEAT_NORMAL MSG_PUTS(_("\nNormal version ")); # else # ifdef FEAT_SMALL MSG_PUTS(_("\nSmall version ")); # else MSG_PUTS(_("\nTiny version ")); # endif # endif # endif #endif #ifndef FEAT_GUI MSG_PUTS(_("without GUI.")); #else # ifdef FEAT_GUI_GTK # ifdef USE_GTK3 MSG_PUTS(_("with GTK3 GUI.")); # else # ifdef FEAT_GUI_GNOME MSG_PUTS(_("with GTK2-GNOME GUI.")); # else MSG_PUTS(_("with GTK2 GUI.")); # endif # endif # else # ifdef FEAT_GUI_MOTIF MSG_PUTS(_("with X11-Motif GUI.")); # else # ifdef FEAT_GUI_ATHENA # ifdef FEAT_GUI_NEXTAW MSG_PUTS(_("with X11-neXtaw GUI.")); # else MSG_PUTS(_("with X11-Athena GUI.")); # endif # else # ifdef FEAT_GUI_PHOTON MSG_PUTS(_("with Photon GUI.")); # else # if defined(MSWIN) MSG_PUTS(_("with GUI.")); # else # if defined(TARGET_API_MAC_CARBON) && TARGET_API_MAC_CARBON MSG_PUTS(_("with Carbon GUI.")); # else # if defined(TARGET_API_MAC_OSX) && TARGET_API_MAC_OSX MSG_PUTS(_("with Cocoa GUI.")); # else # if defined(MACOS) MSG_PUTS(_("with (classic) GUI.")); # endif # endif # endif # endif # endif # endif # endif # endif #endif version_msg(_(" Features included (+) or not (-):\n")); list_features(); #ifdef SYS_VIMRC_FILE version_msg(_(" system vimrc file: \"")); version_msg(SYS_VIMRC_FILE); version_msg("\"\n"); #endif #ifdef USR_VIMRC_FILE version_msg(_(" user vimrc file: \"")); version_msg(USR_VIMRC_FILE); version_msg("\"\n"); #endif #ifdef USR_VIMRC_FILE2 version_msg(_(" 2nd user vimrc file: \"")); version_msg(USR_VIMRC_FILE2); version_msg("\"\n"); #endif #ifdef USR_VIMRC_FILE3 version_msg(_(" 3rd user vimrc file: \"")); version_msg(USR_VIMRC_FILE3); version_msg("\"\n"); #endif #ifdef USR_EXRC_FILE version_msg(_(" user exrc file: \"")); version_msg(USR_EXRC_FILE); version_msg("\"\n"); #endif #ifdef USR_EXRC_FILE2 version_msg(_(" 2nd user exrc file: \"")); version_msg(USR_EXRC_FILE2); version_msg("\"\n"); #endif #ifdef FEAT_GUI # ifdef SYS_GVIMRC_FILE version_msg(_(" system gvimrc file: \"")); version_msg(SYS_GVIMRC_FILE); version_msg("\"\n"); # endif version_msg(_(" user gvimrc file: \"")); version_msg(USR_GVIMRC_FILE); version_msg("\"\n"); # ifdef USR_GVIMRC_FILE2 version_msg(_("2nd user gvimrc file: \"")); version_msg(USR_GVIMRC_FILE2); version_msg("\"\n"); # endif # ifdef USR_GVIMRC_FILE3 version_msg(_("3rd user gvimrc file: \"")); version_msg(USR_GVIMRC_FILE3); version_msg("\"\n"); # endif #endif version_msg(_(" defaults file: \"")); version_msg(VIM_DEFAULTS_FILE); version_msg("\"\n"); #ifdef FEAT_GUI # ifdef SYS_MENU_FILE version_msg(_(" system menu file: \"")); version_msg(SYS_MENU_FILE); version_msg("\"\n"); # endif #endif #ifdef HAVE_PATHDEF if (*default_vim_dir != NUL) { version_msg(_(" fall-back for $VIM: \"")); version_msg((char *)default_vim_dir); version_msg("\"\n"); } if (*default_vimruntime_dir != NUL) { version_msg(_(" f-b for $VIMRUNTIME: \"")); version_msg((char *)default_vimruntime_dir); version_msg("\"\n"); } version_msg(_("Compilation: ")); version_msg((char *)all_cflags); version_msg("\n"); #ifdef VMS if (*compiler_version != NUL) { version_msg(_("Compiler: ")); version_msg((char *)compiler_version); version_msg("\n"); } #endif version_msg(_("Linking: ")); version_msg((char *)all_lflags); #endif #ifdef DEBUG version_msg("\n"); version_msg(_(" DEBUG BUILD")); #endif } /* * Output a string for the version message. If it's going to wrap, output a * newline, unless the message is too long to fit on the screen anyway. */ static void version_msg(char *s) { int len = (int)STRLEN(s); if (!got_int && len < (int)Columns && msg_col + len >= (int)Columns && *s != '\n') msg_putchar('\n'); if (!got_int) MSG_PUTS(s); } static void do_intro_line(int row, char_u *mesg, int add_version, int attr); /* * Show the intro message when not editing a file. */ void maybe_intro_message(void) { if (bufempty() && curbuf->b_fname == NULL #ifdef FEAT_WINDOWS && firstwin->w_next == NULL #endif && vim_strchr(p_shm, SHM_INTRO) == NULL) intro_message(FALSE); } /* * Give an introductory message about Vim. * Only used when starting Vim on an empty file, without a file name. * Or with the ":intro" command (for Sven :-). */ void intro_message( int colon) /* TRUE for ":intro" */ { int i; int row; int blanklines; int sponsor; char *p; static char *(lines[]) = { N_("VIM - Vi IMproved"), "", N_("version "), N_("by Bram Moolenaar et al."), #ifdef MODIFIED_BY " ", #endif N_("Vim is open source and freely distributable"), "", N_("Help poor children in Uganda!"), N_("type :help iccf<Enter> for information "), "", N_("type :q<Enter> to exit "), N_("type :help<Enter> or <F1> for on-line help"), N_("type :help version8<Enter> for version info"), NULL, "", N_("Running in Vi compatible mode"), N_("type :set nocp<Enter> for Vim defaults"), N_("type :help cp-default<Enter> for info on this"), }; #ifdef FEAT_GUI static char *(gui_lines[]) = { NULL, NULL, NULL, NULL, #ifdef MODIFIED_BY NULL, #endif NULL, NULL, NULL, N_("menu Help->Orphans for information "), NULL, N_("Running modeless, typed text is inserted"), N_("menu Edit->Global Settings->Toggle Insert Mode "), N_(" for two modes "), NULL, NULL, NULL, N_("menu Edit->Global Settings->Toggle Vi Compatible"), N_(" for Vim defaults "), }; #endif /* blanklines = screen height - # message lines */ blanklines = (int)Rows - ((sizeof(lines) / sizeof(char *)) - 1); if (!p_cp) blanklines += 4; /* add 4 for not showing "Vi compatible" message */ #ifdef FEAT_WINDOWS /* Don't overwrite a statusline. Depends on 'cmdheight'. */ if (p_ls > 1) blanklines -= Rows - topframe->fr_height; #endif if (blanklines < 0) blanklines = 0; /* Show the sponsor and register message one out of four times, the Uganda * message two out of four times. */ sponsor = (int)time(NULL); sponsor = ((sponsor & 2) == 0) - ((sponsor & 4) == 0); /* start displaying the message lines after half of the blank lines */ row = blanklines / 2; if ((row >= 2 && Columns >= 50) || colon) { for (i = 0; i < (int)(sizeof(lines) / sizeof(char *)); ++i) { p = lines[i]; #ifdef FEAT_GUI if (p_im && gui.in_use && gui_lines[i] != NULL) p = gui_lines[i]; #endif if (p == NULL) { if (!p_cp) break; continue; } if (sponsor != 0) { if (strstr(p, "children") != NULL) p = sponsor < 0 ? N_("Sponsor Vim development!") : N_("Become a registered Vim user!"); else if (strstr(p, "iccf") != NULL) p = sponsor < 0 ? N_("type :help sponsor<Enter> for information ") : N_("type :help register<Enter> for information "); else if (strstr(p, "Orphans") != NULL) p = N_("menu Help->Sponsor/Register for information "); } if (*p != NUL) do_intro_line(row, (char_u *)_(p), i == 2, 0); ++row; } } /* Make the wait-return message appear just below the text. */ if (colon) msg_row = row; } static void do_intro_line( int row, char_u *mesg, int add_version, int attr) { char_u vers[20]; int col; char_u *p; int l; int clen; #ifdef MODIFIED_BY # define MODBY_LEN 150 char_u modby[MODBY_LEN]; if (*mesg == ' ') { vim_strncpy(modby, (char_u *)_("Modified by "), MODBY_LEN - 1); l = (int)STRLEN(modby); vim_strncpy(modby + l, (char_u *)MODIFIED_BY, MODBY_LEN - l - 1); mesg = modby; } #endif /* Center the message horizontally. */ col = vim_strsize(mesg); if (add_version) { STRCPY(vers, mediumVersion); if (highest_patch()) { /* Check for 9.9x or 9.9xx, alpha/beta version */ if (isalpha((int)vers[3])) { int len = (isalpha((int)vers[4])) ? 5 : 4; sprintf((char *)vers + len, ".%d%s", highest_patch(), mediumVersion + len); } else sprintf((char *)vers + 3, ".%d", highest_patch()); } col += (int)STRLEN(vers); } col = (Columns - col) / 2; if (col < 0) col = 0; /* Split up in parts to highlight <> items differently. */ for (p = mesg; *p != NUL; p += l) { clen = 0; for (l = 0; p[l] != NUL && (l == 0 || (p[l] != '<' && p[l - 1] != '>')); ++l) { #ifdef FEAT_MBYTE if (has_mbyte) { clen += ptr2cells(p + l); l += (*mb_ptr2len)(p + l) - 1; } else #endif clen += byte2cells(p[l]); } screen_puts_len(p, l, row, col, *p == '<' ? hl_attr(HLF_8) : attr); col += clen; } /* Add the version number to the version line. */ if (add_version) screen_puts(vers, row, col, 0); } /* * ":intro": clear screen, display intro screen and wait for return. */ void ex_intro(exarg_T *eap UNUSED) { screenclear(); intro_message(TRUE); wait_return(TRUE); }
./CrossVul/dataset_final_sorted/CWE-20/c/good_4900_2
crossvul-cpp_data_bad_2891_3
/* * Copyright (C) 2010 IBM Corporation * Copyright (C) 2010 Politecnico di Torino, Italy * TORSEC group -- http://security.polito.it * * Authors: * Mimi Zohar <zohar@us.ibm.com> * Roberto Sassu <roberto.sassu@polito.it> * * 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, version 2 of the License. * * See Documentation/security/keys/trusted-encrypted.rst */ #include <linux/uaccess.h> #include <linux/module.h> #include <linux/init.h> #include <linux/slab.h> #include <linux/parser.h> #include <linux/string.h> #include <linux/err.h> #include <keys/user-type.h> #include <keys/trusted-type.h> #include <keys/encrypted-type.h> #include <linux/key-type.h> #include <linux/random.h> #include <linux/rcupdate.h> #include <linux/scatterlist.h> #include <linux/ctype.h> #include <crypto/aes.h> #include <crypto/algapi.h> #include <crypto/hash.h> #include <crypto/sha.h> #include <crypto/skcipher.h> #include "encrypted.h" #include "ecryptfs_format.h" static const char KEY_TRUSTED_PREFIX[] = "trusted:"; static const char KEY_USER_PREFIX[] = "user:"; static const char hash_alg[] = "sha256"; static const char hmac_alg[] = "hmac(sha256)"; static const char blkcipher_alg[] = "cbc(aes)"; static const char key_format_default[] = "default"; static const char key_format_ecryptfs[] = "ecryptfs"; static unsigned int ivsize; static int blksize; #define KEY_TRUSTED_PREFIX_LEN (sizeof (KEY_TRUSTED_PREFIX) - 1) #define KEY_USER_PREFIX_LEN (sizeof (KEY_USER_PREFIX) - 1) #define KEY_ECRYPTFS_DESC_LEN 16 #define HASH_SIZE SHA256_DIGEST_SIZE #define MAX_DATA_SIZE 4096 #define MIN_DATA_SIZE 20 static struct crypto_shash *hash_tfm; enum { Opt_err = -1, Opt_new, Opt_load, Opt_update }; enum { Opt_error = -1, Opt_default, Opt_ecryptfs }; static const match_table_t key_format_tokens = { {Opt_default, "default"}, {Opt_ecryptfs, "ecryptfs"}, {Opt_error, NULL} }; static const match_table_t key_tokens = { {Opt_new, "new"}, {Opt_load, "load"}, {Opt_update, "update"}, {Opt_err, NULL} }; static int aes_get_sizes(void) { struct crypto_skcipher *tfm; tfm = crypto_alloc_skcipher(blkcipher_alg, 0, CRYPTO_ALG_ASYNC); if (IS_ERR(tfm)) { pr_err("encrypted_key: failed to alloc_cipher (%ld)\n", PTR_ERR(tfm)); return PTR_ERR(tfm); } ivsize = crypto_skcipher_ivsize(tfm); blksize = crypto_skcipher_blocksize(tfm); crypto_free_skcipher(tfm); return 0; } /* * valid_ecryptfs_desc - verify the description of a new/loaded encrypted key * * The description of a encrypted key with format 'ecryptfs' must contain * exactly 16 hexadecimal characters. * */ static int valid_ecryptfs_desc(const char *ecryptfs_desc) { int i; if (strlen(ecryptfs_desc) != KEY_ECRYPTFS_DESC_LEN) { pr_err("encrypted_key: key description must be %d hexadecimal " "characters long\n", KEY_ECRYPTFS_DESC_LEN); return -EINVAL; } for (i = 0; i < KEY_ECRYPTFS_DESC_LEN; i++) { if (!isxdigit(ecryptfs_desc[i])) { pr_err("encrypted_key: key description must contain " "only hexadecimal characters\n"); return -EINVAL; } } return 0; } /* * valid_master_desc - verify the 'key-type:desc' of a new/updated master-key * * key-type:= "trusted:" | "user:" * desc:= master-key description * * Verify that 'key-type' is valid and that 'desc' exists. On key update, * only the master key description is permitted to change, not the key-type. * The key-type remains constant. * * On success returns 0, otherwise -EINVAL. */ static int valid_master_desc(const char *new_desc, const char *orig_desc) { int prefix_len; if (!strncmp(new_desc, KEY_TRUSTED_PREFIX, KEY_TRUSTED_PREFIX_LEN)) prefix_len = KEY_TRUSTED_PREFIX_LEN; else if (!strncmp(new_desc, KEY_USER_PREFIX, KEY_USER_PREFIX_LEN)) prefix_len = KEY_USER_PREFIX_LEN; else return -EINVAL; if (!new_desc[prefix_len]) return -EINVAL; if (orig_desc && strncmp(new_desc, orig_desc, prefix_len)) return -EINVAL; return 0; } /* * datablob_parse - parse the keyctl data * * datablob format: * new [<format>] <master-key name> <decrypted data length> * load [<format>] <master-key name> <decrypted data length> * <encrypted iv + data> * update <new-master-key name> * * Tokenizes a copy of the keyctl data, returning a pointer to each token, * which is null terminated. * * On success returns 0, otherwise -EINVAL. */ static int datablob_parse(char *datablob, const char **format, char **master_desc, char **decrypted_datalen, char **hex_encoded_iv) { substring_t args[MAX_OPT_ARGS]; int ret = -EINVAL; int key_cmd; int key_format; char *p, *keyword; keyword = strsep(&datablob, " \t"); if (!keyword) { pr_info("encrypted_key: insufficient parameters specified\n"); return ret; } key_cmd = match_token(keyword, key_tokens, args); /* Get optional format: default | ecryptfs */ p = strsep(&datablob, " \t"); if (!p) { pr_err("encrypted_key: insufficient parameters specified\n"); return ret; } key_format = match_token(p, key_format_tokens, args); switch (key_format) { case Opt_ecryptfs: case Opt_default: *format = p; *master_desc = strsep(&datablob, " \t"); break; case Opt_error: *master_desc = p; break; } if (!*master_desc) { pr_info("encrypted_key: master key parameter is missing\n"); goto out; } if (valid_master_desc(*master_desc, NULL) < 0) { pr_info("encrypted_key: master key parameter \'%s\' " "is invalid\n", *master_desc); goto out; } if (decrypted_datalen) { *decrypted_datalen = strsep(&datablob, " \t"); if (!*decrypted_datalen) { pr_info("encrypted_key: keylen parameter is missing\n"); goto out; } } switch (key_cmd) { case Opt_new: if (!decrypted_datalen) { pr_info("encrypted_key: keyword \'%s\' not allowed " "when called from .update method\n", keyword); break; } ret = 0; break; case Opt_load: if (!decrypted_datalen) { pr_info("encrypted_key: keyword \'%s\' not allowed " "when called from .update method\n", keyword); break; } *hex_encoded_iv = strsep(&datablob, " \t"); if (!*hex_encoded_iv) { pr_info("encrypted_key: hex blob is missing\n"); break; } ret = 0; break; case Opt_update: if (decrypted_datalen) { pr_info("encrypted_key: keyword \'%s\' not allowed " "when called from .instantiate method\n", keyword); break; } ret = 0; break; case Opt_err: pr_info("encrypted_key: keyword \'%s\' not recognized\n", keyword); break; } out: return ret; } /* * datablob_format - format as an ascii string, before copying to userspace */ static char *datablob_format(struct encrypted_key_payload *epayload, size_t asciiblob_len) { char *ascii_buf, *bufp; u8 *iv = epayload->iv; int len; int i; ascii_buf = kmalloc(asciiblob_len + 1, GFP_KERNEL); if (!ascii_buf) goto out; ascii_buf[asciiblob_len] = '\0'; /* copy datablob master_desc and datalen strings */ len = sprintf(ascii_buf, "%s %s %s ", epayload->format, epayload->master_desc, epayload->datalen); /* convert the hex encoded iv, encrypted-data and HMAC to ascii */ bufp = &ascii_buf[len]; for (i = 0; i < (asciiblob_len - len) / 2; i++) bufp = hex_byte_pack(bufp, iv[i]); out: return ascii_buf; } /* * request_user_key - request the user key * * Use a user provided key to encrypt/decrypt an encrypted-key. */ static struct key *request_user_key(const char *master_desc, const u8 **master_key, size_t *master_keylen) { const struct user_key_payload *upayload; struct key *ukey; ukey = request_key(&key_type_user, master_desc, NULL); if (IS_ERR(ukey)) goto error; down_read(&ukey->sem); upayload = user_key_payload_locked(ukey); if (!upayload) { /* key was revoked before we acquired its semaphore */ up_read(&ukey->sem); key_put(ukey); ukey = ERR_PTR(-EKEYREVOKED); goto error; } *master_key = upayload->data; *master_keylen = upayload->datalen; error: return ukey; } static int calc_hash(struct crypto_shash *tfm, u8 *digest, const u8 *buf, unsigned int buflen) { SHASH_DESC_ON_STACK(desc, tfm); int err; desc->tfm = tfm; desc->flags = 0; err = crypto_shash_digest(desc, buf, buflen, digest); shash_desc_zero(desc); return err; } static int calc_hmac(u8 *digest, const u8 *key, unsigned int keylen, const u8 *buf, unsigned int buflen) { struct crypto_shash *tfm; int err; tfm = crypto_alloc_shash(hmac_alg, 0, CRYPTO_ALG_ASYNC); if (IS_ERR(tfm)) { pr_err("encrypted_key: can't alloc %s transform: %ld\n", hmac_alg, PTR_ERR(tfm)); return PTR_ERR(tfm); } err = crypto_shash_setkey(tfm, key, keylen); if (!err) err = calc_hash(tfm, digest, buf, buflen); crypto_free_shash(tfm); return err; } enum derived_key_type { ENC_KEY, AUTH_KEY }; /* Derive authentication/encryption key from trusted key */ static int get_derived_key(u8 *derived_key, enum derived_key_type key_type, const u8 *master_key, size_t master_keylen) { u8 *derived_buf; unsigned int derived_buf_len; int ret; derived_buf_len = strlen("AUTH_KEY") + 1 + master_keylen; if (derived_buf_len < HASH_SIZE) derived_buf_len = HASH_SIZE; derived_buf = kzalloc(derived_buf_len, GFP_KERNEL); if (!derived_buf) return -ENOMEM; if (key_type) strcpy(derived_buf, "AUTH_KEY"); else strcpy(derived_buf, "ENC_KEY"); memcpy(derived_buf + strlen(derived_buf) + 1, master_key, master_keylen); ret = calc_hash(hash_tfm, derived_key, derived_buf, derived_buf_len); kzfree(derived_buf); return ret; } static struct skcipher_request *init_skcipher_req(const u8 *key, unsigned int key_len) { struct skcipher_request *req; struct crypto_skcipher *tfm; int ret; tfm = crypto_alloc_skcipher(blkcipher_alg, 0, CRYPTO_ALG_ASYNC); if (IS_ERR(tfm)) { pr_err("encrypted_key: failed to load %s transform (%ld)\n", blkcipher_alg, PTR_ERR(tfm)); return ERR_CAST(tfm); } ret = crypto_skcipher_setkey(tfm, key, key_len); if (ret < 0) { pr_err("encrypted_key: failed to setkey (%d)\n", ret); crypto_free_skcipher(tfm); return ERR_PTR(ret); } req = skcipher_request_alloc(tfm, GFP_KERNEL); if (!req) { pr_err("encrypted_key: failed to allocate request for %s\n", blkcipher_alg); crypto_free_skcipher(tfm); return ERR_PTR(-ENOMEM); } skcipher_request_set_callback(req, 0, NULL, NULL); return req; } static struct key *request_master_key(struct encrypted_key_payload *epayload, const u8 **master_key, size_t *master_keylen) { struct key *mkey = ERR_PTR(-EINVAL); if (!strncmp(epayload->master_desc, KEY_TRUSTED_PREFIX, KEY_TRUSTED_PREFIX_LEN)) { mkey = request_trusted_key(epayload->master_desc + KEY_TRUSTED_PREFIX_LEN, master_key, master_keylen); } else if (!strncmp(epayload->master_desc, KEY_USER_PREFIX, KEY_USER_PREFIX_LEN)) { mkey = request_user_key(epayload->master_desc + KEY_USER_PREFIX_LEN, master_key, master_keylen); } else goto out; if (IS_ERR(mkey)) { int ret = PTR_ERR(mkey); if (ret == -ENOTSUPP) pr_info("encrypted_key: key %s not supported", epayload->master_desc); else pr_info("encrypted_key: key %s not found", epayload->master_desc); goto out; } dump_master_key(*master_key, *master_keylen); out: return mkey; } /* Before returning data to userspace, encrypt decrypted data. */ static int derived_key_encrypt(struct encrypted_key_payload *epayload, const u8 *derived_key, unsigned int derived_keylen) { struct scatterlist sg_in[2]; struct scatterlist sg_out[1]; struct crypto_skcipher *tfm; struct skcipher_request *req; unsigned int encrypted_datalen; u8 iv[AES_BLOCK_SIZE]; int ret; encrypted_datalen = roundup(epayload->decrypted_datalen, blksize); req = init_skcipher_req(derived_key, derived_keylen); ret = PTR_ERR(req); if (IS_ERR(req)) goto out; dump_decrypted_data(epayload); sg_init_table(sg_in, 2); sg_set_buf(&sg_in[0], epayload->decrypted_data, epayload->decrypted_datalen); sg_set_page(&sg_in[1], ZERO_PAGE(0), AES_BLOCK_SIZE, 0); sg_init_table(sg_out, 1); sg_set_buf(sg_out, epayload->encrypted_data, encrypted_datalen); memcpy(iv, epayload->iv, sizeof(iv)); skcipher_request_set_crypt(req, sg_in, sg_out, encrypted_datalen, iv); ret = crypto_skcipher_encrypt(req); tfm = crypto_skcipher_reqtfm(req); skcipher_request_free(req); crypto_free_skcipher(tfm); if (ret < 0) pr_err("encrypted_key: failed to encrypt (%d)\n", ret); else dump_encrypted_data(epayload, encrypted_datalen); out: return ret; } static int datablob_hmac_append(struct encrypted_key_payload *epayload, const u8 *master_key, size_t master_keylen) { u8 derived_key[HASH_SIZE]; u8 *digest; int ret; ret = get_derived_key(derived_key, AUTH_KEY, master_key, master_keylen); if (ret < 0) goto out; digest = epayload->format + epayload->datablob_len; ret = calc_hmac(digest, derived_key, sizeof derived_key, epayload->format, epayload->datablob_len); if (!ret) dump_hmac(NULL, digest, HASH_SIZE); out: memzero_explicit(derived_key, sizeof(derived_key)); return ret; } /* verify HMAC before decrypting encrypted key */ static int datablob_hmac_verify(struct encrypted_key_payload *epayload, const u8 *format, const u8 *master_key, size_t master_keylen) { u8 derived_key[HASH_SIZE]; u8 digest[HASH_SIZE]; int ret; char *p; unsigned short len; ret = get_derived_key(derived_key, AUTH_KEY, master_key, master_keylen); if (ret < 0) goto out; len = epayload->datablob_len; if (!format) { p = epayload->master_desc; len -= strlen(epayload->format) + 1; } else p = epayload->format; ret = calc_hmac(digest, derived_key, sizeof derived_key, p, len); if (ret < 0) goto out; ret = crypto_memneq(digest, epayload->format + epayload->datablob_len, sizeof(digest)); if (ret) { ret = -EINVAL; dump_hmac("datablob", epayload->format + epayload->datablob_len, HASH_SIZE); dump_hmac("calc", digest, HASH_SIZE); } out: memzero_explicit(derived_key, sizeof(derived_key)); return ret; } static int derived_key_decrypt(struct encrypted_key_payload *epayload, const u8 *derived_key, unsigned int derived_keylen) { struct scatterlist sg_in[1]; struct scatterlist sg_out[2]; struct crypto_skcipher *tfm; struct skcipher_request *req; unsigned int encrypted_datalen; u8 iv[AES_BLOCK_SIZE]; u8 *pad; int ret; /* Throwaway buffer to hold the unused zero padding at the end */ pad = kmalloc(AES_BLOCK_SIZE, GFP_KERNEL); if (!pad) return -ENOMEM; encrypted_datalen = roundup(epayload->decrypted_datalen, blksize); req = init_skcipher_req(derived_key, derived_keylen); ret = PTR_ERR(req); if (IS_ERR(req)) goto out; dump_encrypted_data(epayload, encrypted_datalen); sg_init_table(sg_in, 1); sg_init_table(sg_out, 2); sg_set_buf(sg_in, epayload->encrypted_data, encrypted_datalen); sg_set_buf(&sg_out[0], epayload->decrypted_data, epayload->decrypted_datalen); sg_set_buf(&sg_out[1], pad, AES_BLOCK_SIZE); memcpy(iv, epayload->iv, sizeof(iv)); skcipher_request_set_crypt(req, sg_in, sg_out, encrypted_datalen, iv); ret = crypto_skcipher_decrypt(req); tfm = crypto_skcipher_reqtfm(req); skcipher_request_free(req); crypto_free_skcipher(tfm); if (ret < 0) goto out; dump_decrypted_data(epayload); out: kfree(pad); return ret; } /* Allocate memory for decrypted key and datablob. */ static struct encrypted_key_payload *encrypted_key_alloc(struct key *key, const char *format, const char *master_desc, const char *datalen) { struct encrypted_key_payload *epayload = NULL; unsigned short datablob_len; unsigned short decrypted_datalen; unsigned short payload_datalen; unsigned int encrypted_datalen; unsigned int format_len; long dlen; int ret; ret = kstrtol(datalen, 10, &dlen); if (ret < 0 || dlen < MIN_DATA_SIZE || dlen > MAX_DATA_SIZE) return ERR_PTR(-EINVAL); format_len = (!format) ? strlen(key_format_default) : strlen(format); decrypted_datalen = dlen; payload_datalen = decrypted_datalen; if (format && !strcmp(format, key_format_ecryptfs)) { if (dlen != ECRYPTFS_MAX_KEY_BYTES) { pr_err("encrypted_key: keylen for the ecryptfs format " "must be equal to %d bytes\n", ECRYPTFS_MAX_KEY_BYTES); return ERR_PTR(-EINVAL); } decrypted_datalen = ECRYPTFS_MAX_KEY_BYTES; payload_datalen = sizeof(struct ecryptfs_auth_tok); } encrypted_datalen = roundup(decrypted_datalen, blksize); datablob_len = format_len + 1 + strlen(master_desc) + 1 + strlen(datalen) + 1 + ivsize + 1 + encrypted_datalen; ret = key_payload_reserve(key, payload_datalen + datablob_len + HASH_SIZE + 1); if (ret < 0) return ERR_PTR(ret); epayload = kzalloc(sizeof(*epayload) + payload_datalen + datablob_len + HASH_SIZE + 1, GFP_KERNEL); if (!epayload) return ERR_PTR(-ENOMEM); epayload->payload_datalen = payload_datalen; epayload->decrypted_datalen = decrypted_datalen; epayload->datablob_len = datablob_len; return epayload; } static int encrypted_key_decrypt(struct encrypted_key_payload *epayload, const char *format, const char *hex_encoded_iv) { struct key *mkey; u8 derived_key[HASH_SIZE]; const u8 *master_key; u8 *hmac; const char *hex_encoded_data; unsigned int encrypted_datalen; size_t master_keylen; size_t asciilen; int ret; encrypted_datalen = roundup(epayload->decrypted_datalen, blksize); asciilen = (ivsize + 1 + encrypted_datalen + HASH_SIZE) * 2; if (strlen(hex_encoded_iv) != asciilen) return -EINVAL; hex_encoded_data = hex_encoded_iv + (2 * ivsize) + 2; ret = hex2bin(epayload->iv, hex_encoded_iv, ivsize); if (ret < 0) return -EINVAL; ret = hex2bin(epayload->encrypted_data, hex_encoded_data, encrypted_datalen); if (ret < 0) return -EINVAL; hmac = epayload->format + epayload->datablob_len; ret = hex2bin(hmac, hex_encoded_data + (encrypted_datalen * 2), HASH_SIZE); if (ret < 0) return -EINVAL; mkey = request_master_key(epayload, &master_key, &master_keylen); if (IS_ERR(mkey)) return PTR_ERR(mkey); ret = datablob_hmac_verify(epayload, format, master_key, master_keylen); if (ret < 0) { pr_err("encrypted_key: bad hmac (%d)\n", ret); goto out; } ret = get_derived_key(derived_key, ENC_KEY, master_key, master_keylen); if (ret < 0) goto out; ret = derived_key_decrypt(epayload, derived_key, sizeof derived_key); if (ret < 0) pr_err("encrypted_key: failed to decrypt key (%d)\n", ret); out: up_read(&mkey->sem); key_put(mkey); memzero_explicit(derived_key, sizeof(derived_key)); return ret; } static void __ekey_init(struct encrypted_key_payload *epayload, const char *format, const char *master_desc, const char *datalen) { unsigned int format_len; format_len = (!format) ? strlen(key_format_default) : strlen(format); epayload->format = epayload->payload_data + epayload->payload_datalen; epayload->master_desc = epayload->format + format_len + 1; epayload->datalen = epayload->master_desc + strlen(master_desc) + 1; epayload->iv = epayload->datalen + strlen(datalen) + 1; epayload->encrypted_data = epayload->iv + ivsize + 1; epayload->decrypted_data = epayload->payload_data; if (!format) memcpy(epayload->format, key_format_default, format_len); else { if (!strcmp(format, key_format_ecryptfs)) epayload->decrypted_data = ecryptfs_get_auth_tok_key((struct ecryptfs_auth_tok *)epayload->payload_data); memcpy(epayload->format, format, format_len); } memcpy(epayload->master_desc, master_desc, strlen(master_desc)); memcpy(epayload->datalen, datalen, strlen(datalen)); } /* * encrypted_init - initialize an encrypted key * * For a new key, use a random number for both the iv and data * itself. For an old key, decrypt the hex encoded data. */ static int encrypted_init(struct encrypted_key_payload *epayload, const char *key_desc, const char *format, const char *master_desc, const char *datalen, const char *hex_encoded_iv) { int ret = 0; if (format && !strcmp(format, key_format_ecryptfs)) { ret = valid_ecryptfs_desc(key_desc); if (ret < 0) return ret; ecryptfs_fill_auth_tok((struct ecryptfs_auth_tok *)epayload->payload_data, key_desc); } __ekey_init(epayload, format, master_desc, datalen); if (!hex_encoded_iv) { get_random_bytes(epayload->iv, ivsize); get_random_bytes(epayload->decrypted_data, epayload->decrypted_datalen); } else ret = encrypted_key_decrypt(epayload, format, hex_encoded_iv); return ret; } /* * encrypted_instantiate - instantiate an encrypted key * * Decrypt an existing encrypted datablob or create a new encrypted key * based on a kernel random number. * * On success, return 0. Otherwise return errno. */ static int encrypted_instantiate(struct key *key, struct key_preparsed_payload *prep) { struct encrypted_key_payload *epayload = NULL; char *datablob = NULL; const char *format = NULL; char *master_desc = NULL; char *decrypted_datalen = NULL; char *hex_encoded_iv = NULL; size_t datalen = prep->datalen; int ret; if (datalen <= 0 || datalen > 32767 || !prep->data) return -EINVAL; datablob = kmalloc(datalen + 1, GFP_KERNEL); if (!datablob) return -ENOMEM; datablob[datalen] = 0; memcpy(datablob, prep->data, datalen); ret = datablob_parse(datablob, &format, &master_desc, &decrypted_datalen, &hex_encoded_iv); if (ret < 0) goto out; epayload = encrypted_key_alloc(key, format, master_desc, decrypted_datalen); if (IS_ERR(epayload)) { ret = PTR_ERR(epayload); goto out; } ret = encrypted_init(epayload, key->description, format, master_desc, decrypted_datalen, hex_encoded_iv); if (ret < 0) { kzfree(epayload); goto out; } rcu_assign_keypointer(key, epayload); out: kzfree(datablob); return ret; } static void encrypted_rcu_free(struct rcu_head *rcu) { struct encrypted_key_payload *epayload; epayload = container_of(rcu, struct encrypted_key_payload, rcu); kzfree(epayload); } /* * encrypted_update - update the master key description * * Change the master key description for an existing encrypted key. * The next read will return an encrypted datablob using the new * master key description. * * On success, return 0. Otherwise return errno. */ static int encrypted_update(struct key *key, struct key_preparsed_payload *prep) { struct encrypted_key_payload *epayload = key->payload.data[0]; struct encrypted_key_payload *new_epayload; char *buf; char *new_master_desc = NULL; const char *format = NULL; size_t datalen = prep->datalen; int ret = 0; if (test_bit(KEY_FLAG_NEGATIVE, &key->flags)) return -ENOKEY; if (datalen <= 0 || datalen > 32767 || !prep->data) return -EINVAL; buf = kmalloc(datalen + 1, GFP_KERNEL); if (!buf) return -ENOMEM; buf[datalen] = 0; memcpy(buf, prep->data, datalen); ret = datablob_parse(buf, &format, &new_master_desc, NULL, NULL); if (ret < 0) goto out; ret = valid_master_desc(new_master_desc, epayload->master_desc); if (ret < 0) goto out; new_epayload = encrypted_key_alloc(key, epayload->format, new_master_desc, epayload->datalen); if (IS_ERR(new_epayload)) { ret = PTR_ERR(new_epayload); goto out; } __ekey_init(new_epayload, epayload->format, new_master_desc, epayload->datalen); memcpy(new_epayload->iv, epayload->iv, ivsize); memcpy(new_epayload->payload_data, epayload->payload_data, epayload->payload_datalen); rcu_assign_keypointer(key, new_epayload); call_rcu(&epayload->rcu, encrypted_rcu_free); out: kzfree(buf); return ret; } /* * encrypted_read - format and copy the encrypted data to userspace * * The resulting datablob format is: * <master-key name> <decrypted data length> <encrypted iv> <encrypted data> * * On success, return to userspace the encrypted key datablob size. */ static long encrypted_read(const struct key *key, char __user *buffer, size_t buflen) { struct encrypted_key_payload *epayload; struct key *mkey; const u8 *master_key; size_t master_keylen; char derived_key[HASH_SIZE]; char *ascii_buf; size_t asciiblob_len; int ret; epayload = dereference_key_locked(key); /* returns the hex encoded iv, encrypted-data, and hmac as ascii */ asciiblob_len = epayload->datablob_len + ivsize + 1 + roundup(epayload->decrypted_datalen, blksize) + (HASH_SIZE * 2); if (!buffer || buflen < asciiblob_len) return asciiblob_len; mkey = request_master_key(epayload, &master_key, &master_keylen); if (IS_ERR(mkey)) return PTR_ERR(mkey); ret = get_derived_key(derived_key, ENC_KEY, master_key, master_keylen); if (ret < 0) goto out; ret = derived_key_encrypt(epayload, derived_key, sizeof derived_key); if (ret < 0) goto out; ret = datablob_hmac_append(epayload, master_key, master_keylen); if (ret < 0) goto out; ascii_buf = datablob_format(epayload, asciiblob_len); if (!ascii_buf) { ret = -ENOMEM; goto out; } up_read(&mkey->sem); key_put(mkey); memzero_explicit(derived_key, sizeof(derived_key)); if (copy_to_user(buffer, ascii_buf, asciiblob_len) != 0) ret = -EFAULT; kzfree(ascii_buf); return asciiblob_len; out: up_read(&mkey->sem); key_put(mkey); memzero_explicit(derived_key, sizeof(derived_key)); return ret; } /* * encrypted_destroy - clear and free the key's payload */ static void encrypted_destroy(struct key *key) { kzfree(key->payload.data[0]); } struct key_type key_type_encrypted = { .name = "encrypted", .instantiate = encrypted_instantiate, .update = encrypted_update, .destroy = encrypted_destroy, .describe = user_describe, .read = encrypted_read, }; EXPORT_SYMBOL_GPL(key_type_encrypted); static int __init init_encrypted(void) { int ret; hash_tfm = crypto_alloc_shash(hash_alg, 0, CRYPTO_ALG_ASYNC); if (IS_ERR(hash_tfm)) { pr_err("encrypted_key: can't allocate %s transform: %ld\n", hash_alg, PTR_ERR(hash_tfm)); return PTR_ERR(hash_tfm); } ret = aes_get_sizes(); if (ret < 0) goto out; ret = register_key_type(&key_type_encrypted); if (ret < 0) goto out; return 0; out: crypto_free_shash(hash_tfm); return ret; } static void __exit cleanup_encrypted(void) { crypto_free_shash(hash_tfm); unregister_key_type(&key_type_encrypted); } late_initcall(init_encrypted); module_exit(cleanup_encrypted); MODULE_LICENSE("GPL");
./CrossVul/dataset_final_sorted/CWE-20/c/bad_2891_3
crossvul-cpp_data_bad_366_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % PPPP IIIII CCCC TTTTT % % P P I C T % % PPPP I C T % % P I C T % % P IIIII CCCC T % % % % % % Read/Write Apple Macintosh QuickDraw/PICT Format % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2018 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://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/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/cache.h" #include "MagickCore/color-private.h" #include "MagickCore/colormap.h" #include "MagickCore/colormap-private.h" #include "MagickCore/colorspace.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/composite.h" #include "MagickCore/constitute.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/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/profile.h" #include "MagickCore/resource_.h" #include "MagickCore/quantum-private.h" #include "MagickCore/static.h" #include "MagickCore/string_.h" #include "MagickCore/module.h" #include "MagickCore/transform.h" #include "MagickCore/utility.h" /* ImageMagick Macintosh PICT Methods. */ typedef struct _PICTCode { const char *name; ssize_t length; const char *description; } PICTCode; typedef struct _PICTPixmap { short version, pack_type; size_t pack_size, horizontal_resolution, vertical_resolution; short pixel_type, bits_per_pixel, component_count, component_size; size_t plane_bytes, table, reserved; } PICTPixmap; typedef struct _PICTRectangle { short top, left, bottom, right; } PICTRectangle; static const PICTCode codes[] = { /* 0x00 */ { "NOP", 0, "nop" }, /* 0x01 */ { "Clip", 0, "clip" }, /* 0x02 */ { "BkPat", 8, "background pattern" }, /* 0x03 */ { "TxFont", 2, "text font (word)" }, /* 0x04 */ { "TxFace", 1, "text face (byte)" }, /* 0x05 */ { "TxMode", 2, "text mode (word)" }, /* 0x06 */ { "SpExtra", 4, "space extra (fixed point)" }, /* 0x07 */ { "PnSize", 4, "pen size (point)" }, /* 0x08 */ { "PnMode", 2, "pen mode (word)" }, /* 0x09 */ { "PnPat", 8, "pen pattern" }, /* 0x0a */ { "FillPat", 8, "fill pattern" }, /* 0x0b */ { "OvSize", 4, "oval size (point)" }, /* 0x0c */ { "Origin", 4, "dh, dv (word)" }, /* 0x0d */ { "TxSize", 2, "text size (word)" }, /* 0x0e */ { "FgColor", 4, "foreground color (ssize_tword)" }, /* 0x0f */ { "BkColor", 4, "background color (ssize_tword)" }, /* 0x10 */ { "TxRatio", 8, "numerator (point), denominator (point)" }, /* 0x11 */ { "Version", 1, "version (byte)" }, /* 0x12 */ { "BkPixPat", 0, "color background pattern" }, /* 0x13 */ { "PnPixPat", 0, "color pen pattern" }, /* 0x14 */ { "FillPixPat", 0, "color fill pattern" }, /* 0x15 */ { "PnLocHFrac", 2, "fractional pen position" }, /* 0x16 */ { "ChExtra", 2, "extra for each character" }, /* 0x17 */ { "reserved", 0, "reserved for Apple use" }, /* 0x18 */ { "reserved", 0, "reserved for Apple use" }, /* 0x19 */ { "reserved", 0, "reserved for Apple use" }, /* 0x1a */ { "RGBFgCol", 6, "RGB foreColor" }, /* 0x1b */ { "RGBBkCol", 6, "RGB backColor" }, /* 0x1c */ { "HiliteMode", 0, "hilite mode flag" }, /* 0x1d */ { "HiliteColor", 6, "RGB hilite color" }, /* 0x1e */ { "DefHilite", 0, "Use default hilite color" }, /* 0x1f */ { "OpColor", 6, "RGB OpColor for arithmetic modes" }, /* 0x20 */ { "Line", 8, "pnLoc (point), newPt (point)" }, /* 0x21 */ { "LineFrom", 4, "newPt (point)" }, /* 0x22 */ { "ShortLine", 6, "pnLoc (point, dh, dv (-128 .. 127))" }, /* 0x23 */ { "ShortLineFrom", 2, "dh, dv (-128 .. 127)" }, /* 0x24 */ { "reserved", -1, "reserved for Apple use" }, /* 0x25 */ { "reserved", -1, "reserved for Apple use" }, /* 0x26 */ { "reserved", -1, "reserved for Apple use" }, /* 0x27 */ { "reserved", -1, "reserved for Apple use" }, /* 0x28 */ { "LongText", 0, "txLoc (point), count (0..255), text" }, /* 0x29 */ { "DHText", 0, "dh (0..255), count (0..255), text" }, /* 0x2a */ { "DVText", 0, "dv (0..255), count (0..255), text" }, /* 0x2b */ { "DHDVText", 0, "dh, dv (0..255), count (0..255), text" }, /* 0x2c */ { "reserved", -1, "reserved for Apple use" }, /* 0x2d */ { "reserved", -1, "reserved for Apple use" }, /* 0x2e */ { "reserved", -1, "reserved for Apple use" }, /* 0x2f */ { "reserved", -1, "reserved for Apple use" }, /* 0x30 */ { "frameRect", 8, "rect" }, /* 0x31 */ { "paintRect", 8, "rect" }, /* 0x32 */ { "eraseRect", 8, "rect" }, /* 0x33 */ { "invertRect", 8, "rect" }, /* 0x34 */ { "fillRect", 8, "rect" }, /* 0x35 */ { "reserved", 8, "reserved for Apple use" }, /* 0x36 */ { "reserved", 8, "reserved for Apple use" }, /* 0x37 */ { "reserved", 8, "reserved for Apple use" }, /* 0x38 */ { "frameSameRect", 0, "rect" }, /* 0x39 */ { "paintSameRect", 0, "rect" }, /* 0x3a */ { "eraseSameRect", 0, "rect" }, /* 0x3b */ { "invertSameRect", 0, "rect" }, /* 0x3c */ { "fillSameRect", 0, "rect" }, /* 0x3d */ { "reserved", 0, "reserved for Apple use" }, /* 0x3e */ { "reserved", 0, "reserved for Apple use" }, /* 0x3f */ { "reserved", 0, "reserved for Apple use" }, /* 0x40 */ { "frameRRect", 8, "rect" }, /* 0x41 */ { "paintRRect", 8, "rect" }, /* 0x42 */ { "eraseRRect", 8, "rect" }, /* 0x43 */ { "invertRRect", 8, "rect" }, /* 0x44 */ { "fillRRrect", 8, "rect" }, /* 0x45 */ { "reserved", 8, "reserved for Apple use" }, /* 0x46 */ { "reserved", 8, "reserved for Apple use" }, /* 0x47 */ { "reserved", 8, "reserved for Apple use" }, /* 0x48 */ { "frameSameRRect", 0, "rect" }, /* 0x49 */ { "paintSameRRect", 0, "rect" }, /* 0x4a */ { "eraseSameRRect", 0, "rect" }, /* 0x4b */ { "invertSameRRect", 0, "rect" }, /* 0x4c */ { "fillSameRRect", 0, "rect" }, /* 0x4d */ { "reserved", 0, "reserved for Apple use" }, /* 0x4e */ { "reserved", 0, "reserved for Apple use" }, /* 0x4f */ { "reserved", 0, "reserved for Apple use" }, /* 0x50 */ { "frameOval", 8, "rect" }, /* 0x51 */ { "paintOval", 8, "rect" }, /* 0x52 */ { "eraseOval", 8, "rect" }, /* 0x53 */ { "invertOval", 8, "rect" }, /* 0x54 */ { "fillOval", 8, "rect" }, /* 0x55 */ { "reserved", 8, "reserved for Apple use" }, /* 0x56 */ { "reserved", 8, "reserved for Apple use" }, /* 0x57 */ { "reserved", 8, "reserved for Apple use" }, /* 0x58 */ { "frameSameOval", 0, "rect" }, /* 0x59 */ { "paintSameOval", 0, "rect" }, /* 0x5a */ { "eraseSameOval", 0, "rect" }, /* 0x5b */ { "invertSameOval", 0, "rect" }, /* 0x5c */ { "fillSameOval", 0, "rect" }, /* 0x5d */ { "reserved", 0, "reserved for Apple use" }, /* 0x5e */ { "reserved", 0, "reserved for Apple use" }, /* 0x5f */ { "reserved", 0, "reserved for Apple use" }, /* 0x60 */ { "frameArc", 12, "rect, startAngle, arcAngle" }, /* 0x61 */ { "paintArc", 12, "rect, startAngle, arcAngle" }, /* 0x62 */ { "eraseArc", 12, "rect, startAngle, arcAngle" }, /* 0x63 */ { "invertArc", 12, "rect, startAngle, arcAngle" }, /* 0x64 */ { "fillArc", 12, "rect, startAngle, arcAngle" }, /* 0x65 */ { "reserved", 12, "reserved for Apple use" }, /* 0x66 */ { "reserved", 12, "reserved for Apple use" }, /* 0x67 */ { "reserved", 12, "reserved for Apple use" }, /* 0x68 */ { "frameSameArc", 4, "rect, startAngle, arcAngle" }, /* 0x69 */ { "paintSameArc", 4, "rect, startAngle, arcAngle" }, /* 0x6a */ { "eraseSameArc", 4, "rect, startAngle, arcAngle" }, /* 0x6b */ { "invertSameArc", 4, "rect, startAngle, arcAngle" }, /* 0x6c */ { "fillSameArc", 4, "rect, startAngle, arcAngle" }, /* 0x6d */ { "reserved", 4, "reserved for Apple use" }, /* 0x6e */ { "reserved", 4, "reserved for Apple use" }, /* 0x6f */ { "reserved", 4, "reserved for Apple use" }, /* 0x70 */ { "framePoly", 0, "poly" }, /* 0x71 */ { "paintPoly", 0, "poly" }, /* 0x72 */ { "erasePoly", 0, "poly" }, /* 0x73 */ { "invertPoly", 0, "poly" }, /* 0x74 */ { "fillPoly", 0, "poly" }, /* 0x75 */ { "reserved", 0, "reserved for Apple use" }, /* 0x76 */ { "reserved", 0, "reserved for Apple use" }, /* 0x77 */ { "reserved", 0, "reserved for Apple use" }, /* 0x78 */ { "frameSamePoly", 0, "poly (NYI)" }, /* 0x79 */ { "paintSamePoly", 0, "poly (NYI)" }, /* 0x7a */ { "eraseSamePoly", 0, "poly (NYI)" }, /* 0x7b */ { "invertSamePoly", 0, "poly (NYI)" }, /* 0x7c */ { "fillSamePoly", 0, "poly (NYI)" }, /* 0x7d */ { "reserved", 0, "reserved for Apple use" }, /* 0x7e */ { "reserved", 0, "reserved for Apple use" }, /* 0x7f */ { "reserved", 0, "reserved for Apple use" }, /* 0x80 */ { "frameRgn", 0, "region" }, /* 0x81 */ { "paintRgn", 0, "region" }, /* 0x82 */ { "eraseRgn", 0, "region" }, /* 0x83 */ { "invertRgn", 0, "region" }, /* 0x84 */ { "fillRgn", 0, "region" }, /* 0x85 */ { "reserved", 0, "reserved for Apple use" }, /* 0x86 */ { "reserved", 0, "reserved for Apple use" }, /* 0x87 */ { "reserved", 0, "reserved for Apple use" }, /* 0x88 */ { "frameSameRgn", 0, "region (NYI)" }, /* 0x89 */ { "paintSameRgn", 0, "region (NYI)" }, /* 0x8a */ { "eraseSameRgn", 0, "region (NYI)" }, /* 0x8b */ { "invertSameRgn", 0, "region (NYI)" }, /* 0x8c */ { "fillSameRgn", 0, "region (NYI)" }, /* 0x8d */ { "reserved", 0, "reserved for Apple use" }, /* 0x8e */ { "reserved", 0, "reserved for Apple use" }, /* 0x8f */ { "reserved", 0, "reserved for Apple use" }, /* 0x90 */ { "BitsRect", 0, "copybits, rect clipped" }, /* 0x91 */ { "BitsRgn", 0, "copybits, rgn clipped" }, /* 0x92 */ { "reserved", -1, "reserved for Apple use" }, /* 0x93 */ { "reserved", -1, "reserved for Apple use" }, /* 0x94 */ { "reserved", -1, "reserved for Apple use" }, /* 0x95 */ { "reserved", -1, "reserved for Apple use" }, /* 0x96 */ { "reserved", -1, "reserved for Apple use" }, /* 0x97 */ { "reserved", -1, "reserved for Apple use" }, /* 0x98 */ { "PackBitsRect", 0, "packed copybits, rect clipped" }, /* 0x99 */ { "PackBitsRgn", 0, "packed copybits, rgn clipped" }, /* 0x9a */ { "DirectBitsRect", 0, "PixMap, srcRect, dstRect, mode, PixData" }, /* 0x9b */ { "DirectBitsRgn", 0, "PixMap, srcRect, dstRect, mode, maskRgn, PixData" }, /* 0x9c */ { "reserved", -1, "reserved for Apple use" }, /* 0x9d */ { "reserved", -1, "reserved for Apple use" }, /* 0x9e */ { "reserved", -1, "reserved for Apple use" }, /* 0x9f */ { "reserved", -1, "reserved for Apple use" }, /* 0xa0 */ { "ShortComment", 2, "kind (word)" }, /* 0xa1 */ { "LongComment", 0, "kind (word), size (word), data" } }; /* Forward declarations. */ static MagickBooleanType WritePICTImage(const ImageInfo *,Image *,ExceptionInfo *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e c o d e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DecodeImage decompresses an image via Macintosh pack bits decoding for % Macintosh PICT images. % % The format of the DecodeImage method is: % % unsigned char *DecodeImage(Image *blob,Image *image, % size_t bytes_per_line,const int bits_per_pixel, % unsigned size_t extent) % % A description of each parameter follows: % % o image_info: the image info. % % o blob,image: the address of a structure of type Image. % % o bytes_per_line: This integer identifies the number of bytes in a % scanline. % % o bits_per_pixel: the number of bits in a pixel. % % o extent: the number of pixels allocated. % */ static unsigned char *ExpandBuffer(unsigned char *pixels, MagickSizeType *bytes_per_line,const unsigned int bits_per_pixel) { register ssize_t i; register unsigned char *p, *q; static unsigned char scanline[8*256]; p=pixels; q=scanline; switch (bits_per_pixel) { case 8: case 16: case 32: return(pixels); case 4: { for (i=0; i < (ssize_t) *bytes_per_line; i++) { *q++=(*p >> 4) & 0xff; *q++=(*p & 15); p++; } *bytes_per_line*=2; break; } case 2: { for (i=0; i < (ssize_t) *bytes_per_line; i++) { *q++=(*p >> 6) & 0x03; *q++=(*p >> 4) & 0x03; *q++=(*p >> 2) & 0x03; *q++=(*p & 3); p++; } *bytes_per_line*=4; break; } case 1: { for (i=0; i < (ssize_t) *bytes_per_line; i++) { *q++=(*p >> 7) & 0x01; *q++=(*p >> 6) & 0x01; *q++=(*p >> 5) & 0x01; *q++=(*p >> 4) & 0x01; *q++=(*p >> 3) & 0x01; *q++=(*p >> 2) & 0x01; *q++=(*p >> 1) & 0x01; *q++=(*p & 0x01); p++; } *bytes_per_line*=8; break; } default: break; } return(scanline); } static unsigned char *DecodeImage(Image *blob,Image *image, size_t bytes_per_line,const unsigned int bits_per_pixel,size_t *extent) { MagickBooleanType status; MagickSizeType number_pixels; register ssize_t i; register unsigned char *p, *q; size_t bytes_per_pixel, length, row_bytes, scanline_length, width; ssize_t count, j, y; unsigned char *pixels, *scanline; /* Determine pixel buffer size. */ if (bits_per_pixel <= 8) bytes_per_line&=0x7fff; width=image->columns; bytes_per_pixel=1; if (bits_per_pixel == 16) { bytes_per_pixel=2; width*=2; } else if (bits_per_pixel == 32) width*=image->alpha_trait ? 4 : 3; if (bytes_per_line == 0) bytes_per_line=width; row_bytes=(size_t) (image->columns | 0x8000); if (image->storage_class == DirectClass) row_bytes=(size_t) ((4*image->columns) | 0x8000); /* Allocate pixel and scanline buffer. */ pixels=(unsigned char *) AcquireQuantumMemory(image->rows,row_bytes* sizeof(*pixels)); if (pixels == (unsigned char *) NULL) return((unsigned char *) NULL); *extent=row_bytes*image->rows*sizeof(*pixels); (void) memset(pixels,0,*extent); scanline=(unsigned char *) AcquireQuantumMemory(row_bytes,2* sizeof(*scanline)); if (scanline == (unsigned char *) NULL) { pixels=(unsigned char *) RelinquishMagickMemory(pixels); return((unsigned char *) NULL); } (void) memset(scanline,0,2*row_bytes*sizeof(*scanline)); status=MagickTrue; if (bytes_per_line < 8) { /* Pixels are already uncompressed. */ for (y=0; y < (ssize_t) image->rows; y++) { q=pixels+y*width*GetPixelChannels(image); number_pixels=bytes_per_line; count=ReadBlob(blob,(size_t) number_pixels,scanline); if (count != (ssize_t) number_pixels) { status=MagickFalse; break; } p=ExpandBuffer(scanline,&number_pixels,bits_per_pixel); if ((q+number_pixels) > (pixels+(*extent))) { status=MagickFalse; break; } (void) memcpy(q,p,(size_t) number_pixels); } scanline=(unsigned char *) RelinquishMagickMemory(scanline); if (status == MagickFalse) pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(pixels); } /* Uncompress RLE pixels into uncompressed pixel buffer. */ for (y=0; y < (ssize_t) image->rows; y++) { q=pixels+y*width; if (bytes_per_line > 200) scanline_length=ReadBlobMSBShort(blob); else scanline_length=(size_t) ReadBlobByte(blob); if ((scanline_length >= row_bytes) || (scanline_length == 0)) { status=MagickFalse; break; } count=ReadBlob(blob,scanline_length,scanline); if (count != (ssize_t) scanline_length) { status=MagickFalse; break; } for (j=0; j < (ssize_t) scanline_length; ) if ((scanline[j] & 0x80) == 0) { length=(size_t) ((scanline[j] & 0xff)+1); number_pixels=length*bytes_per_pixel; p=ExpandBuffer(scanline+j+1,&number_pixels,bits_per_pixel); if ((q-pixels+number_pixels) <= *extent) (void) memcpy(q,p,(size_t) number_pixels); q+=number_pixels; j+=(ssize_t) (length*bytes_per_pixel+1); } else { length=(size_t) (((scanline[j] ^ 0xff) & 0xff)+2); number_pixels=bytes_per_pixel; p=ExpandBuffer(scanline+j+1,&number_pixels,bits_per_pixel); for (i=0; i < (ssize_t) length; i++) { if ((q-pixels+number_pixels) <= *extent) (void) memcpy(q,p,(size_t) number_pixels); q+=number_pixels; } j+=(ssize_t) bytes_per_pixel+1; } } scanline=(unsigned char *) RelinquishMagickMemory(scanline); if (status == MagickFalse) pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % E n c o d e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % EncodeImage compresses an image via Macintosh pack bits encoding % for Macintosh PICT images. % % The format of the EncodeImage method is: % % size_t EncodeImage(Image *image,const unsigned char *scanline, % const size_t bytes_per_line,unsigned char *pixels) % % A description of each parameter follows: % % o image: the address of a structure of type Image. % % o scanline: A pointer to an array of characters to pack. % % o bytes_per_line: the number of bytes in a scanline. % % o pixels: A pointer to an array of characters where the packed % characters are stored. % */ static size_t EncodeImage(Image *image,const unsigned char *scanline, const size_t bytes_per_line,unsigned char *pixels) { #define MaxCount 128 #define MaxPackbitsRunlength 128 register const unsigned char *p; register ssize_t i; register unsigned char *q; size_t length; ssize_t count, repeat_count, runlength; unsigned char index; /* Pack scanline. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(scanline != (unsigned char *) NULL); assert(pixels != (unsigned char *) NULL); count=0; runlength=0; p=scanline+(bytes_per_line-1); q=pixels; index=(*p); for (i=(ssize_t) bytes_per_line-1; i >= 0; i--) { if (index == *p) runlength++; else { if (runlength < 3) while (runlength > 0) { *q++=(unsigned char) index; runlength--; count++; if (count == MaxCount) { *q++=(unsigned char) (MaxCount-1); count-=MaxCount; } } else { if (count > 0) *q++=(unsigned char) (count-1); count=0; while (runlength > 0) { repeat_count=runlength; if (repeat_count > MaxPackbitsRunlength) repeat_count=MaxPackbitsRunlength; *q++=(unsigned char) index; *q++=(unsigned char) (257-repeat_count); runlength-=repeat_count; } } runlength=1; } index=(*p); p--; } if (runlength < 3) while (runlength > 0) { *q++=(unsigned char) index; runlength--; count++; if (count == MaxCount) { *q++=(unsigned char) (MaxCount-1); count-=MaxCount; } } else { if (count > 0) *q++=(unsigned char) (count-1); count=0; while (runlength > 0) { repeat_count=runlength; if (repeat_count > MaxPackbitsRunlength) repeat_count=MaxPackbitsRunlength; *q++=(unsigned char) index; *q++=(unsigned char) (257-repeat_count); runlength-=repeat_count; } } if (count > 0) *q++=(unsigned char) (count-1); /* Write the number of and the packed length. */ length=(size_t) (q-pixels); if (bytes_per_line > 200) { (void) WriteBlobMSBShort(image,(unsigned short) length); length+=2; } else { (void) WriteBlobByte(image,(unsigned char) length); length++; } while (q != pixels) { q--; (void) WriteBlobByte(image,*q); } return(length); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s P I C T % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsPICT()() returns MagickTrue if the image format type, identified by the % magick string, is PICT. % % The format of the ReadPICTImage method is: % % MagickBooleanType IsPICT(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 IsPICT(const unsigned char *magick,const size_t length) { if (length < 12) return(MagickFalse); /* Embedded OLE2 macintosh have "PICT" instead of 512 platform header. */ if (memcmp(magick,"PICT",4) == 0) return(MagickTrue); if (length < 528) return(MagickFalse); if (memcmp(magick+522,"\000\021\002\377\014\000",6) == 0) return(MagickTrue); return(MagickFalse); } #if !defined(macintosh) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d P I C T I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadPICTImage() reads an Apple Macintosh QuickDraw/PICT 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 ReadPICTImage method is: % % Image *ReadPICTImage(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 MagickBooleanType ReadPixmap(Image *image,PICTPixmap *pixmap) { pixmap->version=(short) ReadBlobMSBShort(image); pixmap->pack_type=(short) ReadBlobMSBShort(image); pixmap->pack_size=ReadBlobMSBLong(image); pixmap->horizontal_resolution=1UL*ReadBlobMSBShort(image); (void) ReadBlobMSBShort(image); pixmap->vertical_resolution=1UL*ReadBlobMSBShort(image); (void) ReadBlobMSBShort(image); pixmap->pixel_type=(short) ReadBlobMSBShort(image); pixmap->bits_per_pixel=(short) ReadBlobMSBShort(image); pixmap->component_count=(short) ReadBlobMSBShort(image); pixmap->component_size=(short) ReadBlobMSBShort(image); pixmap->plane_bytes=ReadBlobMSBLong(image); pixmap->table=ReadBlobMSBLong(image); pixmap->reserved=ReadBlobMSBLong(image); if ((EOFBlob(image) != MagickFalse) || (pixmap->bits_per_pixel <= 0) || (pixmap->bits_per_pixel > 32) || (pixmap->component_count <= 0) || (pixmap->component_count > 4) || (pixmap->component_size <= 0)) return(MagickFalse); return(MagickTrue); } static MagickBooleanType ReadRectangle(Image *image,PICTRectangle *rectangle) { rectangle->top=(short) ReadBlobMSBShort(image); rectangle->left=(short) ReadBlobMSBShort(image); rectangle->bottom=(short) ReadBlobMSBShort(image); rectangle->right=(short) ReadBlobMSBShort(image); if ((EOFBlob(image) != MagickFalse) || ((rectangle->bottom-rectangle->top) <= 0) || ((rectangle->right-rectangle->left) <= 0)) return(MagickFalse); return(MagickTrue); } static Image *ReadPICTImage(const ImageInfo *image_info, ExceptionInfo *exception) { #define ThrowPICTException(exception,message) \ { \ if (tile_image != (Image *) NULL) \ tile_image=DestroyImage(tile_image); \ if (read_info != (ImageInfo *) NULL) \ read_info=DestroyImageInfo(read_info); \ ThrowReaderException((exception),(message)); \ } char geometry[MagickPathExtent], header_ole[4]; Image *image, *tile_image; ImageInfo *read_info; int c, code; MagickBooleanType jpeg, status; PICTRectangle frame; PICTPixmap pixmap; Quantum index; register Quantum *q; register ssize_t i, x; size_t extent, length; ssize_t count, flags, j, version, y; StringInfo *profile; /* 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 PICT header. */ read_info=(ImageInfo *) NULL; tile_image=(Image *) NULL; pixmap.bits_per_pixel=0; pixmap.component_count=0; /* Skip header : 512 for standard PICT and 4, ie "PICT" for OLE2. */ header_ole[0]=ReadBlobByte(image); header_ole[1]=ReadBlobByte(image); header_ole[2]=ReadBlobByte(image); header_ole[3]=ReadBlobByte(image); if (!((header_ole[0] == 0x50) && (header_ole[1] == 0x49) && (header_ole[2] == 0x43) && (header_ole[3] == 0x54 ))) for (i=0; i < 508; i++) if (ReadBlobByte(image) == EOF) break; (void) ReadBlobMSBShort(image); /* skip picture size */ if (ReadRectangle(image,&frame) == MagickFalse) ThrowPICTException(CorruptImageError,"ImproperImageHeader"); while ((c=ReadBlobByte(image)) == 0) ; if (c != 0x11) ThrowPICTException(CorruptImageError,"ImproperImageHeader"); version=(ssize_t) ReadBlobByte(image); if (version == 2) { c=ReadBlobByte(image); if (c != 0xff) ThrowPICTException(CorruptImageError,"ImproperImageHeader"); } else if (version != 1) ThrowPICTException(CorruptImageError,"ImproperImageHeader"); if ((frame.left < 0) || (frame.right < 0) || (frame.top < 0) || (frame.bottom < 0) || (frame.left >= frame.right) || (frame.top >= frame.bottom)) ThrowPICTException(CorruptImageError,"ImproperImageHeader"); /* Create black canvas. */ flags=0; image->depth=8; image->columns=(size_t) (frame.right-frame.left); image->rows=(size_t) (frame.bottom-frame.top); image->resolution.x=DefaultResolution; image->resolution.y=DefaultResolution; image->units=UndefinedResolution; if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } status=SetImageExtent(image,image->columns,image->rows,exception); if (status != MagickFalse) status=ResetImagePixels(image,exception); if (status == MagickFalse) return(DestroyImageList(image)); /* Interpret PICT opcodes. */ jpeg=MagickFalse; for (code=0; EOFBlob(image) == MagickFalse; ) { if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; if ((version == 1) || ((TellBlob(image) % 2) != 0)) code=ReadBlobByte(image); if (version == 2) code=ReadBlobMSBSignedShort(image); if (code < 0) break; if (code == 0) continue; if (code > 0xa1) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"%04X:",code); } else { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " %04X %s: %s",code,codes[code].name,codes[code].description); switch (code) { case 0x01: { /* Clipping rectangle. */ length=ReadBlobMSBShort(image); if (length != 0x000a) { for (i=0; i < (ssize_t) (length-2); i++) if (ReadBlobByte(image) == EOF) break; break; } if (ReadRectangle(image,&frame) == MagickFalse) ThrowPICTException(CorruptImageError,"ImproperImageHeader"); if (((frame.left & 0x8000) != 0) || ((frame.top & 0x8000) != 0)) break; image->columns=(size_t) (frame.right-frame.left); image->rows=(size_t) (frame.bottom-frame.top); status=SetImageExtent(image,image->columns,image->rows,exception); if (status != MagickFalse) status=ResetImagePixels(image,exception); if (status == MagickFalse) return(DestroyImageList(image)); break; } case 0x12: case 0x13: case 0x14: { ssize_t pattern; size_t height, width; /* Skip pattern definition. */ pattern=(ssize_t) ReadBlobMSBShort(image); for (i=0; i < 8; i++) if (ReadBlobByte(image) == EOF) break; if (pattern == 2) { for (i=0; i < 5; i++) if (ReadBlobByte(image) == EOF) break; break; } if (pattern != 1) ThrowPICTException(CorruptImageError,"UnknownPatternType"); length=ReadBlobMSBShort(image); if (ReadRectangle(image,&frame) == MagickFalse) ThrowPICTException(CorruptImageError,"ImproperImageHeader"); if (ReadPixmap(image,&pixmap) == MagickFalse) ThrowPICTException(CorruptImageError,"ImproperImageHeader"); image->depth=(size_t) pixmap.component_size; image->resolution.x=1.0*pixmap.horizontal_resolution; image->resolution.y=1.0*pixmap.vertical_resolution; image->units=PixelsPerInchResolution; (void) ReadBlobMSBLong(image); flags=(ssize_t) ReadBlobMSBShort(image); length=ReadBlobMSBShort(image); for (i=0; i <= (ssize_t) length; i++) (void) ReadBlobMSBLong(image); width=(size_t) (frame.bottom-frame.top); height=(size_t) (frame.right-frame.left); if (pixmap.bits_per_pixel <= 8) length&=0x7fff; if (pixmap.bits_per_pixel == 16) width<<=1; if (length == 0) length=width; if (length < 8) { for (i=0; i < (ssize_t) (length*height); i++) if (ReadBlobByte(image) == EOF) break; } else for (i=0; i < (ssize_t) height; i++) { if (EOFBlob(image) != MagickFalse) break; if (length > 200) { for (j=0; j < (ssize_t) ReadBlobMSBShort(image); j++) if (ReadBlobByte(image) == EOF) break; } else for (j=0; j < (ssize_t) ReadBlobByte(image); j++) if (ReadBlobByte(image) == EOF) break; } break; } case 0x1b: { /* Initialize image background color. */ image->background_color.red=(Quantum) ScaleShortToQuantum(ReadBlobMSBShort(image)); image->background_color.green=(Quantum) ScaleShortToQuantum(ReadBlobMSBShort(image)); image->background_color.blue=(Quantum) ScaleShortToQuantum(ReadBlobMSBShort(image)); break; } case 0x70: case 0x71: case 0x72: case 0x73: case 0x74: case 0x75: case 0x76: case 0x77: { /* Skip polygon or region. */ length=ReadBlobMSBShort(image); for (i=0; i < (ssize_t) (length-2); i++) if (ReadBlobByte(image) == EOF) break; break; } case 0x90: case 0x91: case 0x98: case 0x99: case 0x9a: case 0x9b: { PICTRectangle source, destination; register unsigned char *p; size_t j; ssize_t bytes_per_line; unsigned char *pixels; /* Pixmap clipped by a rectangle. */ bytes_per_line=0; if ((code != 0x9a) && (code != 0x9b)) bytes_per_line=(ssize_t) ReadBlobMSBShort(image); else { (void) ReadBlobMSBShort(image); (void) ReadBlobMSBShort(image); (void) ReadBlobMSBShort(image); } if (ReadRectangle(image,&frame) == MagickFalse) ThrowPICTException(CorruptImageError,"ImproperImageHeader"); /* Initialize tile image. */ tile_image=CloneImage(image,(size_t) (frame.right-frame.left), (size_t) (frame.bottom-frame.top),MagickTrue,exception); if (tile_image == (Image *) NULL) ThrowPICTException(CorruptImageError,"ImproperImageHeader"); if ((code == 0x9a) || (code == 0x9b) || ((bytes_per_line & 0x8000) != 0)) { if (ReadPixmap(image,&pixmap) == MagickFalse) ThrowPICTException(CorruptImageError,"ImproperImageHeader"); tile_image->depth=(size_t) pixmap.component_size; tile_image->alpha_trait=pixmap.component_count == 4 ? BlendPixelTrait : UndefinedPixelTrait; tile_image->resolution.x=(double) pixmap.horizontal_resolution; tile_image->resolution.y=(double) pixmap.vertical_resolution; tile_image->units=PixelsPerInchResolution; if (tile_image->alpha_trait != UndefinedPixelTrait) (void) SetImageAlpha(tile_image,OpaqueAlpha,exception); } if ((code != 0x9a) && (code != 0x9b)) { /* Initialize colormap. */ tile_image->colors=2; if ((bytes_per_line & 0x8000) != 0) { (void) ReadBlobMSBLong(image); flags=(ssize_t) ReadBlobMSBShort(image); tile_image->colors=1UL*ReadBlobMSBShort(image)+1; } status=AcquireImageColormap(tile_image,tile_image->colors, exception); if (status == MagickFalse) ThrowPICTException(ResourceLimitError, "MemoryAllocationFailed"); if ((bytes_per_line & 0x8000) != 0) { for (i=0; i < (ssize_t) tile_image->colors; i++) { j=ReadBlobMSBShort(image) % tile_image->colors; if ((flags & 0x8000) != 0) j=(size_t) i; tile_image->colormap[j].red=(Quantum) ScaleShortToQuantum(ReadBlobMSBShort(image)); tile_image->colormap[j].green=(Quantum) ScaleShortToQuantum(ReadBlobMSBShort(image)); tile_image->colormap[j].blue=(Quantum) ScaleShortToQuantum(ReadBlobMSBShort(image)); } } else { for (i=0; i < (ssize_t) tile_image->colors; i++) { tile_image->colormap[i].red=(Quantum) (QuantumRange- tile_image->colormap[i].red); tile_image->colormap[i].green=(Quantum) (QuantumRange- tile_image->colormap[i].green); tile_image->colormap[i].blue=(Quantum) (QuantumRange- tile_image->colormap[i].blue); } } } if (EOFBlob(image) != MagickFalse) ThrowPICTException(CorruptImageError, "InsufficientImageDataInFile"); if (ReadRectangle(image,&source) == MagickFalse) ThrowPICTException(CorruptImageError,"ImproperImageHeader"); if (ReadRectangle(image,&destination) == MagickFalse) ThrowPICTException(CorruptImageError,"ImproperImageHeader"); (void) ReadBlobMSBShort(image); if ((code == 0x91) || (code == 0x99) || (code == 0x9b)) { /* Skip region. */ length=ReadBlobMSBShort(image); for (i=0; i < (ssize_t) (length-2); i++) if (ReadBlobByte(image) == EOF) break; } if ((code != 0x9a) && (code != 0x9b) && (bytes_per_line & 0x8000) == 0) pixels=DecodeImage(image,tile_image,(size_t) bytes_per_line,1, &extent); else pixels=DecodeImage(image,tile_image,(size_t) bytes_per_line, (unsigned int) pixmap.bits_per_pixel,&extent); if (pixels == (unsigned char *) NULL) ThrowPICTException(CorruptImageError,"UnableToUncompressImage"); /* Convert PICT tile image to pixel packets. */ p=pixels; for (y=0; y < (ssize_t) tile_image->rows; y++) { if (p > (pixels+extent+image->columns)) { pixels=(unsigned char *) RelinquishMagickMemory(pixels); ThrowPICTException(CorruptImageError,"NotEnoughPixelData"); } q=QueueAuthenticPixels(tile_image,0,y,tile_image->columns,1, exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) tile_image->columns; x++) { if (tile_image->storage_class == PseudoClass) { index=(Quantum) ConstrainColormapIndex(tile_image,(ssize_t) *p,exception); SetPixelIndex(tile_image,index,q); SetPixelRed(tile_image, tile_image->colormap[(ssize_t) index].red,q); SetPixelGreen(tile_image, tile_image->colormap[(ssize_t) index].green,q); SetPixelBlue(tile_image, tile_image->colormap[(ssize_t) index].blue,q); } else { if (pixmap.bits_per_pixel == 16) { i=(ssize_t) (*p++); j=(size_t) (*p); SetPixelRed(tile_image,ScaleCharToQuantum( (unsigned char) ((i & 0x7c) << 1)),q); SetPixelGreen(tile_image,ScaleCharToQuantum( (unsigned char) (((i & 0x03) << 6) | ((j & 0xe0) >> 2))),q); SetPixelBlue(tile_image,ScaleCharToQuantum( (unsigned char) ((j & 0x1f) << 3)),q); } else if (tile_image->alpha_trait == UndefinedPixelTrait) { if (p > (pixels+extent+2*image->columns)) ThrowPICTException(CorruptImageError, "NotEnoughPixelData"); SetPixelRed(tile_image,ScaleCharToQuantum(*p),q); SetPixelGreen(tile_image,ScaleCharToQuantum( *(p+tile_image->columns)),q); SetPixelBlue(tile_image,ScaleCharToQuantum( *(p+2*tile_image->columns)),q); } else { if (p > (pixels+extent+3*image->columns)) ThrowPICTException(CorruptImageError, "NotEnoughPixelData"); SetPixelAlpha(tile_image,ScaleCharToQuantum(*p),q); SetPixelRed(tile_image,ScaleCharToQuantum( *(p+tile_image->columns)),q); SetPixelGreen(tile_image,ScaleCharToQuantum( *(p+2*tile_image->columns)),q); SetPixelBlue(tile_image,ScaleCharToQuantum( *(p+3*tile_image->columns)),q); } } p++; q+=GetPixelChannels(tile_image); } if (SyncAuthenticPixels(tile_image,exception) == MagickFalse) break; if ((tile_image->storage_class == DirectClass) && (pixmap.bits_per_pixel != 16)) { p+=(pixmap.component_count-1)*tile_image->columns; if (p < pixels) break; } status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, tile_image->rows); if (status == MagickFalse) break; } pixels=(unsigned char *) RelinquishMagickMemory(pixels); if ((jpeg == MagickFalse) && (EOFBlob(image) == MagickFalse)) if ((code == 0x9a) || (code == 0x9b) || ((bytes_per_line & 0x8000) != 0)) (void) CompositeImage(image,tile_image,CopyCompositeOp, MagickTrue,(ssize_t) destination.left,(ssize_t) destination.top,exception); tile_image=DestroyImage(tile_image); break; } case 0xa1: { unsigned char *info; size_t type; /* Comment. */ type=ReadBlobMSBShort(image); length=ReadBlobMSBShort(image); if (length == 0) break; (void) ReadBlobMSBLong(image); length-=MagickMin(length,4); if (length == 0) break; info=(unsigned char *) AcquireQuantumMemory(length,sizeof(*info)); if (info == (unsigned char *) NULL) break; count=ReadBlob(image,length,info); if (count != (ssize_t) length) { info=(unsigned char *) RelinquishMagickMemory(info); ThrowPICTException(ResourceLimitError,"UnableToReadImageData"); } switch (type) { case 0xe0: { profile=BlobToStringInfo((const void *) NULL,length); SetStringInfoDatum(profile,info); status=SetImageProfile(image,"icc",profile,exception); profile=DestroyStringInfo(profile); if (status == MagickFalse) { info=(unsigned char *) RelinquishMagickMemory(info); ThrowPICTException(ResourceLimitError, "MemoryAllocationFailed"); } break; } case 0x1f2: { profile=BlobToStringInfo((const void *) NULL,length); SetStringInfoDatum(profile,info); status=SetImageProfile(image,"iptc",profile,exception); if (status == MagickFalse) { info=(unsigned char *) RelinquishMagickMemory(info); ThrowPICTException(ResourceLimitError, "MemoryAllocationFailed"); } profile=DestroyStringInfo(profile); break; } default: break; } info=(unsigned char *) RelinquishMagickMemory(info); break; } default: { /* Skip to next op code. */ if (codes[code].length == -1) (void) ReadBlobMSBShort(image); else for (i=0; i < (ssize_t) codes[code].length; i++) if (ReadBlobByte(image) == EOF) break; } } } if (code == 0xc00) { /* Skip header. */ for (i=0; i < 24; i++) if (ReadBlobByte(image) == EOF) break; continue; } if (((code >= 0xb0) && (code <= 0xcf)) || ((code >= 0x8000) && (code <= 0x80ff))) continue; if (code == 0x8200) { char filename[MaxTextExtent]; FILE *file; int unique_file; /* Embedded JPEG. */ jpeg=MagickTrue; read_info=CloneImageInfo(image_info); SetImageInfoBlob(read_info,(void *) NULL,0); file=(FILE *) NULL; unique_file=AcquireUniqueFileResource(filename); (void) FormatLocaleString(read_info->filename,MaxTextExtent,"jpeg:%s", filename); if (unique_file != -1) file=fdopen(unique_file,"wb"); if ((unique_file == -1) || (file == (FILE *) NULL)) { (void) RelinquishUniqueFileResource(read_info->filename); (void) CopyMagickString(image->filename,read_info->filename, MagickPathExtent); ThrowPICTException(FileOpenError,"UnableToCreateTemporaryFile"); } length=ReadBlobMSBLong(image); if (length > 154) { for (i=0; i < 6; i++) (void) ReadBlobMSBLong(image); if (ReadRectangle(image,&frame) == MagickFalse) { (void) fclose(file); (void) RelinquishUniqueFileResource(read_info->filename); ThrowPICTException(CorruptImageError,"ImproperImageHeader"); } for (i=0; i < 122; i++) if (ReadBlobByte(image) == EOF) break; for (i=0; i < (ssize_t) (length-154); i++) { c=ReadBlobByte(image); if (c == EOF) break; if (fputc(c,file) != c) break; } } (void) fclose(file); (void) close(unique_file); tile_image=ReadImage(read_info,exception); (void) RelinquishUniqueFileResource(filename); read_info=DestroyImageInfo(read_info); if (tile_image == (Image *) NULL) continue; (void) FormatLocaleString(geometry,MagickPathExtent,"%.20gx%.20g", (double) MagickMax(image->columns,tile_image->columns), (double) MagickMax(image->rows,tile_image->rows)); (void) SetImageExtent(image, MagickMax(image->columns,tile_image->columns), MagickMax(image->rows,tile_image->rows),exception); (void) TransformImageColorspace(image,tile_image->colorspace,exception); (void) CompositeImage(image,tile_image,CopyCompositeOp,MagickTrue, (ssize_t) frame.left,(ssize_t) frame.right,exception); image->compression=tile_image->compression; tile_image=DestroyImage(tile_image); continue; } if ((code == 0xff) || (code == 0xffff)) break; if (((code >= 0xd0) && (code <= 0xfe)) || ((code >= 0x8100) && (code <= 0xffff))) { /* Skip reserved. */ length=ReadBlobMSBShort(image); for (i=0; i < (ssize_t) length; i++) if (ReadBlobByte(image) == EOF) break; continue; } if ((code >= 0x100) && (code <= 0x7fff)) { /* Skip reserved. */ length=(size_t) ((code >> 7) & 0xff); for (i=0; i < (ssize_t) length; i++) if (ReadBlobByte(image) == EOF) break; continue; } } (void) CloseBlob(image); return(GetFirstImageInList(image)); } #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r P I C T I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterPICTImage() adds attributes for the PICT 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 RegisterPICTImage method is: % % size_t RegisterPICTImage(void) % */ ModuleExport size_t RegisterPICTImage(void) { MagickInfo *entry; entry=AcquireMagickInfo("PICT","PCT","Apple Macintosh QuickDraw/PICT"); entry->decoder=(DecodeImageHandler *) ReadPICTImage; entry->encoder=(EncodeImageHandler *) WritePICTImage; entry->flags^=CoderAdjoinFlag; entry->flags|=CoderEncoderSeekableStreamFlag; entry->magick=(IsImageFormatHandler *) IsPICT; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PICT","PICT","Apple Macintosh QuickDraw/PICT"); entry->decoder=(DecodeImageHandler *) ReadPICTImage; entry->encoder=(EncodeImageHandler *) WritePICTImage; entry->flags^=CoderAdjoinFlag; entry->flags|=CoderEncoderSeekableStreamFlag; entry->magick=(IsImageFormatHandler *) IsPICT; (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r P I C T I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterPICTImage() removes format registrations made by the % PICT module from the list of supported formats. % % The format of the UnregisterPICTImage method is: % % UnregisterPICTImage(void) % */ ModuleExport void UnregisterPICTImage(void) { (void) UnregisterMagickInfo("PCT"); (void) UnregisterMagickInfo("PICT"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e P I C T I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WritePICTImage() writes an image to a file in the Apple Macintosh % QuickDraw/PICT image format. % % The format of the WritePICTImage method is: % % MagickBooleanType WritePICTImage(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 WritePICTImage(const ImageInfo *image_info, Image *image,ExceptionInfo *exception) { #define MaxCount 128 #define PictCropRegionOp 0x01 #define PictEndOfPictureOp 0xff #define PictJPEGOp 0x8200 #define PictInfoOp 0x0C00 #define PictInfoSize 512 #define PictPixmapOp 0x9A #define PictPICTOp 0x98 #define PictVersion 0x11 const StringInfo *profile; double x_resolution, y_resolution; MagickBooleanType status; MagickOffsetType offset; PICTPixmap pixmap; PICTRectangle bounds, crop_rectangle, destination_rectangle, frame_rectangle, size_rectangle, source_rectangle; register const Quantum *p; register ssize_t i, x; size_t bytes_per_line, count, row_bytes, storage_class; ssize_t y; unsigned char *buffer, *packed_scanline, *scanline; unsigned short base_address, transfer_mode; /* Open output 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); if ((image->columns > 65535L) || (image->rows > 65535L)) ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit"); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); (void) TransformImageColorspace(image,sRGBColorspace,exception); /* Initialize image info. */ size_rectangle.top=0; size_rectangle.left=0; size_rectangle.bottom=(short) image->rows; size_rectangle.right=(short) image->columns; frame_rectangle=size_rectangle; crop_rectangle=size_rectangle; source_rectangle=size_rectangle; destination_rectangle=size_rectangle; base_address=0xff; row_bytes=image->columns; bounds.top=0; bounds.left=0; bounds.bottom=(short) image->rows; bounds.right=(short) image->columns; pixmap.version=0; pixmap.pack_type=0; pixmap.pack_size=0; pixmap.pixel_type=0; pixmap.bits_per_pixel=8; pixmap.component_count=1; pixmap.component_size=8; pixmap.plane_bytes=0; pixmap.table=0; pixmap.reserved=0; transfer_mode=0; x_resolution=image->resolution.x != 0.0 ? image->resolution.x : DefaultResolution; y_resolution=image->resolution.y != 0.0 ? image->resolution.y : DefaultResolution; storage_class=image->storage_class; if (image_info->compression == JPEGCompression) storage_class=DirectClass; if (storage_class == DirectClass) { pixmap.component_count=image->alpha_trait != UndefinedPixelTrait ? 4 : 3; pixmap.pixel_type=16; pixmap.bits_per_pixel=32; pixmap.pack_type=0x04; transfer_mode=0x40; row_bytes=4*image->columns; } /* Allocate memory. */ bytes_per_line=image->columns; if (storage_class == DirectClass) bytes_per_line*=image->alpha_trait != UndefinedPixelTrait ? 4 : 3; buffer=(unsigned char *) AcquireQuantumMemory(PictInfoSize,sizeof(*buffer)); packed_scanline=(unsigned char *) AcquireQuantumMemory((size_t) (row_bytes+MaxCount),sizeof(*packed_scanline)); scanline=(unsigned char *) AcquireQuantumMemory(row_bytes,sizeof(*scanline)); if ((buffer == (unsigned char *) NULL) || (packed_scanline == (unsigned char *) NULL) || (scanline == (unsigned char *) NULL)) { if (scanline != (unsigned char *) NULL) scanline=(unsigned char *) RelinquishMagickMemory(scanline); if (packed_scanline != (unsigned char *) NULL) packed_scanline=(unsigned char *) RelinquishMagickMemory( packed_scanline); if (buffer != (unsigned char *) NULL) buffer=(unsigned char *) RelinquishMagickMemory(buffer); ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } (void) memset(scanline,0,row_bytes); (void) memset(packed_scanline,0,(size_t) (row_bytes+MaxCount)); /* Write header, header size, size bounding box, version, and reserved. */ (void) memset(buffer,0,PictInfoSize); (void) WriteBlob(image,PictInfoSize,buffer); (void) WriteBlobMSBShort(image,0); (void) WriteBlobMSBShort(image,(unsigned short) size_rectangle.top); (void) WriteBlobMSBShort(image,(unsigned short) size_rectangle.left); (void) WriteBlobMSBShort(image,(unsigned short) size_rectangle.bottom); (void) WriteBlobMSBShort(image,(unsigned short) size_rectangle.right); (void) WriteBlobMSBShort(image,PictVersion); (void) WriteBlobMSBShort(image,0x02ff); /* version #2 */ (void) WriteBlobMSBShort(image,PictInfoOp); (void) WriteBlobMSBLong(image,0xFFFE0000U); /* Write full size of the file, resolution, frame bounding box, and reserved. */ (void) WriteBlobMSBShort(image,(unsigned short) x_resolution); (void) WriteBlobMSBShort(image,0x0000); (void) WriteBlobMSBShort(image,(unsigned short) y_resolution); (void) WriteBlobMSBShort(image,0x0000); (void) WriteBlobMSBShort(image,(unsigned short) frame_rectangle.top); (void) WriteBlobMSBShort(image,(unsigned short) frame_rectangle.left); (void) WriteBlobMSBShort(image,(unsigned short) frame_rectangle.bottom); (void) WriteBlobMSBShort(image,(unsigned short) frame_rectangle.right); (void) WriteBlobMSBLong(image,0x00000000L); profile=GetImageProfile(image,"iptc"); if (profile != (StringInfo *) NULL) { (void) WriteBlobMSBShort(image,0xa1); (void) WriteBlobMSBShort(image,0x1f2); (void) WriteBlobMSBShort(image,(unsigned short) (GetStringInfoLength(profile)+4)); (void) WriteBlobString(image,"8BIM"); (void) WriteBlob(image,GetStringInfoLength(profile), GetStringInfoDatum(profile)); } profile=GetImageProfile(image,"icc"); if (profile != (StringInfo *) NULL) { (void) WriteBlobMSBShort(image,0xa1); (void) WriteBlobMSBShort(image,0xe0); (void) WriteBlobMSBShort(image,(unsigned short) (GetStringInfoLength(profile)+4)); (void) WriteBlobMSBLong(image,0x00000000U); (void) WriteBlob(image,GetStringInfoLength(profile), GetStringInfoDatum(profile)); (void) WriteBlobMSBShort(image,0xa1); (void) WriteBlobMSBShort(image,0xe0); (void) WriteBlobMSBShort(image,4); (void) WriteBlobMSBLong(image,0x00000002U); } /* Write crop region opcode and crop bounding box. */ (void) WriteBlobMSBShort(image,PictCropRegionOp); (void) WriteBlobMSBShort(image,0xa); (void) WriteBlobMSBShort(image,(unsigned short) crop_rectangle.top); (void) WriteBlobMSBShort(image,(unsigned short) crop_rectangle.left); (void) WriteBlobMSBShort(image,(unsigned short) crop_rectangle.bottom); (void) WriteBlobMSBShort(image,(unsigned short) crop_rectangle.right); if (image_info->compression == JPEGCompression) { Image *jpeg_image; ImageInfo *jpeg_info; size_t length; unsigned char *blob; jpeg_image=CloneImage(image,0,0,MagickTrue,exception); if (jpeg_image == (Image *) NULL) { (void) CloseBlob(image); return(MagickFalse); } jpeg_info=CloneImageInfo(image_info); (void) CopyMagickString(jpeg_info->magick,"JPEG",MagickPathExtent); length=0; blob=(unsigned char *) ImageToBlob(jpeg_info,jpeg_image,&length, exception); jpeg_info=DestroyImageInfo(jpeg_info); if (blob == (unsigned char *) NULL) return(MagickFalse); jpeg_image=DestroyImage(jpeg_image); (void) WriteBlobMSBShort(image,PictJPEGOp); (void) WriteBlobMSBLong(image,(unsigned int) length+154); (void) WriteBlobMSBShort(image,0x0000); (void) WriteBlobMSBLong(image,0x00010000U); (void) WriteBlobMSBLong(image,0x00000000U); (void) WriteBlobMSBLong(image,0x00000000U); (void) WriteBlobMSBLong(image,0x00000000U); (void) WriteBlobMSBLong(image,0x00010000U); (void) WriteBlobMSBLong(image,0x00000000U); (void) WriteBlobMSBLong(image,0x00000000U); (void) WriteBlobMSBLong(image,0x00000000U); (void) WriteBlobMSBLong(image,0x40000000U); (void) WriteBlobMSBLong(image,0x00000000U); (void) WriteBlobMSBLong(image,0x00000000U); (void) WriteBlobMSBLong(image,0x00000000U); (void) WriteBlobMSBLong(image,0x00400000U); (void) WriteBlobMSBShort(image,0x0000); (void) WriteBlobMSBShort(image,(unsigned short) image->rows); (void) WriteBlobMSBShort(image,(unsigned short) image->columns); (void) WriteBlobMSBShort(image,0x0000); (void) WriteBlobMSBShort(image,768); (void) WriteBlobMSBShort(image,0x0000); (void) WriteBlobMSBLong(image,0x00000000U); (void) WriteBlobMSBLong(image,0x00566A70U); (void) WriteBlobMSBLong(image,0x65670000U); (void) WriteBlobMSBLong(image,0x00000000U); (void) WriteBlobMSBLong(image,0x00000001U); (void) WriteBlobMSBLong(image,0x00016170U); (void) WriteBlobMSBLong(image,0x706C0000U); (void) WriteBlobMSBLong(image,0x00000000U); (void) WriteBlobMSBShort(image,768); (void) WriteBlobMSBShort(image,(unsigned short) image->columns); (void) WriteBlobMSBShort(image,(unsigned short) image->rows); (void) WriteBlobMSBShort(image,(unsigned short) x_resolution); (void) WriteBlobMSBShort(image,0x0000); (void) WriteBlobMSBShort(image,(unsigned short) y_resolution); (void) WriteBlobMSBShort(image,0x0000); (void) WriteBlobMSBLong(image,length); (void) WriteBlobMSBShort(image,0x0001); (void) WriteBlobMSBLong(image,0x0B466F74U); (void) WriteBlobMSBLong(image,0x6F202D20U); (void) WriteBlobMSBLong(image,0x4A504547U); (void) WriteBlobMSBLong(image,0x00000000U); (void) WriteBlobMSBLong(image,0x00000000U); (void) WriteBlobMSBLong(image,0x00000000U); (void) WriteBlobMSBLong(image,0x00000000U); (void) WriteBlobMSBLong(image,0x00000000U); (void) WriteBlobMSBLong(image,0x0018FFFFU); (void) WriteBlob(image,length,blob); if ((length & 0x01) != 0) (void) WriteBlobByte(image,'\0'); blob=(unsigned char *) RelinquishMagickMemory(blob); } /* Write picture opcode, row bytes, and picture bounding box, and version. */ if (storage_class == PseudoClass) (void) WriteBlobMSBShort(image,PictPICTOp); else { (void) WriteBlobMSBShort(image,PictPixmapOp); (void) WriteBlobMSBLong(image,(unsigned int) base_address); } (void) WriteBlobMSBShort(image,(unsigned short) (row_bytes | 0x8000)); (void) WriteBlobMSBShort(image,(unsigned short) bounds.top); (void) WriteBlobMSBShort(image,(unsigned short) bounds.left); (void) WriteBlobMSBShort(image,(unsigned short) bounds.bottom); (void) WriteBlobMSBShort(image,(unsigned short) bounds.right); /* Write pack type, pack size, resolution, pixel type, and pixel size. */ (void) WriteBlobMSBShort(image,(unsigned short) pixmap.version); (void) WriteBlobMSBShort(image,(unsigned short) pixmap.pack_type); (void) WriteBlobMSBLong(image,(unsigned int) pixmap.pack_size); (void) WriteBlobMSBShort(image,(unsigned short) (x_resolution+0.5)); (void) WriteBlobMSBShort(image,0x0000); (void) WriteBlobMSBShort(image,(unsigned short) (y_resolution+0.5)); (void) WriteBlobMSBShort(image,0x0000); (void) WriteBlobMSBShort(image,(unsigned short) pixmap.pixel_type); (void) WriteBlobMSBShort(image,(unsigned short) pixmap.bits_per_pixel); /* Write component count, size, plane bytes, table size, and reserved. */ (void) WriteBlobMSBShort(image,(unsigned short) pixmap.component_count); (void) WriteBlobMSBShort(image,(unsigned short) pixmap.component_size); (void) WriteBlobMSBLong(image,(unsigned int) pixmap.plane_bytes); (void) WriteBlobMSBLong(image,(unsigned int) pixmap.table); (void) WriteBlobMSBLong(image,(unsigned int) pixmap.reserved); if (storage_class == PseudoClass) { /* Write image colormap. */ (void) WriteBlobMSBLong(image,0x00000000L); /* color seed */ (void) WriteBlobMSBShort(image,0L); /* color flags */ (void) WriteBlobMSBShort(image,(unsigned short) (image->colors-1)); for (i=0; i < (ssize_t) image->colors; i++) { (void) WriteBlobMSBShort(image,(unsigned short) i); (void) WriteBlobMSBShort(image,ScaleQuantumToShort( image->colormap[i].red)); (void) WriteBlobMSBShort(image,ScaleQuantumToShort( image->colormap[i].green)); (void) WriteBlobMSBShort(image,ScaleQuantumToShort( image->colormap[i].blue)); } } /* Write source and destination rectangle. */ (void) WriteBlobMSBShort(image,(unsigned short) source_rectangle.top); (void) WriteBlobMSBShort(image,(unsigned short) source_rectangle.left); (void) WriteBlobMSBShort(image,(unsigned short) source_rectangle.bottom); (void) WriteBlobMSBShort(image,(unsigned short) source_rectangle.right); (void) WriteBlobMSBShort(image,(unsigned short) destination_rectangle.top); (void) WriteBlobMSBShort(image,(unsigned short) destination_rectangle.left); (void) WriteBlobMSBShort(image,(unsigned short) destination_rectangle.bottom); (void) WriteBlobMSBShort(image,(unsigned short) destination_rectangle.right); (void) WriteBlobMSBShort(image,(unsigned short) transfer_mode); /* Write picture data. */ count=0; if (storage_class == PseudoClass) 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++) { scanline[x]=(unsigned char) GetPixelIndex(image,p); p+=GetPixelChannels(image); } count+=EncodeImage(image,scanline,(size_t) (row_bytes & 0x7FFF), packed_scanline); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } else if (image_info->compression == JPEGCompression) { (void) memset(scanline,0,row_bytes); for (y=0; y < (ssize_t) image->rows; y++) count+=EncodeImage(image,scanline,(size_t) (row_bytes & 0x7FFF), packed_scanline); } else { register unsigned char *blue, *green, *opacity, *red; red=scanline; green=scanline+image->columns; blue=scanline+2*image->columns; opacity=scanline+3*image->columns; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; red=scanline; green=scanline+image->columns; blue=scanline+2*image->columns; if (image->alpha_trait != UndefinedPixelTrait) { opacity=scanline; red=scanline+image->columns; green=scanline+2*image->columns; blue=scanline+3*image->columns; } for (x=0; x < (ssize_t) image->columns; x++) { *red++=ScaleQuantumToChar(GetPixelRed(image,p)); *green++=ScaleQuantumToChar(GetPixelGreen(image,p)); *blue++=ScaleQuantumToChar(GetPixelBlue(image,p)); if (image->alpha_trait != UndefinedPixelTrait) *opacity++=ScaleQuantumToChar((Quantum) (GetPixelAlpha(image,p))); p+=GetPixelChannels(image); } count+=EncodeImage(image,scanline,bytes_per_line,packed_scanline); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } if ((count & 0x01) != 0) (void) WriteBlobByte(image,'\0'); (void) WriteBlobMSBShort(image,PictEndOfPictureOp); offset=TellBlob(image); offset=SeekBlob(image,512,SEEK_SET); (void) WriteBlobMSBShort(image,(unsigned short) offset); scanline=(unsigned char *) RelinquishMagickMemory(scanline); packed_scanline=(unsigned char *) RelinquishMagickMemory(packed_scanline); buffer=(unsigned char *) RelinquishMagickMemory(buffer); (void) CloseBlob(image); return(MagickTrue); }
./CrossVul/dataset_final_sorted/CWE-20/c/bad_366_0
crossvul-cpp_data_good_2024_0
/* Copyright (C) 2009 Red Hat, Inc. * Author: Michael S. Tsirkin <mst@redhat.com> * * This work is licensed under the terms of the GNU GPL, version 2. * * virtio-net server in host kernel. */ #include <linux/compat.h> #include <linux/eventfd.h> #include <linux/vhost.h> #include <linux/virtio_net.h> #include <linux/miscdevice.h> #include <linux/module.h> #include <linux/moduleparam.h> #include <linux/mutex.h> #include <linux/workqueue.h> #include <linux/file.h> #include <linux/slab.h> #include <linux/net.h> #include <linux/if_packet.h> #include <linux/if_arp.h> #include <linux/if_tun.h> #include <linux/if_macvlan.h> #include <linux/if_vlan.h> #include <net/sock.h> #include "vhost.h" static int experimental_zcopytx = 1; module_param(experimental_zcopytx, int, 0444); MODULE_PARM_DESC(experimental_zcopytx, "Enable Zero Copy TX;" " 1 -Enable; 0 - Disable"); /* Max number of bytes transferred before requeueing the job. * Using this limit prevents one virtqueue from starving others. */ #define VHOST_NET_WEIGHT 0x80000 /* MAX number of TX used buffers for outstanding zerocopy */ #define VHOST_MAX_PEND 128 #define VHOST_GOODCOPY_LEN 256 /* * For transmit, used buffer len is unused; we override it to track buffer * status internally; used for zerocopy tx only. */ /* Lower device DMA failed */ #define VHOST_DMA_FAILED_LEN 3 /* Lower device DMA done */ #define VHOST_DMA_DONE_LEN 2 /* Lower device DMA in progress */ #define VHOST_DMA_IN_PROGRESS 1 /* Buffer unused */ #define VHOST_DMA_CLEAR_LEN 0 #define VHOST_DMA_IS_DONE(len) ((len) >= VHOST_DMA_DONE_LEN) enum { VHOST_NET_FEATURES = VHOST_FEATURES | (1ULL << VHOST_NET_F_VIRTIO_NET_HDR) | (1ULL << VIRTIO_NET_F_MRG_RXBUF), }; enum { VHOST_NET_VQ_RX = 0, VHOST_NET_VQ_TX = 1, VHOST_NET_VQ_MAX = 2, }; struct vhost_net_ubuf_ref { /* refcount follows semantics similar to kref: * 0: object is released * 1: no outstanding ubufs * >1: outstanding ubufs */ atomic_t refcount; wait_queue_head_t wait; struct vhost_virtqueue *vq; }; struct vhost_net_virtqueue { struct vhost_virtqueue vq; /* hdr is used to store the virtio header. * Since each iovec has >= 1 byte length, we never need more than * header length entries to store the header. */ struct iovec hdr[sizeof(struct virtio_net_hdr_mrg_rxbuf)]; size_t vhost_hlen; size_t sock_hlen; /* vhost zerocopy support fields below: */ /* last used idx for outstanding DMA zerocopy buffers */ int upend_idx; /* first used idx for DMA done zerocopy buffers */ int done_idx; /* an array of userspace buffers info */ struct ubuf_info *ubuf_info; /* Reference counting for outstanding ubufs. * Protected by vq mutex. Writers must also take device mutex. */ struct vhost_net_ubuf_ref *ubufs; }; struct vhost_net { struct vhost_dev dev; struct vhost_net_virtqueue vqs[VHOST_NET_VQ_MAX]; struct vhost_poll poll[VHOST_NET_VQ_MAX]; /* Number of TX recently submitted. * Protected by tx vq lock. */ unsigned tx_packets; /* Number of times zerocopy TX recently failed. * Protected by tx vq lock. */ unsigned tx_zcopy_err; /* Flush in progress. Protected by tx vq lock. */ bool tx_flush; }; static unsigned vhost_net_zcopy_mask __read_mostly; static void vhost_net_enable_zcopy(int vq) { vhost_net_zcopy_mask |= 0x1 << vq; } static struct vhost_net_ubuf_ref * vhost_net_ubuf_alloc(struct vhost_virtqueue *vq, bool zcopy) { struct vhost_net_ubuf_ref *ubufs; /* No zero copy backend? Nothing to count. */ if (!zcopy) return NULL; ubufs = kmalloc(sizeof(*ubufs), GFP_KERNEL); if (!ubufs) return ERR_PTR(-ENOMEM); atomic_set(&ubufs->refcount, 1); init_waitqueue_head(&ubufs->wait); ubufs->vq = vq; return ubufs; } static int vhost_net_ubuf_put(struct vhost_net_ubuf_ref *ubufs) { int r = atomic_sub_return(1, &ubufs->refcount); if (unlikely(!r)) wake_up(&ubufs->wait); return r; } static void vhost_net_ubuf_put_and_wait(struct vhost_net_ubuf_ref *ubufs) { vhost_net_ubuf_put(ubufs); wait_event(ubufs->wait, !atomic_read(&ubufs->refcount)); } static void vhost_net_ubuf_put_wait_and_free(struct vhost_net_ubuf_ref *ubufs) { vhost_net_ubuf_put_and_wait(ubufs); kfree(ubufs); } static void vhost_net_clear_ubuf_info(struct vhost_net *n) { int i; for (i = 0; i < VHOST_NET_VQ_MAX; ++i) { kfree(n->vqs[i].ubuf_info); n->vqs[i].ubuf_info = NULL; } } static int vhost_net_set_ubuf_info(struct vhost_net *n) { bool zcopy; int i; for (i = 0; i < VHOST_NET_VQ_MAX; ++i) { zcopy = vhost_net_zcopy_mask & (0x1 << i); if (!zcopy) continue; n->vqs[i].ubuf_info = kmalloc(sizeof(*n->vqs[i].ubuf_info) * UIO_MAXIOV, GFP_KERNEL); if (!n->vqs[i].ubuf_info) goto err; } return 0; err: vhost_net_clear_ubuf_info(n); return -ENOMEM; } static void vhost_net_vq_reset(struct vhost_net *n) { int i; vhost_net_clear_ubuf_info(n); for (i = 0; i < VHOST_NET_VQ_MAX; i++) { n->vqs[i].done_idx = 0; n->vqs[i].upend_idx = 0; n->vqs[i].ubufs = NULL; n->vqs[i].vhost_hlen = 0; n->vqs[i].sock_hlen = 0; } } static void vhost_net_tx_packet(struct vhost_net *net) { ++net->tx_packets; if (net->tx_packets < 1024) return; net->tx_packets = 0; net->tx_zcopy_err = 0; } static void vhost_net_tx_err(struct vhost_net *net) { ++net->tx_zcopy_err; } static bool vhost_net_tx_select_zcopy(struct vhost_net *net) { /* TX flush waits for outstanding DMAs to be done. * Don't start new DMAs. */ return !net->tx_flush && net->tx_packets / 64 >= net->tx_zcopy_err; } static bool vhost_sock_zcopy(struct socket *sock) { return unlikely(experimental_zcopytx) && sock_flag(sock->sk, SOCK_ZEROCOPY); } /* Pop first len bytes from iovec. Return number of segments used. */ static int move_iovec_hdr(struct iovec *from, struct iovec *to, size_t len, int iov_count) { int seg = 0; size_t size; while (len && seg < iov_count) { size = min(from->iov_len, len); to->iov_base = from->iov_base; to->iov_len = size; from->iov_len -= size; from->iov_base += size; len -= size; ++from; ++to; ++seg; } return seg; } /* Copy iovec entries for len bytes from iovec. */ static void copy_iovec_hdr(const struct iovec *from, struct iovec *to, size_t len, int iovcount) { int seg = 0; size_t size; while (len && seg < iovcount) { size = min(from->iov_len, len); to->iov_base = from->iov_base; to->iov_len = size; len -= size; ++from; ++to; ++seg; } } /* In case of DMA done not in order in lower device driver for some reason. * upend_idx is used to track end of used idx, done_idx is used to track head * of used idx. Once lower device DMA done contiguously, we will signal KVM * guest used idx. */ static void vhost_zerocopy_signal_used(struct vhost_net *net, struct vhost_virtqueue *vq) { struct vhost_net_virtqueue *nvq = container_of(vq, struct vhost_net_virtqueue, vq); int i, add; int j = 0; for (i = nvq->done_idx; i != nvq->upend_idx; i = (i + 1) % UIO_MAXIOV) { if (vq->heads[i].len == VHOST_DMA_FAILED_LEN) vhost_net_tx_err(net); if (VHOST_DMA_IS_DONE(vq->heads[i].len)) { vq->heads[i].len = VHOST_DMA_CLEAR_LEN; ++j; } else break; } while (j) { add = min(UIO_MAXIOV - nvq->done_idx, j); vhost_add_used_and_signal_n(vq->dev, vq, &vq->heads[nvq->done_idx], add); nvq->done_idx = (nvq->done_idx + add) % UIO_MAXIOV; j -= add; } } static void vhost_zerocopy_callback(struct ubuf_info *ubuf, bool success) { struct vhost_net_ubuf_ref *ubufs = ubuf->ctx; struct vhost_virtqueue *vq = ubufs->vq; int cnt; rcu_read_lock_bh(); /* set len to mark this desc buffers done DMA */ vq->heads[ubuf->desc].len = success ? VHOST_DMA_DONE_LEN : VHOST_DMA_FAILED_LEN; cnt = vhost_net_ubuf_put(ubufs); /* * Trigger polling thread if guest stopped submitting new buffers: * in this case, the refcount after decrement will eventually reach 1. * We also trigger polling periodically after each 16 packets * (the value 16 here is more or less arbitrary, it's tuned to trigger * less than 10% of times). */ if (cnt <= 1 || !(cnt % 16)) vhost_poll_queue(&vq->poll); rcu_read_unlock_bh(); } /* Expects to be always run from workqueue - which acts as * read-size critical section for our kind of RCU. */ static void handle_tx(struct vhost_net *net) { struct vhost_net_virtqueue *nvq = &net->vqs[VHOST_NET_VQ_TX]; struct vhost_virtqueue *vq = &nvq->vq; unsigned out, in, s; int head; struct msghdr msg = { .msg_name = NULL, .msg_namelen = 0, .msg_control = NULL, .msg_controllen = 0, .msg_iov = vq->iov, .msg_flags = MSG_DONTWAIT, }; size_t len, total_len = 0; int err; size_t hdr_size; struct socket *sock; struct vhost_net_ubuf_ref *uninitialized_var(ubufs); bool zcopy, zcopy_used; mutex_lock(&vq->mutex); sock = vq->private_data; if (!sock) goto out; vhost_disable_notify(&net->dev, vq); hdr_size = nvq->vhost_hlen; zcopy = nvq->ubufs; for (;;) { /* Release DMAs done buffers first */ if (zcopy) vhost_zerocopy_signal_used(net, vq); /* If more outstanding DMAs, queue the work. * Handle upend_idx wrap around */ if (unlikely((nvq->upend_idx + vq->num - VHOST_MAX_PEND) % UIO_MAXIOV == nvq->done_idx)) break; head = vhost_get_vq_desc(&net->dev, vq, vq->iov, ARRAY_SIZE(vq->iov), &out, &in, NULL, NULL); /* On error, stop handling until the next kick. */ if (unlikely(head < 0)) break; /* Nothing new? Wait for eventfd to tell us they refilled. */ if (head == vq->num) { if (unlikely(vhost_enable_notify(&net->dev, vq))) { vhost_disable_notify(&net->dev, vq); continue; } break; } if (in) { vq_err(vq, "Unexpected descriptor format for TX: " "out %d, int %d\n", out, in); break; } /* Skip header. TODO: support TSO. */ s = move_iovec_hdr(vq->iov, nvq->hdr, hdr_size, out); msg.msg_iovlen = out; len = iov_length(vq->iov, out); /* Sanity check */ if (!len) { vq_err(vq, "Unexpected header len for TX: " "%zd expected %zd\n", iov_length(nvq->hdr, s), hdr_size); break; } zcopy_used = zcopy && len >= VHOST_GOODCOPY_LEN && (nvq->upend_idx + 1) % UIO_MAXIOV != nvq->done_idx && vhost_net_tx_select_zcopy(net); /* use msg_control to pass vhost zerocopy ubuf info to skb */ if (zcopy_used) { struct ubuf_info *ubuf; ubuf = nvq->ubuf_info + nvq->upend_idx; vq->heads[nvq->upend_idx].id = head; vq->heads[nvq->upend_idx].len = VHOST_DMA_IN_PROGRESS; ubuf->callback = vhost_zerocopy_callback; ubuf->ctx = nvq->ubufs; ubuf->desc = nvq->upend_idx; msg.msg_control = ubuf; msg.msg_controllen = sizeof(ubuf); ubufs = nvq->ubufs; atomic_inc(&ubufs->refcount); nvq->upend_idx = (nvq->upend_idx + 1) % UIO_MAXIOV; } else { msg.msg_control = NULL; ubufs = NULL; } /* TODO: Check specific error and bomb out unless ENOBUFS? */ err = sock->ops->sendmsg(NULL, sock, &msg, len); if (unlikely(err < 0)) { if (zcopy_used) { vhost_net_ubuf_put(ubufs); nvq->upend_idx = ((unsigned)nvq->upend_idx - 1) % UIO_MAXIOV; } vhost_discard_vq_desc(vq, 1); break; } if (err != len) pr_debug("Truncated TX packet: " " len %d != %zd\n", err, len); if (!zcopy_used) vhost_add_used_and_signal(&net->dev, vq, head, 0); else vhost_zerocopy_signal_used(net, vq); total_len += len; vhost_net_tx_packet(net); if (unlikely(total_len >= VHOST_NET_WEIGHT)) { vhost_poll_queue(&vq->poll); break; } } out: mutex_unlock(&vq->mutex); } static int peek_head_len(struct sock *sk) { struct sk_buff *head; int len = 0; unsigned long flags; spin_lock_irqsave(&sk->sk_receive_queue.lock, flags); head = skb_peek(&sk->sk_receive_queue); if (likely(head)) { len = head->len; if (vlan_tx_tag_present(head)) len += VLAN_HLEN; } spin_unlock_irqrestore(&sk->sk_receive_queue.lock, flags); return len; } /* This is a multi-buffer version of vhost_get_desc, that works if * vq has read descriptors only. * @vq - the relevant virtqueue * @datalen - data length we'll be reading * @iovcount - returned count of io vectors we fill * @log - vhost log * @log_num - log offset * @quota - headcount quota, 1 for big buffer * returns number of buffer heads allocated, negative on error */ static int get_rx_bufs(struct vhost_virtqueue *vq, struct vring_used_elem *heads, int datalen, unsigned *iovcount, struct vhost_log *log, unsigned *log_num, unsigned int quota) { unsigned int out, in; int seg = 0; int headcount = 0; unsigned d; int r, nlogs = 0; while (datalen > 0 && headcount < quota) { if (unlikely(seg >= UIO_MAXIOV)) { r = -ENOBUFS; goto err; } d = vhost_get_vq_desc(vq->dev, vq, vq->iov + seg, ARRAY_SIZE(vq->iov) - seg, &out, &in, log, log_num); if (d == vq->num) { r = 0; goto err; } if (unlikely(out || in <= 0)) { vq_err(vq, "unexpected descriptor format for RX: " "out %d, in %d\n", out, in); r = -EINVAL; goto err; } if (unlikely(log)) { nlogs += *log_num; log += *log_num; } heads[headcount].id = d; heads[headcount].len = iov_length(vq->iov + seg, in); datalen -= heads[headcount].len; ++headcount; seg += in; } heads[headcount - 1].len += datalen; *iovcount = seg; if (unlikely(log)) *log_num = nlogs; /* Detect overrun */ if (unlikely(datalen > 0)) { r = UIO_MAXIOV + 1; goto err; } return headcount; err: vhost_discard_vq_desc(vq, headcount); return r; } /* Expects to be always run from workqueue - which acts as * read-size critical section for our kind of RCU. */ static void handle_rx(struct vhost_net *net) { struct vhost_net_virtqueue *nvq = &net->vqs[VHOST_NET_VQ_RX]; struct vhost_virtqueue *vq = &nvq->vq; unsigned uninitialized_var(in), log; struct vhost_log *vq_log; struct msghdr msg = { .msg_name = NULL, .msg_namelen = 0, .msg_control = NULL, /* FIXME: get and handle RX aux data. */ .msg_controllen = 0, .msg_iov = vq->iov, .msg_flags = MSG_DONTWAIT, }; struct virtio_net_hdr_mrg_rxbuf hdr = { .hdr.flags = 0, .hdr.gso_type = VIRTIO_NET_HDR_GSO_NONE }; size_t total_len = 0; int err, mergeable; s16 headcount; size_t vhost_hlen, sock_hlen; size_t vhost_len, sock_len; struct socket *sock; mutex_lock(&vq->mutex); sock = vq->private_data; if (!sock) goto out; vhost_disable_notify(&net->dev, vq); vhost_hlen = nvq->vhost_hlen; sock_hlen = nvq->sock_hlen; vq_log = unlikely(vhost_has_feature(&net->dev, VHOST_F_LOG_ALL)) ? vq->log : NULL; mergeable = vhost_has_feature(&net->dev, VIRTIO_NET_F_MRG_RXBUF); while ((sock_len = peek_head_len(sock->sk))) { sock_len += sock_hlen; vhost_len = sock_len + vhost_hlen; headcount = get_rx_bufs(vq, vq->heads, vhost_len, &in, vq_log, &log, likely(mergeable) ? UIO_MAXIOV : 1); /* On error, stop handling until the next kick. */ if (unlikely(headcount < 0)) break; /* On overrun, truncate and discard */ if (unlikely(headcount > UIO_MAXIOV)) { msg.msg_iovlen = 1; err = sock->ops->recvmsg(NULL, sock, &msg, 1, MSG_DONTWAIT | MSG_TRUNC); pr_debug("Discarded rx packet: len %zd\n", sock_len); continue; } /* OK, now we need to know about added descriptors. */ if (!headcount) { if (unlikely(vhost_enable_notify(&net->dev, vq))) { /* They have slipped one in as we were * doing that: check again. */ vhost_disable_notify(&net->dev, vq); continue; } /* Nothing new? Wait for eventfd to tell us * they refilled. */ break; } /* We don't need to be notified again. */ if (unlikely((vhost_hlen))) /* Skip header. TODO: support TSO. */ move_iovec_hdr(vq->iov, nvq->hdr, vhost_hlen, in); else /* Copy the header for use in VIRTIO_NET_F_MRG_RXBUF: * needed because recvmsg can modify msg_iov. */ copy_iovec_hdr(vq->iov, nvq->hdr, sock_hlen, in); msg.msg_iovlen = in; err = sock->ops->recvmsg(NULL, sock, &msg, sock_len, MSG_DONTWAIT | MSG_TRUNC); /* Userspace might have consumed the packet meanwhile: * it's not supposed to do this usually, but might be hard * to prevent. Discard data we got (if any) and keep going. */ if (unlikely(err != sock_len)) { pr_debug("Discarded rx packet: " " len %d, expected %zd\n", err, sock_len); vhost_discard_vq_desc(vq, headcount); continue; } if (unlikely(vhost_hlen) && memcpy_toiovecend(nvq->hdr, (unsigned char *)&hdr, 0, vhost_hlen)) { vq_err(vq, "Unable to write vnet_hdr at addr %p\n", vq->iov->iov_base); break; } /* TODO: Should check and handle checksum. */ if (likely(mergeable) && memcpy_toiovecend(nvq->hdr, (unsigned char *)&headcount, offsetof(typeof(hdr), num_buffers), sizeof hdr.num_buffers)) { vq_err(vq, "Failed num_buffers write"); vhost_discard_vq_desc(vq, headcount); break; } vhost_add_used_and_signal_n(&net->dev, vq, vq->heads, headcount); if (unlikely(vq_log)) vhost_log_write(vq, vq_log, log, vhost_len); total_len += vhost_len; if (unlikely(total_len >= VHOST_NET_WEIGHT)) { vhost_poll_queue(&vq->poll); break; } } out: mutex_unlock(&vq->mutex); } static void handle_tx_kick(struct vhost_work *work) { struct vhost_virtqueue *vq = container_of(work, struct vhost_virtqueue, poll.work); struct vhost_net *net = container_of(vq->dev, struct vhost_net, dev); handle_tx(net); } static void handle_rx_kick(struct vhost_work *work) { struct vhost_virtqueue *vq = container_of(work, struct vhost_virtqueue, poll.work); struct vhost_net *net = container_of(vq->dev, struct vhost_net, dev); handle_rx(net); } static void handle_tx_net(struct vhost_work *work) { struct vhost_net *net = container_of(work, struct vhost_net, poll[VHOST_NET_VQ_TX].work); handle_tx(net); } static void handle_rx_net(struct vhost_work *work) { struct vhost_net *net = container_of(work, struct vhost_net, poll[VHOST_NET_VQ_RX].work); handle_rx(net); } static int vhost_net_open(struct inode *inode, struct file *f) { struct vhost_net *n = kmalloc(sizeof *n, GFP_KERNEL); struct vhost_dev *dev; struct vhost_virtqueue **vqs; int i; if (!n) return -ENOMEM; vqs = kmalloc(VHOST_NET_VQ_MAX * sizeof(*vqs), GFP_KERNEL); if (!vqs) { kfree(n); return -ENOMEM; } dev = &n->dev; vqs[VHOST_NET_VQ_TX] = &n->vqs[VHOST_NET_VQ_TX].vq; vqs[VHOST_NET_VQ_RX] = &n->vqs[VHOST_NET_VQ_RX].vq; n->vqs[VHOST_NET_VQ_TX].vq.handle_kick = handle_tx_kick; n->vqs[VHOST_NET_VQ_RX].vq.handle_kick = handle_rx_kick; for (i = 0; i < VHOST_NET_VQ_MAX; i++) { n->vqs[i].ubufs = NULL; n->vqs[i].ubuf_info = NULL; n->vqs[i].upend_idx = 0; n->vqs[i].done_idx = 0; n->vqs[i].vhost_hlen = 0; n->vqs[i].sock_hlen = 0; } vhost_dev_init(dev, vqs, VHOST_NET_VQ_MAX); vhost_poll_init(n->poll + VHOST_NET_VQ_TX, handle_tx_net, POLLOUT, dev); vhost_poll_init(n->poll + VHOST_NET_VQ_RX, handle_rx_net, POLLIN, dev); f->private_data = n; return 0; } static void vhost_net_disable_vq(struct vhost_net *n, struct vhost_virtqueue *vq) { struct vhost_net_virtqueue *nvq = container_of(vq, struct vhost_net_virtqueue, vq); struct vhost_poll *poll = n->poll + (nvq - n->vqs); if (!vq->private_data) return; vhost_poll_stop(poll); } static int vhost_net_enable_vq(struct vhost_net *n, struct vhost_virtqueue *vq) { struct vhost_net_virtqueue *nvq = container_of(vq, struct vhost_net_virtqueue, vq); struct vhost_poll *poll = n->poll + (nvq - n->vqs); struct socket *sock; sock = vq->private_data; if (!sock) return 0; return vhost_poll_start(poll, sock->file); } static struct socket *vhost_net_stop_vq(struct vhost_net *n, struct vhost_virtqueue *vq) { struct socket *sock; mutex_lock(&vq->mutex); sock = vq->private_data; vhost_net_disable_vq(n, vq); vq->private_data = NULL; mutex_unlock(&vq->mutex); return sock; } static void vhost_net_stop(struct vhost_net *n, struct socket **tx_sock, struct socket **rx_sock) { *tx_sock = vhost_net_stop_vq(n, &n->vqs[VHOST_NET_VQ_TX].vq); *rx_sock = vhost_net_stop_vq(n, &n->vqs[VHOST_NET_VQ_RX].vq); } static void vhost_net_flush_vq(struct vhost_net *n, int index) { vhost_poll_flush(n->poll + index); vhost_poll_flush(&n->vqs[index].vq.poll); } static void vhost_net_flush(struct vhost_net *n) { vhost_net_flush_vq(n, VHOST_NET_VQ_TX); vhost_net_flush_vq(n, VHOST_NET_VQ_RX); if (n->vqs[VHOST_NET_VQ_TX].ubufs) { mutex_lock(&n->vqs[VHOST_NET_VQ_TX].vq.mutex); n->tx_flush = true; mutex_unlock(&n->vqs[VHOST_NET_VQ_TX].vq.mutex); /* Wait for all lower device DMAs done. */ vhost_net_ubuf_put_and_wait(n->vqs[VHOST_NET_VQ_TX].ubufs); mutex_lock(&n->vqs[VHOST_NET_VQ_TX].vq.mutex); n->tx_flush = false; atomic_set(&n->vqs[VHOST_NET_VQ_TX].ubufs->refcount, 1); mutex_unlock(&n->vqs[VHOST_NET_VQ_TX].vq.mutex); } } static int vhost_net_release(struct inode *inode, struct file *f) { struct vhost_net *n = f->private_data; struct socket *tx_sock; struct socket *rx_sock; vhost_net_stop(n, &tx_sock, &rx_sock); vhost_net_flush(n); vhost_dev_stop(&n->dev); vhost_dev_cleanup(&n->dev, false); vhost_net_vq_reset(n); if (tx_sock) fput(tx_sock->file); if (rx_sock) fput(rx_sock->file); /* Make sure no callbacks are outstanding */ synchronize_rcu_bh(); /* We do an extra flush before freeing memory, * since jobs can re-queue themselves. */ vhost_net_flush(n); kfree(n->dev.vqs); kfree(n); return 0; } static struct socket *get_raw_socket(int fd) { struct { struct sockaddr_ll sa; char buf[MAX_ADDR_LEN]; } uaddr; int uaddr_len = sizeof uaddr, r; struct socket *sock = sockfd_lookup(fd, &r); if (!sock) return ERR_PTR(-ENOTSOCK); /* Parameter checking */ if (sock->sk->sk_type != SOCK_RAW) { r = -ESOCKTNOSUPPORT; goto err; } r = sock->ops->getname(sock, (struct sockaddr *)&uaddr.sa, &uaddr_len, 0); if (r) goto err; if (uaddr.sa.sll_family != AF_PACKET) { r = -EPFNOSUPPORT; goto err; } return sock; err: fput(sock->file); return ERR_PTR(r); } static struct socket *get_tap_socket(int fd) { struct file *file = fget(fd); struct socket *sock; if (!file) return ERR_PTR(-EBADF); sock = tun_get_socket(file); if (!IS_ERR(sock)) return sock; sock = macvtap_get_socket(file); if (IS_ERR(sock)) fput(file); return sock; } static struct socket *get_socket(int fd) { struct socket *sock; /* special case to disable backend */ if (fd == -1) return NULL; sock = get_raw_socket(fd); if (!IS_ERR(sock)) return sock; sock = get_tap_socket(fd); if (!IS_ERR(sock)) return sock; return ERR_PTR(-ENOTSOCK); } static long vhost_net_set_backend(struct vhost_net *n, unsigned index, int fd) { struct socket *sock, *oldsock; struct vhost_virtqueue *vq; struct vhost_net_virtqueue *nvq; struct vhost_net_ubuf_ref *ubufs, *oldubufs = NULL; int r; mutex_lock(&n->dev.mutex); r = vhost_dev_check_owner(&n->dev); if (r) goto err; if (index >= VHOST_NET_VQ_MAX) { r = -ENOBUFS; goto err; } vq = &n->vqs[index].vq; nvq = &n->vqs[index]; mutex_lock(&vq->mutex); /* Verify that ring has been setup correctly. */ if (!vhost_vq_access_ok(vq)) { r = -EFAULT; goto err_vq; } sock = get_socket(fd); if (IS_ERR(sock)) { r = PTR_ERR(sock); goto err_vq; } /* start polling new socket */ oldsock = vq->private_data; if (sock != oldsock) { ubufs = vhost_net_ubuf_alloc(vq, sock && vhost_sock_zcopy(sock)); if (IS_ERR(ubufs)) { r = PTR_ERR(ubufs); goto err_ubufs; } vhost_net_disable_vq(n, vq); vq->private_data = sock; r = vhost_init_used(vq); if (r) goto err_used; r = vhost_net_enable_vq(n, vq); if (r) goto err_used; oldubufs = nvq->ubufs; nvq->ubufs = ubufs; n->tx_packets = 0; n->tx_zcopy_err = 0; n->tx_flush = false; } mutex_unlock(&vq->mutex); if (oldubufs) { vhost_net_ubuf_put_wait_and_free(oldubufs); mutex_lock(&vq->mutex); vhost_zerocopy_signal_used(n, vq); mutex_unlock(&vq->mutex); } if (oldsock) { vhost_net_flush_vq(n, index); fput(oldsock->file); } mutex_unlock(&n->dev.mutex); return 0; err_used: vq->private_data = oldsock; vhost_net_enable_vq(n, vq); if (ubufs) vhost_net_ubuf_put_wait_and_free(ubufs); err_ubufs: fput(sock->file); err_vq: mutex_unlock(&vq->mutex); err: mutex_unlock(&n->dev.mutex); return r; } static long vhost_net_reset_owner(struct vhost_net *n) { struct socket *tx_sock = NULL; struct socket *rx_sock = NULL; long err; struct vhost_memory *memory; mutex_lock(&n->dev.mutex); err = vhost_dev_check_owner(&n->dev); if (err) goto done; memory = vhost_dev_reset_owner_prepare(); if (!memory) { err = -ENOMEM; goto done; } vhost_net_stop(n, &tx_sock, &rx_sock); vhost_net_flush(n); vhost_dev_reset_owner(&n->dev, memory); vhost_net_vq_reset(n); done: mutex_unlock(&n->dev.mutex); if (tx_sock) fput(tx_sock->file); if (rx_sock) fput(rx_sock->file); return err; } static int vhost_net_set_features(struct vhost_net *n, u64 features) { size_t vhost_hlen, sock_hlen, hdr_len; int i; hdr_len = (features & (1 << VIRTIO_NET_F_MRG_RXBUF)) ? sizeof(struct virtio_net_hdr_mrg_rxbuf) : sizeof(struct virtio_net_hdr); if (features & (1 << VHOST_NET_F_VIRTIO_NET_HDR)) { /* vhost provides vnet_hdr */ vhost_hlen = hdr_len; sock_hlen = 0; } else { /* socket provides vnet_hdr */ vhost_hlen = 0; sock_hlen = hdr_len; } mutex_lock(&n->dev.mutex); if ((features & (1 << VHOST_F_LOG_ALL)) && !vhost_log_access_ok(&n->dev)) { mutex_unlock(&n->dev.mutex); return -EFAULT; } n->dev.acked_features = features; smp_wmb(); for (i = 0; i < VHOST_NET_VQ_MAX; ++i) { mutex_lock(&n->vqs[i].vq.mutex); n->vqs[i].vhost_hlen = vhost_hlen; n->vqs[i].sock_hlen = sock_hlen; mutex_unlock(&n->vqs[i].vq.mutex); } vhost_net_flush(n); mutex_unlock(&n->dev.mutex); return 0; } static long vhost_net_set_owner(struct vhost_net *n) { int r; mutex_lock(&n->dev.mutex); if (vhost_dev_has_owner(&n->dev)) { r = -EBUSY; goto out; } r = vhost_net_set_ubuf_info(n); if (r) goto out; r = vhost_dev_set_owner(&n->dev); if (r) vhost_net_clear_ubuf_info(n); vhost_net_flush(n); out: mutex_unlock(&n->dev.mutex); return r; } static long vhost_net_ioctl(struct file *f, unsigned int ioctl, unsigned long arg) { struct vhost_net *n = f->private_data; void __user *argp = (void __user *)arg; u64 __user *featurep = argp; struct vhost_vring_file backend; u64 features; int r; switch (ioctl) { case VHOST_NET_SET_BACKEND: if (copy_from_user(&backend, argp, sizeof backend)) return -EFAULT; return vhost_net_set_backend(n, backend.index, backend.fd); case VHOST_GET_FEATURES: features = VHOST_NET_FEATURES; if (copy_to_user(featurep, &features, sizeof features)) return -EFAULT; return 0; case VHOST_SET_FEATURES: if (copy_from_user(&features, featurep, sizeof features)) return -EFAULT; if (features & ~VHOST_NET_FEATURES) return -EOPNOTSUPP; return vhost_net_set_features(n, features); case VHOST_RESET_OWNER: return vhost_net_reset_owner(n); case VHOST_SET_OWNER: return vhost_net_set_owner(n); default: mutex_lock(&n->dev.mutex); r = vhost_dev_ioctl(&n->dev, ioctl, argp); if (r == -ENOIOCTLCMD) r = vhost_vring_ioctl(&n->dev, ioctl, argp); else vhost_net_flush(n); mutex_unlock(&n->dev.mutex); return r; } } #ifdef CONFIG_COMPAT static long vhost_net_compat_ioctl(struct file *f, unsigned int ioctl, unsigned long arg) { return vhost_net_ioctl(f, ioctl, (unsigned long)compat_ptr(arg)); } #endif static const struct file_operations vhost_net_fops = { .owner = THIS_MODULE, .release = vhost_net_release, .unlocked_ioctl = vhost_net_ioctl, #ifdef CONFIG_COMPAT .compat_ioctl = vhost_net_compat_ioctl, #endif .open = vhost_net_open, .llseek = noop_llseek, }; static struct miscdevice vhost_net_misc = { .minor = VHOST_NET_MINOR, .name = "vhost-net", .fops = &vhost_net_fops, }; static int vhost_net_init(void) { if (experimental_zcopytx) vhost_net_enable_zcopy(VHOST_NET_VQ_TX); return misc_register(&vhost_net_misc); } module_init(vhost_net_init); static void vhost_net_exit(void) { misc_deregister(&vhost_net_misc); } module_exit(vhost_net_exit); MODULE_VERSION("0.0.1"); MODULE_LICENSE("GPL v2"); MODULE_AUTHOR("Michael S. Tsirkin"); MODULE_DESCRIPTION("Host kernel accelerator for virtio net"); MODULE_ALIAS_MISCDEV(VHOST_NET_MINOR); MODULE_ALIAS("devname:vhost-net");
./CrossVul/dataset_final_sorted/CWE-20/c/good_2024_0
crossvul-cpp_data_bad_2789_0
/* mboxlist.c -- Mailbox list manipulation routines * * Copyright (c) 1994-2008 Carnegie Mellon University. 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. The name "Carnegie Mellon University" must not be used to * endorse or promote products derived from this software without * prior written permission. For permission or any legal * details, please contact * Carnegie Mellon University * Center for Technology Transfer and Enterprise Creation * 4615 Forbes Avenue * Suite 302 * Pittsburgh, PA 15213 * (412) 268-7393, fax: (412) 268-7395 * innovation@andrew.cmu.edu * * 4. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by Computing Services * at Carnegie Mellon University (http://www.cmu.edu/computing/)." * * CARNEGIE MELLON UNIVERSITY DISCLAIMS ALL WARRANTIES WITH REGARD TO * THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS, IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY BE LIABLE * FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN * AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <config.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #include <sys/types.h> #include <sys/stat.h> #include <sys/uio.h> #include <fcntl.h> #include <syslog.h> #include <sys/ipc.h> #include <sys/msg.h> #include "acl.h" #include "annotate.h" #include "glob.h" #include "assert.h" #include "global.h" #include "cyrusdb.h" #include "util.h" #include "mailbox.h" #include "mboxevent.h" #include "exitcodes.h" #include "xmalloc.h" #include "xstrlcpy.h" #include "partlist.h" #include "xstrlcat.h" #include "user.h" /* generated headers are not necessarily in current directory */ #include "imap/imap_err.h" #include "mboxname.h" #include "mupdate-client.h" #include "mboxlist.h" #include "quota.h" #include "sync_log.h" #define DB config_mboxlist_db #define SUBDB config_subscription_db cyrus_acl_canonproc_t mboxlist_ensureOwnerRights; static struct db *mbdb; static int mboxlist_dbopen = 0; static int mboxlist_opensubs(const char *userid, struct db **ret); static void mboxlist_closesubs(struct db *sub); static int mboxlist_rmquota(const mbentry_t *mbentry, void *rock); static int mboxlist_changequota(const mbentry_t *mbentry, void *rock); EXPORTED mbentry_t *mboxlist_entry_create(void) { mbentry_t *ret = xzmalloc(sizeof(mbentry_t)); /* xxx - initialiser functions here? */ return ret; } EXPORTED mbentry_t *mboxlist_entry_copy(const mbentry_t *src) { mbentry_t *copy = mboxlist_entry_create(); copy->name = xstrdupnull(src->name); copy->ext_name = xstrdupnull(src->ext_name); copy->mtime = src->mtime; copy->uidvalidity = src->uidvalidity; copy->mbtype = src->mbtype; copy->foldermodseq = src->foldermodseq; copy->partition = xstrdupnull(src->partition); copy->server = xstrdupnull(src->server); copy->acl = xstrdupnull(src->acl); copy->uniqueid = xstrdupnull(src->uniqueid); copy->legacy_specialuse = xstrdupnull(src->legacy_specialuse); return copy; } EXPORTED void mboxlist_entry_free(mbentry_t **mbentryptr) { mbentry_t *mbentry = *mbentryptr; /* idempotent */ if (!mbentry) return; free(mbentry->name); free(mbentry->ext_name); free(mbentry->partition); free(mbentry->server); free(mbentry->acl); free(mbentry->uniqueid); free(mbentry->legacy_specialuse); free(mbentry); *mbentryptr = NULL; } static void _write_acl(struct dlist *dl, const char *aclstr) { const char *p, *q; struct dlist *al = dlist_newkvlist(dl, "A"); p = aclstr; while (p && *p) { char *name,*val; q = strchr(p, '\t'); if (!q) break; name = xstrndup(p, q-p); q++; p = strchr(q, '\t'); if (p) { val = xstrndup(q, p-q); p++; } else val = xstrdup(q); dlist_setatom(al, name, val); free(name); free(val); } } EXPORTED const char *mboxlist_mbtype_to_string(uint32_t mbtype) { static struct buf buf = BUF_INITIALIZER; buf_reset(&buf); if (mbtype & MBTYPE_DELETED) buf_putc(&buf, 'd'); if (mbtype & MBTYPE_MOVING) buf_putc(&buf, 'm'); if (mbtype & MBTYPE_NETNEWS) buf_putc(&buf, 'n'); if (mbtype & MBTYPE_REMOTE) buf_putc(&buf, 'r'); if (mbtype & MBTYPE_RESERVE) buf_putc(&buf, 'z'); if (mbtype & MBTYPE_CALENDAR) buf_putc(&buf, 'c'); if (mbtype & MBTYPE_COLLECTION) buf_putc(&buf, 'b'); if (mbtype & MBTYPE_ADDRESSBOOK) buf_putc(&buf, 'a'); return buf_cstring(&buf); } static char *mboxlist_entry_cstring(const mbentry_t *mbentry) { struct buf buf = BUF_INITIALIZER; struct dlist *dl = dlist_newkvlist(NULL, mbentry->name); if (mbentry->acl) _write_acl(dl, mbentry->acl); if (mbentry->uniqueid) dlist_setatom(dl, "I", mbentry->uniqueid); if (mbentry->partition) dlist_setatom(dl, "P", mbentry->partition); if (mbentry->server) dlist_setatom(dl, "S", mbentry->server); if (mbentry->mbtype) dlist_setatom(dl, "T", mboxlist_mbtype_to_string(mbentry->mbtype)); if (mbentry->uidvalidity) dlist_setnum32(dl, "V", mbentry->uidvalidity); if (mbentry->foldermodseq) dlist_setnum64(dl, "F", mbentry->foldermodseq); dlist_setdate(dl, "M", time(NULL)); dlist_printbuf(dl, 0, &buf); dlist_free(&dl); return buf_release(&buf); } EXPORTED char *mbentry_metapath(const struct mboxlist_entry *mbentry, int metatype, int isnew) { return mboxname_metapath(mbentry->partition, mbentry->name, mbentry->uniqueid, metatype, isnew); } EXPORTED char *mbentry_datapath(const struct mboxlist_entry *mbentry, uint32_t uid) { return mboxname_datapath(mbentry->partition, mbentry->name, mbentry->uniqueid, uid); } /* * read a single record from the mailboxes.db and return a pointer to it */ static int mboxlist_read(const char *name, const char **dataptr, size_t *datalenptr, struct txn **tid, int wrlock) { int namelen = strlen(name); int r; if (!namelen) return IMAP_MAILBOX_NONEXISTENT; if (wrlock) { r = cyrusdb_fetchlock(mbdb, name, namelen, dataptr, datalenptr, tid); } else { r = cyrusdb_fetch(mbdb, name, namelen, dataptr, datalenptr, tid); } switch (r) { case CYRUSDB_OK: /* no entry required, just checking if it exists */ return 0; break; case CYRUSDB_AGAIN: return IMAP_AGAIN; break; case CYRUSDB_NOTFOUND: return IMAP_MAILBOX_NONEXISTENT; break; default: syslog(LOG_ERR, "DBERROR: error fetching mboxlist %s: %s", name, cyrusdb_strerror(r)); return IMAP_IOERROR; break; } /* never get here */ } EXPORTED uint32_t mboxlist_string_to_mbtype(const char *string) { uint32_t mbtype = 0; if (!string) return 0; /* null just means default */ for (; *string; string++) { switch (*string) { case 'a': mbtype |= MBTYPE_ADDRESSBOOK; break; case 'b': mbtype |= MBTYPE_COLLECTION; break; case 'c': mbtype |= MBTYPE_CALENDAR; break; case 'd': mbtype |= MBTYPE_DELETED; break; case 'm': mbtype |= MBTYPE_MOVING; break; case 'n': mbtype |= MBTYPE_NETNEWS; break; case 'r': mbtype |= MBTYPE_REMOTE; break; case 'z': mbtype |= MBTYPE_RESERVE; break; } } return mbtype; } struct parseentry_rock { struct mboxlist_entry *mbentry; struct buf *aclbuf; int doingacl; }; int parseentry_cb(int type, struct dlistsax_data *d) { struct parseentry_rock *rock = (struct parseentry_rock *)d->rock; switch(type) { case DLISTSAX_KVLISTSTART: if (!strcmp(buf_cstring(&d->kbuf), "A")) { rock->doingacl = 1; } break; case DLISTSAX_KVLISTEND: rock->doingacl = 0; break; case DLISTSAX_STRING: if (rock->doingacl) { buf_append(rock->aclbuf, &d->kbuf); buf_putc(rock->aclbuf, '\t'); buf_append(rock->aclbuf, &d->buf); buf_putc(rock->aclbuf, '\t'); } else { const char *key = buf_cstring(&d->kbuf); if (!strcmp(key, "F")) { rock->mbentry->foldermodseq = atoll(buf_cstring(&d->buf)); } else if (!strcmp(key, "I")) { rock->mbentry->uniqueid = buf_newcstring(&d->buf); } else if (!strcmp(key, "M")) { rock->mbentry->mtime = atoi(buf_cstring(&d->buf)); } else if (!strcmp(key, "P")) { rock->mbentry->partition = buf_newcstring(&d->buf); } else if (!strcmp(key, "S")) { rock->mbentry->server = buf_newcstring(&d->buf); } else if (!strcmp(key, "T")) { rock->mbentry->mbtype = mboxlist_string_to_mbtype(buf_cstring(&d->buf)); } else if (!strcmp(key, "V")) { rock->mbentry->uidvalidity = atol(buf_cstring(&d->buf)); } } } return 0; } /* * parse a record read from the mailboxes.db into its parts. * * full dlist format is: * A: _a_cl * I: unique_i_d * M: _m_time * P: _p_artition * S: _s_erver * T: _t_ype * V: uid_v_alidity */ EXPORTED int mboxlist_parse_entry(mbentry_t **mbentryptr, const char *name, size_t namelen, const char *data, size_t datalen) { static struct buf aclbuf; int r = IMAP_MAILBOX_BADFORMAT; char *freeme = NULL; char **target; char *p, *q; mbentry_t *mbentry = mboxlist_entry_create(); if (!datalen) goto done; /* copy name */ if (namelen) mbentry->name = xstrndup(name, namelen); else mbentry->name = xstrdup(name); /* check for DLIST mboxlist */ if (*data == '%') { struct parseentry_rock rock; memset(&rock, 0, sizeof(struct parseentry_rock)); rock.mbentry = mbentry; rock.aclbuf = &aclbuf; aclbuf.len = 0; r = dlist_parsesax(data, datalen, 0, parseentry_cb, &rock); if (!r) mbentry->acl = buf_newcstring(&aclbuf); goto done; } /* copy data */ freeme = p = xstrndup(data, datalen); /* check for extended mboxlist entry */ if (*p == '(') { int last = 0; p++; /* past leading '(' */ while (!last) { target = NULL; q = p; while (*q && *q != ' ' && *q != ')') q++; if (*q != ' ') break; *q++ = '\0'; if (!strcmp(p, "uniqueid")) target = &mbentry->uniqueid; if (!strcmp(p, "specialuse")) target = &mbentry->legacy_specialuse; p = q; while (*q && *q != ' ' && *q != ')') q++; if (*q != ' ') last = 1; if (*q) *q++ = '\0'; if (target) *target = xstrdup(p); p = q; } if (*p == ' ') p++; /* past trailing ' ' */ } /* copy out interesting parts */ mbentry->mbtype = strtol(p, &p, 10); if (*p == ' ') p++; q = p; while (*q && *q != ' ' && *q != '!') q++; if (*q == '!') { *q++ = '\0'; mbentry->server = xstrdup(p); p = q; while (*q && *q != ' ') q++; } if (*q) *q++ = '\0'; mbentry->partition = xstrdup(p); mbentry->acl = xstrdup(q); r = 0; done: if (!r && mbentryptr) *mbentryptr = mbentry; else mboxlist_entry_free(&mbentry); free(freeme); return r; } /* read a record and parse into parts */ static int mboxlist_mylookup(const char *name, mbentry_t **mbentryptr, struct txn **tid, int wrlock) { int r; const char *data; size_t datalen; r = mboxlist_read(name, &data, &datalen, tid, wrlock); if (r) return r; return mboxlist_parse_entry(mbentryptr, name, 0, data, datalen); } /* * Lookup 'name' in the mailbox list, ignoring reserved records */ EXPORTED int mboxlist_lookup(const char *name, mbentry_t **entryptr, struct txn **tid) { mbentry_t *entry = NULL; int r; r = mboxlist_mylookup(name, &entry, tid, 0); if (r) return r; /* Ignore "reserved" entries, like they aren't there */ if (entry->mbtype & MBTYPE_RESERVE) { mboxlist_entry_free(&entry); return IMAP_MAILBOX_RESERVED; } /* Ignore "deleted" entries, like they aren't there */ if (entry->mbtype & MBTYPE_DELETED) { mboxlist_entry_free(&entry); return IMAP_MAILBOX_NONEXISTENT; } if (entryptr) *entryptr = entry; else mboxlist_entry_free(&entry); return 0; } EXPORTED int mboxlist_lookup_allow_all(const char *name, mbentry_t **entryptr, struct txn **tid) { return mboxlist_mylookup(name, entryptr, tid, 0); } struct _find_specialuse_data { const char *use; const char *userid; char *mboxname; }; static int _find_specialuse(const mbentry_t *mbentry, void *rock) { struct _find_specialuse_data *d = (struct _find_specialuse_data *)rock; struct buf attrib = BUF_INITIALIZER; annotatemore_lookup(mbentry->name, "/specialuse", d->userid, &attrib); if (attrib.len) { strarray_t *uses = strarray_split(buf_cstring(&attrib), " ", 0); if (strarray_find_case(uses, d->use, 0) >= 0) d->mboxname = xstrdup(mbentry->name); strarray_free(uses); } buf_free(&attrib); if (d->mboxname) return CYRUSDB_DONE; return 0; } EXPORTED char *mboxlist_find_specialuse(const char *use, const char *userid) { /* \\Inbox is magical */ if (!strcasecmp(use, "\\Inbox")) return mboxname_user_mbox(userid, NULL); struct _find_specialuse_data rock = { use, userid, NULL }; mboxlist_usermboxtree(userid, _find_specialuse, &rock, MBOXTREE_SKIP_ROOT); return rock.mboxname; } struct _find_uniqueid_data { const char *uniqueid; char *mboxname; }; static int _find_uniqueid(const mbentry_t *mbentry, void *rock) { struct _find_uniqueid_data *d = (struct _find_uniqueid_data *) rock; int r = 0; if (!strcmp(d->uniqueid, mbentry->uniqueid)) { d->mboxname = xstrdup(mbentry->name); r = CYRUSDB_DONE; } return r; } EXPORTED char *mboxlist_find_uniqueid(const char *uniqueid, const char *userid) { struct _find_uniqueid_data rock = { uniqueid, NULL }; mboxlist_usermboxtree(userid, _find_uniqueid, &rock, MBOXTREE_PLUS_RACL); return rock.mboxname; } /* given a mailbox name, find the staging directory. XXX - this should * require more locking, and staging directories should be by pid */ HIDDEN int mboxlist_findstage(const char *name, char *stagedir, size_t sd_len) { const char *root; mbentry_t *mbentry = NULL; int r; assert(stagedir != NULL); /* Find mailbox */ r = mboxlist_lookup(name, &mbentry, NULL); if (r) return r; root = config_partitiondir(mbentry->partition); mboxlist_entry_free(&mbentry); if (!root) return IMAP_PARTITION_UNKNOWN; snprintf(stagedir, sd_len, "%s/stage./", root); return 0; } static void mboxlist_racl_key(int isuser, const char *keyuser, const char *mbname, struct buf *buf) { buf_setcstr(buf, "$RACL$"); buf_putc(buf, isuser ? 'U' : 'S'); buf_putc(buf, '$'); if (keyuser) { buf_appendcstr(buf, keyuser); buf_putc(buf, '$'); } if (mbname) { buf_appendcstr(buf, mbname); } } static int user_is_in(const strarray_t *aclbits, const char *user) { int i; if (!aclbits) return 0; for (i = 0; i+1 < strarray_size(aclbits); i+=2) { if (!strcmp(strarray_nth(aclbits, i), user)) return 1; } return 0; } static int mboxlist_update_racl(const char *name, const mbentry_t *oldmbentry, const mbentry_t *newmbentry, struct txn **txn) { static strarray_t *admins = NULL; struct buf buf = BUF_INITIALIZER; char *userid = mboxname_to_userid(name); strarray_t *oldusers = NULL; strarray_t *newusers = NULL; int i; int r = 0; if (!admins) admins = strarray_split(config_getstring(IMAPOPT_ADMINS), NULL, 0); if (oldmbentry && oldmbentry->mbtype != MBTYPE_DELETED) oldusers = strarray_split(oldmbentry->acl, "\t", 0); if (newmbentry && newmbentry->mbtype != MBTYPE_DELETED) newusers = strarray_split(newmbentry->acl, "\t", 0); if (oldusers) { for (i = 0; i+1 < strarray_size(oldusers); i+=2) { const char *acluser = strarray_nth(oldusers, i); const char *aclval = strarray_nth(oldusers, i+1); if (!strchr(aclval, 'l')) continue; /* non-lookup ACLs can be skipped */ if (!strcmpsafe(userid, acluser)) continue; if (strarray_find(admins, acluser, 0) >= 0) continue; if (user_is_in(newusers, acluser)) continue; mboxlist_racl_key(!!userid, acluser, name, &buf); r = cyrusdb_delete(mbdb, buf.s, buf.len, txn, /*force*/1); if (r) goto done; } } if (newusers) { for (i = 0; i+1 < strarray_size(newusers); i+=2) { const char *acluser = strarray_nth(newusers, i); const char *aclval = strarray_nth(newusers, i+1); if (!strchr(aclval, 'l')) continue; /* non-lookup ACLs can be skipped */ if (!strcmpsafe(userid, acluser)) continue; if (strarray_find(admins, acluser, 0) >= 0) continue; if (user_is_in(oldusers, acluser)) continue; mboxlist_racl_key(!!userid, acluser, name, &buf); r = cyrusdb_store(mbdb, buf.s, buf.len, "", 0, txn); if (r) goto done; } } done: strarray_free(oldusers); strarray_free(newusers); free(userid); buf_free(&buf); return r; } static int mboxlist_update_entry(const char *name, const mbentry_t *mbentry, struct txn **txn) { mbentry_t *old = NULL; int r = 0; mboxlist_mylookup(name, &old, txn, 0); // ignore errors, it will be NULL if (!cyrusdb_fetch(mbdb, "$RACL", 5, NULL, NULL, txn)) { r = mboxlist_update_racl(name, old, mbentry, txn); /* XXX return value here is discarded? */ } if (mbentry) { char *mboxent = mboxlist_entry_cstring(mbentry); r = cyrusdb_store(mbdb, name, strlen(name), mboxent, strlen(mboxent), txn); free(mboxent); if (!r && config_auditlog) { /* XXX is there a difference between "" and NULL? */ if (old && strcmpsafe(old->acl, mbentry->acl)) { syslog(LOG_NOTICE, "auditlog: acl sessionid=<%s> " "mailbox=<%s> uniqueid=<%s> " "oldacl=<%s> acl=<%s>", session_id(), name, mbentry->uniqueid, old->acl, mbentry->acl); } } } else { r = cyrusdb_delete(mbdb, name, strlen(name), txn, /*force*/1); } mboxlist_entry_free(&old); return r; } EXPORTED int mboxlist_delete(const char *name) { return mboxlist_update_entry(name, NULL, NULL); } EXPORTED int mboxlist_update(mbentry_t *mbentry, int localonly) { int r = 0, r2 = 0; struct txn *tid = NULL; r = mboxlist_update_entry(mbentry->name, mbentry, &tid); if (!r) mboxname_setmodseq(mbentry->name, mbentry->foldermodseq, mbentry->mbtype, /*dofolder*/1); /* commit the change to mupdate */ if (!r && !localonly && config_mupdate_server) { mupdate_handle *mupdate_h = NULL; r = mupdate_connect(config_mupdate_server, NULL, &mupdate_h, NULL); if (r) { syslog(LOG_ERR, "cannot connect to mupdate server for update of '%s'", mbentry->name); } else { char *location = strconcat(config_servername, "!", mbentry->partition, (char *)NULL); r = mupdate_activate(mupdate_h, mbentry->name, location, mbentry->acl); free(location); if (r) { syslog(LOG_ERR, "MUPDATE: can't update mailbox entry for '%s'", mbentry->name); } } mupdate_disconnect(&mupdate_h); } if (tid) { if (r) { r2 = cyrusdb_abort(mbdb, tid); } else { r2 = cyrusdb_commit(mbdb, tid); } } if (r2) { syslog(LOG_ERR, "DBERROR: error %s txn in mboxlist_update: %s", r ? "aborting" : "commiting", cyrusdb_strerror(r2)); } return r; } EXPORTED int mboxlist_findparent(const char *mboxname, mbentry_t **mbentryp) { mbentry_t *mbentry = NULL; mbname_t *mbname = mbname_from_intname(mboxname); int r = IMAP_MAILBOX_NONEXISTENT; while (strarray_size(mbname_boxes(mbname))) { free(mbname_pop_boxes(mbname)); mboxlist_entry_free(&mbentry); r = mboxlist_lookup(mbname_intname(mbname), &mbentry, NULL); if (r != IMAP_MAILBOX_NONEXISTENT) break; } if (r) mboxlist_entry_free(&mbentry); else *mbentryp = mbentry; mbname_free(&mbname); return r; } static int mboxlist_create_partition(const char *mboxname, const char *part, char **out) { mbentry_t *parent = NULL; if (!part) { int r = mboxlist_findparent(mboxname, &parent); if (!r) part = parent->partition; } /* use defaultpartition if specified */ if (!part && config_defpartition) part = config_defpartition; /* look for most fitting partition */ if (!part) part = partlist_local_select(); /* Configuration error */ if (!part || (strlen(part) > MAX_PARTITION_LEN)) goto err; if (!config_partitiondir(part)) goto err; *out = xstrdupnull(part); mboxlist_entry_free(&parent); return 0; err: mboxlist_entry_free(&parent); return IMAP_PARTITION_UNKNOWN; } /* * Check if a mailbox can be created. There is no other setup at this * stage, just the check! */ static int mboxlist_create_namecheck(const char *mboxname, const char *userid, const struct auth_state *auth_state, int isadmin, int force_subdirs) { mbentry_t *mbentry = NULL; int r = 0; /* policy first */ r = mboxname_policycheck(mboxname); if (r) goto done; /* is this the user's INBOX namespace? */ if (!isadmin && mboxname_userownsmailbox(userid, mboxname)) { /* User has admin rights over their own mailbox namespace */ if (config_implicitrights & ACL_ADMIN) isadmin = 1; } /* Check to see if mailbox already exists */ r = mboxlist_lookup(mboxname, &mbentry, NULL); if (r != IMAP_MAILBOX_NONEXISTENT) { if (!r) { r = IMAP_MAILBOX_EXISTS; /* Lie about error if privacy demands */ if (!isadmin && !(cyrus_acl_myrights(auth_state, mbentry->acl) & ACL_LOOKUP)) { r = IMAP_PERMISSION_DENIED; } } goto done; } mboxlist_entry_free(&mbentry); /* look for a parent mailbox */ r = mboxlist_findparent(mboxname, &mbentry); if (r == 0) { /* found a parent */ char root[MAX_MAILBOX_NAME+1]; /* check acl */ if (!isadmin && !(cyrus_acl_myrights(auth_state, mbentry->acl) & ACL_CREATE)) { r = IMAP_PERMISSION_DENIED; goto done; } /* check quota */ if (quota_findroot(root, sizeof(root), mboxname)) { quota_t qdiffs[QUOTA_NUMRESOURCES] = QUOTA_DIFFS_DONTCARE_INITIALIZER; qdiffs[QUOTA_NUMFOLDERS] = 1; r = quota_check_useds(root, qdiffs); if (r) goto done; } } else if (r == IMAP_MAILBOX_NONEXISTENT) { /* no parent mailbox */ if (!isadmin) { r = IMAP_PERMISSION_DENIED; goto done; } if (!force_subdirs) { mbname_t *mbname = mbname_from_intname(mboxname); if (!mbname_isdeleted(mbname) && mbname_userid(mbname) && strarray_size(mbname_boxes(mbname))) { /* Disallow creating user.X.* when no user.X */ r = IMAP_PERMISSION_DENIED; goto done; } mbname_free(&mbname); } /* otherwise no parent is OK */ r = 0; } done: mboxlist_entry_free(&mbentry); return r; } static int mboxlist_create_acl(const char *mboxname, char **out) { mbentry_t *mbentry = NULL; int r; int mask; char *defaultacl; char *identifier; char *rights; char *p; r = mboxlist_findparent(mboxname, &mbentry); if (!r) { *out = xstrdup(mbentry->acl); mboxlist_entry_free(&mbentry); return 0; } *out = xstrdup(""); char *owner = mboxname_to_userid(mboxname); if (owner) { /* owner gets full permission on own mailbox by default */ cyrus_acl_set(out, owner, ACL_MODE_SET, ACL_ALL, (cyrus_acl_canonproc_t *)0, (void *)0); free(owner); return 0; } defaultacl = identifier = xstrdup(config_getstring(IMAPOPT_DEFAULTACL)); for (;;) { while (*identifier && Uisspace(*identifier)) identifier++; rights = identifier; while (*rights && !Uisspace(*rights)) rights++; if (!*rights) break; *rights++ = '\0'; while (*rights && Uisspace(*rights)) rights++; if (!*rights) break; p = rights; while (*p && !Uisspace(*p)) p++; if (*p) *p++ = '\0'; cyrus_acl_strtomask(rights, &mask); /* XXX and if strtomask fails? */ cyrus_acl_set(out, identifier, ACL_MODE_SET, mask, (cyrus_acl_canonproc_t *)0, (void *)0); identifier = p; } free(defaultacl); return 0; } /* and this API just plain sucks */ EXPORTED int mboxlist_createmailboxcheck(const char *name, int mbtype __attribute__((unused)), const char *partition, int isadmin, const char *userid, const struct auth_state *auth_state, char **newacl, char **newpartition, int forceuser) { char *part = NULL; char *acl = NULL; int r = 0; r = mboxlist_create_namecheck(name, userid, auth_state, isadmin, forceuser); if (r) goto done; if (newacl) { r = mboxlist_create_acl(name, &acl); if (r) goto done; } if (newpartition) { r = mboxlist_create_partition(name, partition, &part); if (r) goto done; } done: if (r || !newacl) free(acl); else *newacl = acl; if (r || !newpartition) free(part); else *newpartition = part; return r; } /* * Create a mailbox * * 1. verify ACL's to best of ability (CRASH: abort) * 2. verify parent ACL's if need to * 3. create the local mailbox locally (exclusive lock) and keep it locked * 4. open mupdate connection if necessary * 5. create mupdate entry (CRASH: mupdate inconsistant) * */ static int mboxlist_createmailbox_full(const char *mboxname, int mbtype, const char *partition, int isadmin, const char *userid, const struct auth_state *auth_state, int options, unsigned uidvalidity, modseq_t highestmodseq, const char *copyacl, const char *uniqueid, int localonly, int forceuser, int dbonly, struct mailbox **mboxptr) { int r; char *newpartition = NULL; char *acl = NULL; struct mailbox *newmailbox = NULL; int isremote = mbtype & MBTYPE_REMOTE; mbentry_t *newmbentry = NULL; r = mboxlist_create_namecheck(mboxname, userid, auth_state, isadmin, forceuser); if (r) goto done; if (copyacl) { acl = xstrdup(copyacl); } else { r = mboxlist_create_acl(mboxname, &acl); if (r) goto done; } r = mboxlist_create_partition(mboxname, partition, &newpartition); if (r) goto done; if (!dbonly && !isremote) { /* Filesystem Operations */ r = mailbox_create(mboxname, mbtype, newpartition, acl, uniqueid, options, uidvalidity, highestmodseq, &newmailbox); if (r) goto done; /* CREATE failed */ r = mailbox_add_conversations(newmailbox); if (r) goto done; } /* all is well - activate the mailbox */ newmbentry = mboxlist_entry_create(); newmbentry->acl = xstrdupnull(acl); newmbentry->mbtype = mbtype; newmbentry->partition = xstrdupnull(newpartition); if (newmailbox) { newmbentry->uniqueid = xstrdupnull(newmailbox->uniqueid); newmbentry->uidvalidity = newmailbox->i.uidvalidity; newmbentry->foldermodseq = newmailbox->i.highestmodseq; } r = mboxlist_update_entry(mboxname, newmbentry, NULL); if (r) { syslog(LOG_ERR, "DBERROR: failed to insert to mailboxes list %s: %s", mboxname, cyrusdb_strerror(r)); r = IMAP_IOERROR; } /* 9. set MUPDATE entry as commited (CRASH: commited) */ if (!r && config_mupdate_server && !localonly) { mupdate_handle *mupdate_h = NULL; char *loc = strconcat(config_servername, "!", newpartition, (char *)NULL); r = mupdate_connect(config_mupdate_server, NULL, &mupdate_h, NULL); if (!r) r = mupdate_reserve(mupdate_h, mboxname, loc); if (!r) r = mupdate_activate(mupdate_h, mboxname, loc, acl); if (r) { syslog(LOG_ERR, "MUPDATE: can't commit mailbox entry for '%s'", mboxname); mboxlist_update_entry(mboxname, NULL, 0); } if (mupdate_h) mupdate_disconnect(&mupdate_h); free(loc); } done: if (newmailbox) { if (r) mailbox_delete(&newmailbox); else if (mboxptr) *mboxptr = newmailbox; else mailbox_close(&newmailbox); } free(acl); free(newpartition); mboxlist_entry_free(&newmbentry); return r; } EXPORTED int mboxlist_createmailbox(const char *name, int mbtype, const char *partition, int isadmin, const char *userid, const struct auth_state *auth_state, int localonly, int forceuser, int dbonly, int notify, struct mailbox **mailboxptr) { int options = config_getint(IMAPOPT_MAILBOX_DEFAULT_OPTIONS) | OPT_POP3_NEW_UIDL; int r; struct mailbox *mailbox = NULL; uint32_t uidvalidity = 0; /* check if a previous deleted mailbox existed */ mbentry_t *oldmbentry = NULL; r = mboxlist_lookup_allow_all(name, &oldmbentry, NULL); if (!r && oldmbentry->mbtype == MBTYPE_DELETED) { /* then the UIDVALIDITY must be higher than before */ if (uidvalidity <= oldmbentry->uidvalidity) uidvalidity = oldmbentry->uidvalidity+1; } mboxlist_entry_free(&oldmbentry); r = mboxlist_createmailbox_full(name, mbtype, partition, isadmin, userid, auth_state, options, uidvalidity, 0, NULL, NULL, localonly, forceuser, dbonly, &mailbox); if (notify && !r) { /* send a MailboxCreate event notification */ struct mboxevent *mboxevent = mboxevent_new(EVENT_MAILBOX_CREATE); mboxevent_extract_mailbox(mboxevent, mailbox); mboxevent_set_access(mboxevent, NULL, NULL, userid, mailbox->name, 1); mboxevent_notify(&mboxevent); mboxevent_free(&mboxevent); } if (mailboxptr && !r) *mailboxptr = mailbox; else mailbox_close(&mailbox); return r; } EXPORTED int mboxlist_createsync(const char *name, int mbtype, const char *partition, const char *userid, const struct auth_state *auth_state, int options, unsigned uidvalidity, modseq_t highestmodseq, const char *acl, const char *uniqueid, int local_only, struct mailbox **mboxptr) { return mboxlist_createmailbox_full(name, mbtype, partition, 1, userid, auth_state, options, uidvalidity, highestmodseq, acl, uniqueid, local_only, 1, 0, mboxptr); } /* insert an entry for the proxy */ EXPORTED int mboxlist_insertremote(mbentry_t *mbentry, struct txn **txn) { int r = 0; if (mbentry->server) { /* remote mailbox */ if (config_mupdate_config == IMAP_ENUM_MUPDATE_CONFIG_UNIFIED && !strcasecmp(mbentry->server, config_servername)) { /* its on our server, make it a local mailbox */ mbentry->mbtype &= ~MBTYPE_REMOTE; mbentry->server = NULL; } else { /* make sure it's a remote mailbox */ mbentry->mbtype |= MBTYPE_REMOTE; } } /* database put */ r = mboxlist_update_entry(mbentry->name, mbentry, txn); switch (r) { case CYRUSDB_OK: break; case CYRUSDB_AGAIN: abort(); /* shouldn't happen ! */ break; default: syslog(LOG_ERR, "DBERROR: error updating database %s: %s", mbentry->name, cyrusdb_strerror(r)); r = IMAP_IOERROR; break; } return r; } /* Special function to delete a remote mailbox. * Only affects mboxlist. * Assumes admin powers. */ EXPORTED int mboxlist_deleteremote(const char *name, struct txn **in_tid) { int r; struct txn **tid; struct txn *lcl_tid = NULL; mbentry_t *mbentry = NULL; if(in_tid) { tid = in_tid; } else { tid = &lcl_tid; } retry: r = mboxlist_mylookup(name, &mbentry, tid, 1); switch (r) { case 0: break; case IMAP_MAILBOX_NONEXISTENT: r = 0; break; case IMAP_AGAIN: goto retry; break; default: goto done; } if (mbentry && (mbentry->mbtype & MBTYPE_REMOTE) && !mbentry->server) { syslog(LOG_ERR, "mboxlist_deleteremote called on non-remote mailbox: %s", name); goto done; } r = mboxlist_update_entry(name, NULL, tid); if (r) { syslog(LOG_ERR, "DBERROR: error deleting %s: %s", name, cyrusdb_strerror(r)); r = IMAP_IOERROR; } /* commit db operations, but only if we weren't passed a transaction */ if (!in_tid) { r = cyrusdb_commit(mbdb, *tid); if (r) { syslog(LOG_ERR, "DBERROR: failed on commit: %s", cyrusdb_strerror(r)); r = IMAP_IOERROR; } tid = NULL; } done: if (r && !in_tid && tid) { /* Abort the transaction if it is still in progress */ cyrusdb_abort(mbdb, *tid); } return r; } static int addmbox_to_list(const mbentry_t *mbentry, void *rock) { strarray_t *list = (strarray_t *)rock; strarray_append(list, mbentry->name); return 0; } /* * Delayed Delete a mailbox: translate delete into rename */ EXPORTED int mboxlist_delayed_deletemailbox(const char *name, int isadmin, const char *userid, const struct auth_state *auth_state, struct mboxevent *mboxevent, int checkacl, int localonly, int force) { mbentry_t *mbentry = NULL; strarray_t existing = STRARRAY_INITIALIZER; int i; char newname[MAX_MAILBOX_BUFFER]; int r = 0; long myrights; if (!isadmin && force) return IMAP_PERMISSION_DENIED; /* delete of a user.X folder */ mbname_t *mbname = mbname_from_intname(name); if (mbname_userid(mbname) && !strarray_size(mbname_boxes(mbname))) { /* Can't DELETE INBOX (your own inbox) */ if (!strcmpsafe(mbname_userid(mbname), userid)) { r = IMAP_MAILBOX_NOTSUPPORTED; goto done; } /* Only admins may delete user */ if (!isadmin) { r = IMAP_PERMISSION_DENIED; goto done; } } if (!isadmin && mbname_userid(mbname)) { struct buf attrib = BUF_INITIALIZER; annotatemore_lookup(mbname_intname(mbname), "/specialuse", mbname_userid(mbname), &attrib); if (attrib.len) r = IMAP_MAILBOX_SPECIALUSE; buf_free(&attrib); if (r) goto done; } r = mboxlist_lookup(name, &mbentry, NULL); if (r) goto done; /* check if user has Delete right (we've already excluded non-admins * from deleting a user mailbox) */ if (checkacl) { myrights = cyrus_acl_myrights(auth_state, mbentry->acl); if (!(myrights & ACL_DELETEMBOX)) { /* User has admin rights over their own mailbox namespace */ if (mboxname_userownsmailbox(userid, name) && (config_implicitrights & ACL_ADMIN)) { isadmin = 1; } /* Lie about error if privacy demands */ r = (isadmin || (myrights & ACL_LOOKUP)) ? IMAP_PERMISSION_DENIED : IMAP_MAILBOX_NONEXISTENT; goto done; } } /* check if there are already too many! */ mboxname_todeleted(name, newname, 0); r = mboxlist_mboxtree(newname, addmbox_to_list, &existing, MBOXTREE_SKIP_ROOT); if (r) goto done; /* keep the last 19, so the new one is the 20th */ for (i = 0; i < (int)existing.count - 19; i++) { const char *subname = strarray_nth(&existing, i); syslog(LOG_NOTICE, "too many subfolders for %s, deleting %s (%d / %d)", newname, subname, i+1, (int)existing.count); r = mboxlist_deletemailbox(subname, 1, userid, auth_state, NULL, 0, 1, 1); if (r) goto done; } /* get the deleted name */ mboxname_todeleted(name, newname, 1); /* Get mboxlist_renamemailbox to do the hard work. No ACL checks needed */ r = mboxlist_renamemailbox((char *)name, newname, mbentry->partition, 0 /* uidvalidity */, 1 /* isadmin */, userid, auth_state, mboxevent, localonly /* local_only */, force, 1); done: strarray_fini(&existing); mboxlist_entry_free(&mbentry); mbname_free(&mbname); return r; } /* * Delete a mailbox. * Deleting the mailbox user.FOO may only be performed by an admin. * * 1. Begin transaction * 2. Verify ACL's * 3. remove from database * 4. remove from disk * 5. commit transaction * 6. Open mupdate connection if necessary * 7. delete from mupdate * */ EXPORTED int mboxlist_deletemailbox(const char *name, int isadmin, const char *userid, const struct auth_state *auth_state, struct mboxevent *mboxevent, int checkacl, int local_only, int force) { mbentry_t *mbentry = NULL; int r = 0; long myrights; struct mailbox *mailbox = NULL; int isremote = 0; mupdate_handle *mupdate_h = NULL; if (!isadmin && force) return IMAP_PERMISSION_DENIED; /* delete of a user.X folder */ mbname_t *mbname = mbname_from_intname(name); if (mbname_userid(mbname) && !strarray_size(mbname_boxes(mbname))) { /* Can't DELETE INBOX (your own inbox) */ if (!strcmpsafe(mbname_userid(mbname), userid)) { r = IMAP_MAILBOX_NOTSUPPORTED; goto done; } /* Only admins may delete user */ if (!isadmin) { r = IMAP_PERMISSION_DENIED; goto done; } } if (!isadmin && mbname_userid(mbname)) { struct buf attrib = BUF_INITIALIZER; annotatemore_lookup(mbname_intname(mbname), "/specialuse", mbname_userid(mbname), &attrib); if (attrib.len) r = IMAP_MAILBOX_SPECIALUSE; buf_free(&attrib); if (r) goto done; } r = mboxlist_lookup_allow_all(name, &mbentry, NULL); if (r) goto done; isremote = mbentry->mbtype & MBTYPE_REMOTE; /* check if user has Delete right (we've already excluded non-admins * from deleting a user mailbox) */ if (checkacl) { myrights = cyrus_acl_myrights(auth_state, mbentry->acl); if(!(myrights & ACL_DELETEMBOX)) { /* User has admin rights over their own mailbox namespace */ if (mboxname_userownsmailbox(userid, name) && (config_implicitrights & ACL_ADMIN)) { isadmin = 1; } /* Lie about error if privacy demands */ r = (isadmin || (myrights & ACL_LOOKUP)) ? IMAP_PERMISSION_DENIED : IMAP_MAILBOX_NONEXISTENT; goto done; } } /* Lock the mailbox if it isn't a remote mailbox */ if (!isremote) { r = mailbox_open_iwl(name, &mailbox); } if (r && !force) goto done; /* remove from mupdate */ if (!isremote && !local_only && config_mupdate_server) { /* delete the mailbox in MUPDATE */ r = mupdate_connect(config_mupdate_server, NULL, &mupdate_h, NULL); if (r) { syslog(LOG_ERR, "cannot connect to mupdate server for delete of '%s'", name); goto done; } r = mupdate_delete(mupdate_h, name); if(r) { syslog(LOG_ERR, "MUPDATE: can't delete mailbox entry '%s'", name); } if (mupdate_h) mupdate_disconnect(&mupdate_h); } if (r && !force) goto done; if (!isremote && !mboxname_isdeletedmailbox(name, NULL)) { /* store a DELETED marker */ mbentry_t *newmbentry = mboxlist_entry_create(); newmbentry->name = xstrdupnull(name); newmbentry->mbtype = MBTYPE_DELETED; if (mailbox) { newmbentry->uniqueid = xstrdupnull(mailbox->uniqueid); newmbentry->uidvalidity = mailbox->i.uidvalidity; newmbentry->foldermodseq = mailbox_modseq_dirty(mailbox); } r = mboxlist_update(newmbentry, /*localonly*/1); mboxlist_entry_free(&newmbentry); } else { /* delete entry (including DELETED.* mailboxes, no need * to keep that rubbish around) */ r = mboxlist_update_entry(name, NULL, 0); if (r) { syslog(LOG_ERR, "DBERROR: error deleting %s: %s", name, cyrusdb_strerror(r)); r = IMAP_IOERROR; if (!force) goto done; } if (r && !force) goto done; } /* delete underlying mailbox */ if (!isremote && mailbox) { /* only on a real delete do we delete from the remote end as well */ sync_log_unmailbox(mailbox->name); mboxevent_extract_mailbox(mboxevent, mailbox); mboxevent_set_access(mboxevent, NULL, NULL, userid, mailbox->name, 1); r = mailbox_delete(&mailbox); /* abort event notification */ if (r && mboxevent) mboxevent_free(&mboxevent); } done: mailbox_close(&mailbox); mboxlist_entry_free(&mbentry); mbname_free(&mbname); return r; } static int _rename_check_specialuse(const char *oldname, const char *newname) { mbname_t *old = mbname_from_intname(oldname); mbname_t *new = mbname_from_intname(newname); struct buf attrib = BUF_INITIALIZER; int r = 0; if (mbname_userid(old)) annotatemore_lookup(oldname, "/specialuse", mbname_userid(old), &attrib); /* we have specialuse? */ if (attrib.len) { /* then target must be a single-depth mailbox too */ if (strarray_size(mbname_boxes(new)) != 1) r = IMAP_MAILBOX_SPECIALUSE; /* and have a userid as well */ if (!mbname_userid(new)) r = IMAP_MAILBOX_SPECIALUSE; /* and not be deleted */ if (mbname_isdeleted(new)) r = IMAP_MAILBOX_SPECIALUSE; } mbname_free(&new); mbname_free(&old); buf_free(&attrib); return r; } /* * Rename/move a single mailbox (recursive renames are handled at a * higher level). This only supports local mailboxes. Remote * mailboxes are handled up in imapd.c */ EXPORTED int mboxlist_renamemailbox(const char *oldname, const char *newname, const char *partition, unsigned uidvalidity, int isadmin, const char *userid, const struct auth_state *auth_state, struct mboxevent *mboxevent, int local_only, int forceuser, int ignorequota) { int r; int mupdatecommiterror = 0; long myrights; int isusermbox = 0; /* Are we renaming someone's inbox */ int partitionmove = 0; struct mailbox *oldmailbox = NULL; struct mailbox *newmailbox = NULL; struct txn *tid = NULL; const char *root = NULL; char *newpartition = NULL; mupdate_handle *mupdate_h = NULL; mbentry_t *newmbentry = NULL; /* 1. open mailbox */ r = mailbox_open_iwl(oldname, &oldmailbox); if (r) return r; myrights = cyrus_acl_myrights(auth_state, oldmailbox->acl); /* check the ACLs up-front */ if (!isadmin) { if (!(myrights & ACL_DELETEMBOX)) { r = (myrights & ACL_LOOKUP) ? IMAP_PERMISSION_DENIED : IMAP_MAILBOX_NONEXISTENT; goto done; } } /* 2. verify valid move */ /* XXX - handle remote mailbox */ /* special case: same mailbox, must be a partition move */ if (!strcmp(oldname, newname)) { const char *oldpath = mailbox_datapath(oldmailbox, 0); /* Only admin can move mailboxes between partitions */ if (!isadmin) { r = IMAP_PERMISSION_DENIED; goto done; } /* No partition, we're definitely not moving anywhere */ if (!partition) { r = IMAP_MAILBOX_EXISTS; goto done; } /* let mupdate code below know it was a partition move */ partitionmove = 1; /* this is OK because it uses a different static buffer */ root = config_partitiondir(partition); if (!root) { r = IMAP_PARTITION_UNKNOWN; goto done; } if (!strncmp(root, oldpath, strlen(root)) && oldpath[strlen(root)] == '/') { /* partitions are the same or share common prefix */ r = IMAP_MAILBOX_EXISTS; goto done; } /* NOTE: this is a rename to the same mailbox name on a * different partition. This is a pretty filthy hack, * which should be handled by having four totally different * codepaths: INBOX -> INBOX.foo, user rename, regular rename * and of course this one, partition move */ newpartition = xstrdup(partition); r = mailbox_copy_files(oldmailbox, newpartition, newname, oldmailbox->uniqueid); if (r) goto done; newmbentry = mboxlist_entry_create(); newmbentry->mbtype = oldmailbox->mbtype; newmbentry->partition = xstrdupnull(newpartition); newmbentry->acl = xstrdupnull(oldmailbox->acl); newmbentry->uidvalidity = oldmailbox->i.uidvalidity; newmbentry->uniqueid = xstrdupnull(oldmailbox->uniqueid); newmbentry->foldermodseq = oldmailbox->i.highestmodseq; /* bump regardless, it's rare */ r = mboxlist_update_entry(newname, newmbentry, &tid); if (r) goto done; /* skip ahead to the commit */ goto dbdone; } if (!isadmin) { r = _rename_check_specialuse(oldname, newname); if (r) goto done; } /* RENAME of some user's INBOX */ if (mboxname_isusermailbox(oldname, 1)) { if (mboxname_isdeletedmailbox(newname, NULL)) { /* delete user is OK */ } else if (mboxname_isusermailbox(newname, 1)) { /* user rename is depends on config */ if (!config_getswitch(IMAPOPT_ALLOWUSERMOVES)) { r = IMAP_MAILBOX_NOTSUPPORTED; goto done; } } else if (mboxname_userownsmailbox(userid, oldname) && mboxname_userownsmailbox(userid, newname)) { /* Special case of renaming inbox */ isusermbox = 1; } else { /* Everything else is bogus */ r = IMAP_MAILBOX_NOTSUPPORTED; goto done; } } r = mboxlist_create_namecheck(newname, userid, auth_state, isadmin, forceuser); if (r) goto done; r = mboxlist_create_partition(newname, partition, &newpartition); if (r) goto done; if (!newpartition) newpartition = xstrdup(config_defpartition); /* keep uidvalidity on rename unless specified */ if (!uidvalidity) uidvalidity = oldmailbox->i.uidvalidity; /* Rename the actual mailbox */ r = mailbox_rename_copy(oldmailbox, newname, newpartition, uidvalidity, isusermbox ? userid : NULL, ignorequota, &newmailbox); if (r) goto done; syslog(LOG_INFO, "Rename: %s -> %s", oldname, newname); /* create new entry */ newmbentry = mboxlist_entry_create(); newmbentry->name = xstrdupnull(newmailbox->name); newmbentry->mbtype = newmailbox->mbtype; newmbentry->partition = xstrdupnull(newmailbox->part); newmbentry->acl = xstrdupnull(newmailbox->acl); newmbentry->uidvalidity = newmailbox->i.uidvalidity; newmbentry->uniqueid = xstrdupnull(newmailbox->uniqueid); newmbentry->foldermodseq = newmailbox->i.highestmodseq; do { r = 0; /* delete the old entry */ if (!isusermbox) { /* store a DELETED marker */ mbentry_t *oldmbentry = mboxlist_entry_create(); oldmbentry->name = xstrdupnull(oldmailbox->name); oldmbentry->mbtype = MBTYPE_DELETED; oldmbentry->uidvalidity = oldmailbox->i.uidvalidity; oldmbentry->uniqueid = xstrdupnull(oldmailbox->uniqueid); oldmbentry->foldermodseq = mailbox_modseq_dirty(oldmailbox); r = mboxlist_update_entry(oldname, oldmbentry, &tid); mboxlist_entry_free(&oldmbentry); } /* create a new entry */ if (!r) { r = mboxlist_update_entry(newname, newmbentry, &tid); } switch (r) { case 0: /* success */ break; case CYRUSDB_AGAIN: tid = NULL; break; default: syslog(LOG_ERR, "DBERROR: rename failed on store %s %s: %s", oldname, newname, cyrusdb_strerror(r)); r = IMAP_IOERROR; goto done; break; } } while (r == CYRUSDB_AGAIN); dbdone: /* 3. Commit transaction */ r = cyrusdb_commit(mbdb, tid); tid = NULL; if (r) { syslog(LOG_ERR, "DBERROR: rename failed on commit %s %s: %s", oldname, newname, cyrusdb_strerror(r)); r = IMAP_IOERROR; goto done; } if (!local_only && config_mupdate_server) { /* commit the mailbox in MUPDATE */ char *loc = strconcat(config_servername, "!", newpartition, (char *)NULL); r = mupdate_connect(config_mupdate_server, NULL, &mupdate_h, NULL); if (!partitionmove) { if (!r && !isusermbox) r = mupdate_delete(mupdate_h, oldname); if (!r) r = mupdate_reserve(mupdate_h, newname, loc); } if (!r) r = mupdate_activate(mupdate_h, newname, loc, newmbentry->acl); if (r) { syslog(LOG_ERR, "MUPDATE: can't commit mailbox entry for '%s'", newname); mupdatecommiterror = r; } if (mupdate_h) mupdate_disconnect(&mupdate_h); free(loc); } done: /* Commit or cleanup */ if (!r && newmailbox) r = mailbox_commit(newmailbox); if (r) { /* rollback DB changes if it was an mupdate failure */ if (mupdatecommiterror) { r = 0; /* recreate an old entry */ if (!isusermbox) r = mboxlist_update_entry(oldname, newmbentry, &tid); /* delete the new entry */ if (!r) r = mboxlist_update_entry(newname, NULL, &tid); /* Commit transaction */ if (!r) r = cyrusdb_commit(mbdb, tid); tid = NULL; if (r) { /* XXX HOWTO repair this mess! */ syslog(LOG_ERR, "DBERROR: failed DB rollback on mailboxrename %s %s: %s", oldname, newname, cyrusdb_strerror(r)); syslog(LOG_ERR, "DBERROR: mailboxdb on mupdate and backend ARE NOT CONSISTENT"); syslog(LOG_ERR, "DBERROR: mailboxdb on mupdate has entry for %s, mailboxdb on backend has entry for %s and files are on the old position", oldname, newname); r = IMAP_IOERROR; } else { r = mupdatecommiterror; } } if (newmailbox) mailbox_delete(&newmailbox); if (partitionmove && newpartition) mailbox_delete_cleanup(NULL, newpartition, newname, oldmailbox->uniqueid); mailbox_close(&oldmailbox); } else { if (newmailbox) { /* prepare the event notification */ if (mboxevent) { /* case of delayed delete */ if (mboxevent->type == EVENT_MAILBOX_DELETE) mboxevent_extract_mailbox(mboxevent, oldmailbox); else { mboxevent_extract_mailbox(mboxevent, newmailbox); mboxevent_extract_old_mailbox(mboxevent, oldmailbox); } mboxevent_set_access(mboxevent, NULL, NULL, userid, newmailbox->name, 1); } /* log the rename before we close either mailbox, so that * we never nuke the mailbox from the replica before realising * that it has been renamed. This can be moved later again when * we sync mailboxes by uniqueid rather than name... */ sync_log_mailbox_double(oldname, newname); mailbox_rename_cleanup(&oldmailbox, isusermbox); #ifdef WITH_DAV mailbox_add_dav(newmailbox); #endif mailbox_close(&newmailbox); /* and log an append so that squatter indexes it */ sync_log_append(newname); } else if (partitionmove) { char *oldpartition = xstrdup(oldmailbox->part); char *olduniqueid = xstrdup(oldmailbox->uniqueid); if (config_auditlog) syslog(LOG_NOTICE, "auditlog: partitionmove sessionid=<%s> " "mailbox=<%s> uniqueid=<%s> oldpart=<%s> newpart=<%s>", session_id(), oldmailbox->name, oldmailbox->uniqueid, oldpartition, partition); /* this will sync-log the name anyway */ mailbox_close(&oldmailbox); mailbox_delete_cleanup(NULL, oldpartition, oldname, olduniqueid); free(olduniqueid); free(oldpartition); } else abort(); /* impossible, in theory */ } /* free memory */ free(newpartition); mboxlist_entry_free(&newmbentry); return r; } /* * Check if the admin rights are present in the 'rights' */ static int mboxlist_have_admin_rights(const char *rights) { int access, have_admin_access; cyrus_acl_strtomask(rights, &access); have_admin_access = access & ACL_ADMIN; return have_admin_access; } /* * Change the ACL for mailbox 'name' so that 'identifier' has the * rights enumerated in the string 'rights'. If 'rights' is the null * pointer, removes the ACL entry for 'identifier'. 'isadmin' is * nonzero if user is a mailbox admin. 'userid' is the user's login id. * * 1. Start transaction * 2. Check rights * 3. Set db entry * 4. Change backup copy (cyrus.header) * 5. Commit transaction * 6. Change mupdate entry * */ EXPORTED int mboxlist_setacl(const struct namespace *namespace __attribute__((unused)), const char *name, const char *identifier, const char *rights, int isadmin, const char *userid, const struct auth_state *auth_state) { mbentry_t *mbentry = NULL; int r; int myrights; int mode = ACL_MODE_SET; int isusermbox = 0; int isidentifiermbox = 0; int anyoneuseracl = 1; int ensure_owner_rights = 0; int mask; const char *mailbox_owner = NULL; struct mailbox *mailbox = NULL; char *newacl = NULL; struct txn *tid = NULL; /* round trip identifier to potentially strip domain */ mbname_t *mbname = mbname_from_userid(identifier); /* XXX - enforce cross domain restrictions */ identifier = mbname_userid(mbname); /* checks if the mailbox belongs to the user who is trying to change the access rights */ if (mboxname_userownsmailbox(userid, name)) isusermbox = 1; anyoneuseracl = config_getswitch(IMAPOPT_ANYONEUSERACL); /* checks if the identifier is the mailbox owner */ if (mboxname_userownsmailbox(identifier, name)) isidentifiermbox = 1; /* who is the mailbox owner? */ if (isusermbox) { mailbox_owner = userid; } else if (isidentifiermbox) { mailbox_owner = identifier; } /* ensure the access rights if the folder owner is the current user or the identifier */ ensure_owner_rights = isusermbox || isidentifiermbox; /* 1. Start Transaction */ /* lookup the mailbox to make sure it exists and get its acl */ do { r = mboxlist_mylookup(name, &mbentry, &tid, 1); } while(r == IMAP_AGAIN); /* Can't do this to an in-transit or reserved mailbox */ if (!r && mbentry->mbtype & (MBTYPE_MOVING | MBTYPE_RESERVE | MBTYPE_DELETED)) { r = IMAP_MAILBOX_NOTSUPPORTED; } /* if it is not a remote mailbox, we need to unlock the mailbox list, * lock the mailbox, and re-lock the mailboxes list */ /* we must do this to obey our locking rules */ if (!r && !(mbentry->mbtype & MBTYPE_REMOTE)) { cyrusdb_abort(mbdb, tid); tid = NULL; mboxlist_entry_free(&mbentry); /* open & lock mailbox header */ r = mailbox_open_iwl(name, &mailbox); if (!r) { do { /* lookup the mailbox to make sure it exists and get its acl */ r = mboxlist_mylookup(name, &mbentry, &tid, 1); } while (r == IMAP_AGAIN); } if(r) goto done; } /* 2. Check Rights */ if (!r && !isadmin) { myrights = cyrus_acl_myrights(auth_state, mbentry->acl); if (!(myrights & ACL_ADMIN)) { r = (myrights & ACL_LOOKUP) ? IMAP_PERMISSION_DENIED : IMAP_MAILBOX_NONEXISTENT; goto done; } } /* 2.1 Only admin user can set 'anyone' rights if config says so */ if (!r && !isadmin && !anyoneuseracl && !strncmp(identifier, "anyone", 6)) { r = IMAP_PERMISSION_DENIED; goto done; } /* 3. Set DB Entry */ if(!r) { /* Make change to ACL */ newacl = xstrdup(mbentry->acl); if (rights && *rights) { /* rights are present and non-empty */ mode = ACL_MODE_SET; if (*rights == '+') { rights++; mode = ACL_MODE_ADD; } else if (*rights == '-') { rights++; mode = ACL_MODE_REMOVE; } /* do not allow non-admin user to remove the admin rights from mailbox owner */ if (!isadmin && isidentifiermbox && mode != ACL_MODE_ADD) { int has_admin_rights = mboxlist_have_admin_rights(rights); if ((has_admin_rights && mode == ACL_MODE_REMOVE) || (!has_admin_rights && mode != ACL_MODE_REMOVE)) { syslog(LOG_ERR, "Denied removal of admin rights on " "folder \"%s\" (owner: %s) by user \"%s\"", name, mailbox_owner, userid); r = IMAP_PERMISSION_DENIED; goto done; } } r = cyrus_acl_strtomask(rights, &mask); if (!r && cyrus_acl_set(&newacl, identifier, mode, mask, ensure_owner_rights ? mboxlist_ensureOwnerRights : 0, (void *)mailbox_owner)) { r = IMAP_INVALID_IDENTIFIER; } } else { /* do not allow to remove the admin rights from mailbox owner */ if (!isadmin && isidentifiermbox) { syslog(LOG_ERR, "Denied removal of admin rights on " "folder \"%s\" (owner: %s) by user \"%s\"", name, mailbox_owner, userid); r = IMAP_PERMISSION_DENIED; goto done; } if (cyrus_acl_remove(&newacl, identifier, ensure_owner_rights ? mboxlist_ensureOwnerRights : 0, (void *)mailbox_owner)) { r = IMAP_INVALID_IDENTIFIER; } } } if (!r) { /* ok, change the database */ free(mbentry->acl); mbentry->acl = xstrdupnull(newacl); r = mboxlist_update_entry(name, mbentry, &tid); if (r) { syslog(LOG_ERR, "DBERROR: error updating acl %s: %s", name, cyrusdb_strerror(r)); r = IMAP_IOERROR; } /* send a AclChange event notification */ struct mboxevent *mboxevent = mboxevent_new(EVENT_ACL_CHANGE); mboxevent_extract_mailbox(mboxevent, mailbox); mboxevent_set_acl(mboxevent, identifier, rights); mboxevent_set_access(mboxevent, NULL, NULL, userid, mailbox->name, 0); mboxevent_notify(&mboxevent); mboxevent_free(&mboxevent); } /* 4. Change backup copy (cyrus.header) */ /* we already have it locked from above */ if (!r && !(mbentry->mbtype & MBTYPE_REMOTE)) { mailbox_set_acl(mailbox, newacl, 1); /* want to commit immediately to ensure ordering */ r = mailbox_commit(mailbox); } /* 5. Commit transaction */ if (!r) { if((r = cyrusdb_commit(mbdb, tid)) != 0) { syslog(LOG_ERR, "DBERROR: failed on commit: %s", cyrusdb_strerror(r)); r = IMAP_IOERROR; } tid = NULL; } /* 6. Change mupdate entry */ if (!r && config_mupdate_server) { mupdate_handle *mupdate_h = NULL; /* commit the update to MUPDATE */ char buf[MAX_PARTITION_LEN + HOSTNAME_SIZE + 2]; snprintf(buf, sizeof(buf), "%s!%s", config_servername, mbentry->partition); r = mupdate_connect(config_mupdate_server, NULL, &mupdate_h, NULL); if(r) { syslog(LOG_ERR, "cannot connect to mupdate server for setacl on '%s'", name); } else { r = mupdate_activate(mupdate_h, name, buf, newacl); if(r) { syslog(LOG_ERR, "MUPDATE: can't update mailbox entry for '%s'", name); } } mupdate_disconnect(&mupdate_h); } done: if (r && tid) { /* if we are mid-transaction, abort it! */ int r2 = cyrusdb_abort(mbdb, tid); if (r2) { syslog(LOG_ERR, "DBERROR: error aborting txn in mboxlist_setacl: %s", cyrusdb_strerror(r2)); } } mailbox_close(&mailbox); free(newacl); mboxlist_entry_free(&mbentry); mbname_free(&mbname); return r; } /* * Change the ACL for mailbox 'name'. We already have it locked * and have written the backup copy to the header, so there's * nothing left but to write the mailboxes.db. * * 1. Start transaction * 2. Set db entry * 3. Commit transaction * 4. Change mupdate entry * */ EXPORTED int mboxlist_sync_setacls(const char *name, const char *newacl) { mbentry_t *mbentry = NULL; int r; struct txn *tid = NULL; /* 1. Start Transaction */ /* lookup the mailbox to make sure it exists and get its acl */ do { r = mboxlist_mylookup(name, &mbentry, &tid, 1); } while(r == IMAP_AGAIN); /* Can't do this to an in-transit or reserved mailbox */ if (!r && mbentry->mbtype & (MBTYPE_MOVING | MBTYPE_RESERVE | MBTYPE_DELETED)) { r = IMAP_MAILBOX_NOTSUPPORTED; } /* 2. Set DB Entry */ if (!r) { /* ok, change the database */ free(mbentry->acl); mbentry->acl = xstrdupnull(newacl); r = mboxlist_update_entry(name, mbentry, &tid); if (r) { syslog(LOG_ERR, "DBERROR: error updating acl %s: %s", name, cyrusdb_strerror(r)); r = IMAP_IOERROR; } } /* 3. Commit transaction */ if (!r) { r = cyrusdb_commit(mbdb, tid); if (r) { syslog(LOG_ERR, "DBERROR: failed on commit %s: %s", name, cyrusdb_strerror(r)); r = IMAP_IOERROR; } tid = NULL; } /* 4. Change mupdate entry */ if (!r && config_mupdate_server) { mupdate_handle *mupdate_h = NULL; /* commit the update to MUPDATE */ char buf[MAX_PARTITION_LEN + HOSTNAME_SIZE + 2]; sprintf(buf, "%s!%s", config_servername, mbentry->partition); r = mupdate_connect(config_mupdate_server, NULL, &mupdate_h, NULL); if (r) { syslog(LOG_ERR, "cannot connect to mupdate server for syncacl on '%s'", name); } else { r = mupdate_activate(mupdate_h, name, buf, newacl); if(r) { syslog(LOG_ERR, "MUPDATE: can't update mailbox entry for '%s'", name); } } mupdate_disconnect(&mupdate_h); } if (r && tid) { /* if we are mid-transaction, abort it! */ int r2 = cyrusdb_abort(mbdb, tid); if (r2) { syslog(LOG_ERR, "DBERROR: error aborting txn in sync_setacls %s: %s", name, cyrusdb_strerror(r2)); } } mboxlist_entry_free(&mbentry); return r; } struct find_rock { ptrarray_t globs; struct namespace *namespace; const char *userid; const char *domain; int mb_category; int checkmboxlist; int issubs; int singlepercent; struct db *db; int isadmin; const struct auth_state *auth_state; mbname_t *mbname; mbentry_t *mbentry; int matchlen; findall_cb *proc; void *procrock; }; /* return non-zero if we like this one */ static int find_p(void *rockp, const char *key, size_t keylen, const char *data, size_t datalen) { struct find_rock *rock = (struct find_rock *) rockp; char intname[MAX_MAILBOX_PATH+1]; int i; /* skip any $RACL or future $ space keys */ if (key[0] == '$') return 0; memcpy(intname, key, keylen); intname[keylen] = 0; assert(!rock->mbname); rock->mbname = mbname_from_intname(intname); if (!rock->isadmin && !config_getswitch(IMAPOPT_CROSSDOMAINS)) { /* don't list mailboxes outside of the default domain */ if (strcmpsafe(rock->domain, mbname_domain(rock->mbname))) goto nomatch; } if (rock->mb_category && mbname_category(rock->mbname, rock->namespace, rock->userid) != rock->mb_category) goto nomatch; /* NOTE: this will all be cleaned up to be much more efficient sooner or later, with * a mbname_t being kept inside the mbentry, and the extname cached all the way to * final use. For now, we pay the cost of re-calculating for simplicity of the * changes to mbname_t itself */ const char *extname = mbname_extname(rock->mbname, rock->namespace, rock->userid); if (!extname) goto nomatch; int matchlen = 0; for (i = 0; i < rock->globs.count; i++) { glob *g = ptrarray_nth(&rock->globs, i); int thismatch = glob_test(g, extname); if (thismatch > matchlen) matchlen = thismatch; } /* If its not a match, skip it -- partial matches are ok. */ if (!matchlen) goto nomatch; rock->matchlen = matchlen; /* subs DB has empty keys */ if (rock->issubs) goto good; /* ignore entirely deleted records */ if (mboxlist_parse_entry(&rock->mbentry, key, keylen, data, datalen)) goto nomatch; /* nobody sees tombstones */ if (rock->mbentry->mbtype & MBTYPE_DELETED) goto nomatch; /* check acl */ if (!rock->isadmin) { /* always suppress deleted for non-admin */ if (mbname_isdeleted(rock->mbname)) goto nomatch; /* check the acls */ if (!(cyrus_acl_myrights(rock->auth_state, rock->mbentry->acl) & ACL_LOOKUP)) goto nomatch; } good: return 1; nomatch: mboxlist_entry_free(&rock->mbentry); mbname_free(&rock->mbname); return 0; } static int find_cb(void *rockp, /* XXX - confirm these are the same? - nah */ const char *key __attribute__((unused)), size_t keylen __attribute__((unused)), const char *data __attribute__((unused)), size_t datalen __attribute__((unused))) { struct find_rock *rock = (struct find_rock *) rockp; char *testname = NULL; int r = 0; int i; if (rock->checkmboxlist && !rock->mbentry) { r = mboxlist_lookup(mbname_intname(rock->mbname), &rock->mbentry, NULL); if (r) { if (r == IMAP_MAILBOX_NONEXISTENT) r = 0; goto done; } } const char *extname = mbname_extname(rock->mbname, rock->namespace, rock->userid); testname = xstrndup(extname, rock->matchlen); struct findall_data fdata = { testname, rock->mb_category, rock->mbentry, NULL }; if (rock->singlepercent) { char sep = rock->namespace->hier_sep; char *p = testname; /* we need to try all the previous names in order */ while ((p = strchr(p, sep)) != NULL) { *p = '\0'; /* only if this expression could fully match */ int matchlen = 0; for (i = 0; i < rock->globs.count; i++) { glob *g = ptrarray_nth(&rock->globs, i); int thismatch = glob_test(g, testname); if (thismatch > matchlen) matchlen = thismatch; } if (matchlen == (int)strlen(testname)) { r = (*rock->proc)(&fdata, rock->procrock); if (r) goto done; } /* replace the separator for the next longest name */ *p++ = sep; } } /* mbname confirms that it's an exact match */ if (rock->matchlen == (int)strlen(extname)) fdata.mbname = rock->mbname; r = (*rock->proc)(&fdata, rock->procrock); done: free(testname); mboxlist_entry_free(&rock->mbentry); mbname_free(&rock->mbname); return r; } struct allmb_rock { struct mboxlist_entry *mbentry; int flags; mboxlist_cb *proc; void *rock; }; static int allmbox_cb(void *rock, const char *key, size_t keylen, const char *data, size_t datalen) { struct allmb_rock *mbrock = (struct allmb_rock *)rock; if (!mbrock->mbentry) { int r = mboxlist_parse_entry(&mbrock->mbentry, key, keylen, data, datalen); if (r) return r; } return mbrock->proc(mbrock->mbentry, mbrock->rock); } static int allmbox_p(void *rock, const char *key, size_t keylen, const char *data, size_t datalen) { struct allmb_rock *mbrock = (struct allmb_rock *)rock; int r; /* skip any dollar keys */ if (keylen && key[0] == '$') return 0; /* free previous record */ mboxlist_entry_free(&mbrock->mbentry); r = mboxlist_parse_entry(&mbrock->mbentry, key, keylen, data, datalen); if (r) return 0; if (!(mbrock->flags & MBOXTREE_TOMBSTONES) && (mbrock->mbentry->mbtype & MBTYPE_DELETED)) return 0; return 1; /* process this record */ } EXPORTED int mboxlist_allmbox(const char *prefix, mboxlist_cb *proc, void *rock, int incdel) { struct allmb_rock mbrock = { NULL, 0, proc, rock }; int r = 0; if (incdel) mbrock.flags |= MBOXTREE_TOMBSTONES; if (!prefix) prefix = ""; r = cyrusdb_foreach(mbdb, prefix, strlen(prefix), allmbox_p, allmbox_cb, &mbrock, 0); mboxlist_entry_free(&mbrock.mbentry); return r; } EXPORTED int mboxlist_mboxtree(const char *mboxname, mboxlist_cb *proc, void *rock, int flags) { struct allmb_rock mbrock = { NULL, flags, proc, rock }; int r = 0; if (!(flags & MBOXTREE_SKIP_ROOT)) { r = cyrusdb_forone(mbdb, mboxname, strlen(mboxname), allmbox_p, allmbox_cb, &mbrock, 0); if (r) goto done; } if (!(flags & MBOXTREE_SKIP_CHILDREN)) { char *prefix = strconcat(mboxname, ".", (char *)NULL); r = cyrusdb_foreach(mbdb, prefix, strlen(prefix), allmbox_p, allmbox_cb, &mbrock, 0); free(prefix); if (r) goto done; } if ((flags & MBOXTREE_DELETED)) { struct buf buf = BUF_INITIALIZER; const char *p = strchr(mboxname, '!'); const char *dp = config_getstring(IMAPOPT_DELETEDPREFIX); if (p) { buf_printf(&buf, "%.*s!%s.%s", (int)(p-mboxname), mboxname, dp, p+1); } else { buf_printf(&buf, "%s.%s", dp, mboxname); } const char *prefix = buf_cstring(&buf); r = cyrusdb_foreach(mbdb, prefix, strlen(prefix), allmbox_p, allmbox_cb, &mbrock, 0); buf_free(&buf); if (r) goto done; } done: mboxlist_entry_free(&mbrock.mbentry); return r; } static int racls_del_cb(void *rock, const char *key, size_t keylen, const char *data __attribute__((unused)), size_t datalen __attribute__((unused))) { struct txn **txn = (struct txn **)rock; return cyrusdb_delete(mbdb, key, keylen, txn, /*force*/0); } static int racls_add_cb(const mbentry_t *mbentry, void *rock) { struct txn **txn = (struct txn **)rock; return mboxlist_update_racl(mbentry->name, NULL, mbentry, txn); } EXPORTED int mboxlist_set_racls(int enabled) { struct txn *tid = NULL; int r = 0; int now = !cyrusdb_fetch(mbdb, "$RACL", 5, NULL, NULL, &tid); if (now && !enabled) { syslog(LOG_NOTICE, "removing reverse acl support"); /* remove */ r = cyrusdb_foreach(mbdb, "$RACL", 5, NULL, racls_del_cb, &tid, &tid); } else if (enabled && !now) { /* add */ struct allmb_rock mbrock = { NULL, 0, racls_add_cb, &tid }; /* we can't use mboxlist_allmbox because it doesn't do transactions */ syslog(LOG_NOTICE, "adding reverse acl support"); r = cyrusdb_foreach(mbdb, "", 0, allmbox_p, allmbox_cb, &mbrock, &tid); if (r) { syslog(LOG_ERR, "ERROR: failed to add reverse acl support %s", error_message(r)); } mboxlist_entry_free(&mbrock.mbentry); if (!r) r = cyrusdb_store(mbdb, "$RACL", 5, "", 0, &tid); } if (r) cyrusdb_abort(mbdb, tid); else cyrusdb_commit(mbdb, tid); return r; } struct alluser_rock { char *prev; user_cb *proc; void *rock; }; static int alluser_cb(const mbentry_t *mbentry, void *rock) { struct alluser_rock *urock = (struct alluser_rock *)rock; char *userid = mboxname_to_userid(mbentry->name); int r = 0; if (userid) { if (strcmpsafe(urock->prev, userid)) { r = urock->proc(userid, urock->rock); free(urock->prev); urock->prev = xstrdup(userid); } free(userid); } return r; } EXPORTED int mboxlist_alluser(user_cb *proc, void *rock) { struct alluser_rock urock; int r = 0; urock.prev = NULL; urock.proc = proc; urock.rock = rock; r = mboxlist_allmbox(NULL, alluser_cb, &urock, /*flags*/0); free(urock.prev); return r; } struct raclrock { int prefixlen; strarray_t *list; }; static int racl_cb(void *rock, const char *key, size_t keylen, const char *data __attribute__((unused)), size_t datalen __attribute__((unused))) { struct raclrock *raclrock = (struct raclrock *)rock; strarray_appendm(raclrock->list, xstrndup(key + raclrock->prefixlen, keylen - raclrock->prefixlen)); return 0; } EXPORTED int mboxlist_usermboxtree(const char *userid, mboxlist_cb *proc, void *rock, int flags) { char *inbox = mboxname_user_mbox(userid, 0); int r = mboxlist_mboxtree(inbox, proc, rock, flags); if (flags & MBOXTREE_PLUS_RACL) { struct allmb_rock mbrock = { NULL, flags, proc, rock }; /* we're using reverse ACLs */ struct buf buf = BUF_INITIALIZER; strarray_t matches = STRARRAY_INITIALIZER; /* user items */ mboxlist_racl_key(1, userid, NULL, &buf); /* this is the prefix */ struct raclrock raclrock = { buf.len, &matches }; /* we only need to look inside the prefix still, but we keep the length * in raclrock pointing to the start of the mboxname part of the key so * we get correct names in matches */ r = cyrusdb_foreach(mbdb, buf.s, buf.len, NULL, racl_cb, &raclrock, NULL); buf_reset(&buf); /* shared items */ mboxlist_racl_key(0, userid, NULL, &buf); raclrock.prefixlen = buf.len; if (!r) r = cyrusdb_foreach(mbdb, buf.s, buf.len, NULL, racl_cb, &raclrock, NULL); /* XXX - later we need to sort the array when we've added groups */ int i; for (i = 0; !r && i < strarray_size(&matches); i++) { const char *mboxname = strarray_nth(&matches, i); r = cyrusdb_forone(mbdb, mboxname, strlen(mboxname), allmbox_p, allmbox_cb, &mbrock, 0); } buf_free(&buf); strarray_fini(&matches); mboxlist_entry_free(&mbrock.mbentry); } free(inbox); return r; } static int mboxlist_find_category(struct find_rock *rock, const char *prefix, size_t len) { int r = 0; if (!rock->issubs && !rock->isadmin && !cyrusdb_fetch(rock->db, "$RACL", 5, NULL, NULL, NULL)) { /* we're using reverse ACLs */ struct buf buf = BUF_INITIALIZER; strarray_t matches = STRARRAY_INITIALIZER; mboxlist_racl_key(rock->mb_category == MBNAME_OTHERUSER, rock->userid, NULL, &buf); /* this is the prefix */ struct raclrock raclrock = { buf.len, &matches }; /* we only need to look inside the prefix still, but we keep the length * in raclrock pointing to the start of the mboxname part of the key so * we get correct names in matches */ if (len) buf_appendmap(&buf, prefix, len); r = cyrusdb_foreach(rock->db, buf.s, buf.len, NULL, racl_cb, &raclrock, NULL); /* XXX - later we need to sort the array when we've added groups */ int i; for (i = 0; !r && i < strarray_size(&matches); i++) { const char *key = strarray_nth(&matches, i); r = cyrusdb_forone(rock->db, key, strlen(key), &find_p, &find_cb, rock, NULL); } strarray_fini(&matches); } else { r = cyrusdb_foreach(rock->db, prefix, len, &find_p, &find_cb, rock, NULL); } if (r == CYRUSDB_DONE) r = 0; return r; } /* * Find all mailboxes that match 'pattern'. * 'isadmin' is nonzero if user is a mailbox admin. 'userid' * is the user's login id. For each matching mailbox, calls * 'proc' with the name of the mailbox. If 'proc' ever returns * a nonzero value, mboxlist_findall immediately stops searching * and returns that value. 'rock' is passed along as an argument to proc in * case it wants some persistant storage or extra data. */ /* Find all mailboxes that match 'pattern'. */ static int mboxlist_do_find(struct find_rock *rock, const strarray_t *patterns) { const char *userid = rock->userid; int isadmin = rock->isadmin; int crossdomains = config_getswitch(IMAPOPT_CROSSDOMAINS); char inbox[MAX_MAILBOX_BUFFER]; size_t inboxlen = 0; size_t prefixlen, len; size_t domainlen = 0; size_t userlen = userid ? strlen(userid) : 0; char domainpat[MAX_MAILBOX_BUFFER]; /* do intra-domain fetches only */ char commonpat[MAX_MAILBOX_BUFFER]; int r = 0; int i; const char *p; if (patterns->count < 1) return 0; /* nothing to do */ for (i = 0; i < patterns->count; i++) { glob *g = glob_init(strarray_nth(patterns, i), rock->namespace->hier_sep); ptrarray_append(&rock->globs, g); } if (config_virtdomains && userid && (p = strchr(userid, '@'))) { userlen = p - userid; domainlen = strlen(p); /* includes separator */ snprintf(domainpat, sizeof(domainpat), "%s!", p+1); } else domainpat[0] = '\0'; /* calculate the inbox (with trailing .INBOX. for later use) */ if (userid && (!(p = strchr(userid, rock->namespace->hier_sep)) || ((p - userid) > (int)userlen)) && strlen(userid)+7 < MAX_MAILBOX_BUFFER) { char *t, *tmpuser = NULL; const char *inboxuser; if (domainlen) snprintf(inbox, sizeof(inbox), "%s!", userid+userlen+1); if (rock->namespace->hier_sep == '/' && (p = strchr(userid, '.'))) { tmpuser = xmalloc(userlen); memcpy(tmpuser, userid, userlen); t = tmpuser + (p - userid); while(t < (tmpuser + userlen)) { if (*t == '.') *t = '^'; t++; } inboxuser = tmpuser; } else inboxuser = userid; snprintf(inbox+domainlen, sizeof(inbox)-domainlen, "user.%.*s.INBOX.", (int)userlen, inboxuser); free(tmpuser); inboxlen = strlen(inbox) - 7; } else { userid = 0; } /* Find the common search prefix of all patterns */ const char *firstpat = strarray_nth(patterns, 0); for (prefixlen = 0; firstpat[prefixlen]; prefixlen++) { if (prefixlen >= MAX_MAILBOX_NAME) { r = IMAP_MAILBOX_BADNAME; goto done; } char c = firstpat[prefixlen]; for (i = 1; i < patterns->count; i++) { const char *pat = strarray_nth(patterns, i); if (pat[prefixlen] != c) break; } if (i < patterns->count) break; if (c == '*' || c == '%' || c == '?') break; commonpat[prefixlen] = c; } commonpat[prefixlen] = '\0'; if (patterns->count == 1) { /* Skip pattern which matches shared namespace prefix */ if (!strcmp(firstpat+prefixlen, "%")) rock->singlepercent = 2; /* output prefix regardless */ if (!strcmp(firstpat+prefixlen, "*%")) rock->singlepercent = 1; } /* * Personal (INBOX) namespace (only if not admin) */ if (userid && !isadmin) { /* first the INBOX */ rock->mb_category = MBNAME_INBOX; r = cyrusdb_forone(rock->db, inbox, inboxlen, &find_p, &find_cb, rock, NULL); if (r == CYRUSDB_DONE) r = 0; if (r) goto done; if (rock->namespace->isalt) { /* do exact INBOX subs before resetting the namebuffer */ rock->mb_category = MBNAME_INBOXSUB; r = cyrusdb_foreach(rock->db, inbox, inboxlen+7, &find_p, &find_cb, rock, NULL); if (r == CYRUSDB_DONE) r = 0; if (r) goto done; /* reset the the namebuffer */ r = (*rock->proc)(NULL, rock->procrock); if (r) goto done; } /* iterate through all the mailboxes under the user's inbox */ rock->mb_category = MBNAME_OWNER; r = cyrusdb_foreach(rock->db, inbox, inboxlen+1, &find_p, &find_cb, rock, NULL); if (r == CYRUSDB_DONE) r = 0; if (r) goto done; /* "Alt Prefix" folders */ if (rock->namespace->isalt) { /* reset the the namebuffer */ r = (*rock->proc)(NULL, rock->procrock); if (r) goto done; rock->mb_category = MBNAME_ALTINBOX; /* special case user.foo.INBOX. If we're singlepercent == 2, this could return DONE, in which case we don't need to foreach the rest of the altprefix space */ r = cyrusdb_forone(rock->db, inbox, inboxlen+6, &find_p, &find_cb, rock, NULL); if (r == CYRUSDB_DONE) goto skipalt; if (r) goto done; /* special case any other altprefix stuff */ rock->mb_category = MBNAME_ALTPREFIX; r = cyrusdb_foreach(rock->db, inbox, inboxlen+1, &find_p, &find_cb, rock, NULL); skipalt: /* we got a done, so skip out of the foreach early */ if (r == CYRUSDB_DONE) r = 0; if (r) goto done; } } /* * Other Users namespace * * If "Other Users*" can match pattern, search for those mailboxes next */ if (isadmin || rock->namespace->accessible[NAMESPACE_USER]) { len = strlen(rock->namespace->prefix[NAMESPACE_USER]); if (len) len--; // trailing separator if (!strncmp(rock->namespace->prefix[NAMESPACE_USER], commonpat, MIN(len, prefixlen))) { if (prefixlen < len) { /* we match all users */ strlcpy(domainpat+domainlen, "user.", sizeof(domainpat)-domainlen); } else { /* just those in this prefix */ strlcpy(domainpat+domainlen, "user.", sizeof(domainpat)-domainlen); strlcpy(domainpat+domainlen+5, commonpat+len+1, sizeof(domainpat)-domainlen-5); } rock->mb_category = MBNAME_OTHERUSER; /* because of how domains work, with crossdomains or admin you can't prefix at all :( */ size_t thislen = (isadmin || crossdomains) ? 0 : strlen(domainpat); /* reset the the namebuffer */ r = (*rock->proc)(NULL, rock->procrock); if (r) goto done; r = mboxlist_find_category(rock, domainpat, thislen); if (r) goto done; } } /* * Shared namespace * * search for all remaining mailboxes. * just bother looking at the ones that have the same pattern prefix. */ if (isadmin || rock->namespace->accessible[NAMESPACE_SHARED]) { len = strlen(rock->namespace->prefix[NAMESPACE_SHARED]); if (len) len--; // trailing separator if (!strncmp(rock->namespace->prefix[NAMESPACE_SHARED], commonpat, MIN(len, prefixlen))) { rock->mb_category = MBNAME_SHARED; /* reset the the namebuffer */ r = (*rock->proc)(NULL, rock->procrock); if (r) goto done; /* iterate through all the non-user folders on the server */ r = mboxlist_find_category(rock, domainpat, domainlen); if (r) goto done; } } /* finish with a reset call always */ r = (*rock->proc)(NULL, rock->procrock); done: for (i = 0; i < rock->globs.count; i++) { glob *g = ptrarray_nth(&rock->globs, i); glob_free(&g); } ptrarray_fini(&rock->globs); return r; } EXPORTED int mboxlist_findallmulti(struct namespace *namespace, const strarray_t *patterns, int isadmin, const char *userid, const struct auth_state *auth_state, findall_cb *proc, void *rock) { int r = 0; if (!namespace) namespace = mboxname_get_adminnamespace(); struct find_rock cbrock; memset(&cbrock, 0, sizeof(struct find_rock)); cbrock.auth_state = auth_state; cbrock.db = mbdb; cbrock.isadmin = isadmin; cbrock.namespace = namespace; cbrock.proc = proc; cbrock.procrock = rock; cbrock.userid = userid; if (userid) { const char *domp = strchr(userid, '@'); if (domp) cbrock.domain = domp + 1; } r = mboxlist_do_find(&cbrock, patterns); return r; } EXPORTED int mboxlist_findall(struct namespace *namespace, const char *pattern, int isadmin, const char *userid, const struct auth_state *auth_state, findall_cb *proc, void *rock) { strarray_t patterns = STRARRAY_INITIALIZER; strarray_append(&patterns, pattern); int r = mboxlist_findallmulti(namespace, &patterns, isadmin, userid, auth_state, proc, rock); strarray_fini(&patterns); return r; } EXPORTED int mboxlist_findone(struct namespace *namespace, const char *intname, int isadmin, const char *userid, const struct auth_state *auth_state, findall_cb *proc, void *rock) { int r = 0; if (!namespace) namespace = mboxname_get_adminnamespace(); struct find_rock cbrock; memset(&cbrock, 0, sizeof(struct find_rock)); cbrock.auth_state = auth_state; cbrock.db = mbdb; cbrock.isadmin = isadmin; cbrock.namespace = namespace; cbrock.proc = proc; cbrock.procrock = rock; cbrock.userid = userid; if (userid) { const char *domp = strchr(userid, '@'); if (domp) cbrock.domain = domp + 1; } mbname_t *mbname = mbname_from_intname(intname); glob *g = glob_init(mbname_extname(mbname, namespace, userid), namespace->hier_sep); ptrarray_append(&cbrock.globs, g); mbname_free(&mbname); r = cyrusdb_forone(cbrock.db, intname, strlen(intname), &find_p, &find_cb, &cbrock, NULL); glob_free(&g); ptrarray_fini(&cbrock.globs); return r; } static int exists_cb(const mbentry_t *mbentry __attribute__((unused)), void *rock) { int *exists = (int *)rock; *exists = 1; return CYRUSDB_DONE; /* one is enough */ } /* * Set all the resource quotas on, or create a quota root. */ EXPORTED int mboxlist_setquotas(const char *root, quota_t newquotas[QUOTA_NUMRESOURCES], int force) { struct quota q; int r; int res; struct txn *tid = NULL; struct mboxevent *mboxevents = NULL; struct mboxevent *quotachange_event = NULL; struct mboxevent *quotawithin_event = NULL; if (!root[0] || root[0] == '.' || strchr(root, '/') || strchr(root, '*') || strchr(root, '%') || strchr(root, '?')) { return IMAP_MAILBOX_BADNAME; } quota_init(&q, root); r = quota_read(&q, &tid, 1); if (!r) { int changed = 0; int underquota; /* has it changed? */ for (res = 0 ; res < QUOTA_NUMRESOURCES ; res++) { if (q.limits[res] != newquotas[res]) { underquota = 0; /* Prepare a QuotaChange event notification *now*. * * This is to ensure the QuotaChange is emitted before the * subsequent QuotaWithin (if the latter becomes applicable). */ if (quotachange_event == NULL) { quotachange_event = mboxevent_enqueue(EVENT_QUOTA_CHANGE, &mboxevents); } /* prepare a QuotaWithin event notification if now under quota */ if (quota_is_overquota(&q, res, NULL) && (!quota_is_overquota(&q, res, newquotas) || newquotas[res] == -1)) { if (quotawithin_event == NULL) quotawithin_event = mboxevent_enqueue(EVENT_QUOTA_WITHIN, &mboxevents); underquota++; } q.limits[res] = newquotas[res]; changed++; mboxevent_extract_quota(quotachange_event, &q, res); if (underquota) mboxevent_extract_quota(quotawithin_event, &q, res); } } if (changed) { r = quota_write(&q, &tid); if (quotachange_event == NULL) { quotachange_event = mboxevent_enqueue(EVENT_QUOTA_CHANGE, &mboxevents); } for (res = 0; res < QUOTA_NUMRESOURCES; res++) { mboxevent_extract_quota(quotachange_event, &q, res); } } if (!r) quota_commit(&tid); goto done; } if (r != IMAP_QUOTAROOT_NONEXISTENT) goto done; if (config_virtdomains && root[strlen(root)-1] == '!') { /* domain quota */ } else { mbentry_t *mbentry = NULL; /* look for a top-level mailbox in the proposed quotaroot */ r = mboxlist_lookup(root, &mbentry, NULL); if (r) { if (!force && r == IMAP_MAILBOX_NONEXISTENT) { mboxlist_mboxtree(root, exists_cb, &force, MBOXTREE_SKIP_ROOT); } /* are we going to force the create anyway? */ if (force) { r = 0; } } else if (mbentry->mbtype & (MBTYPE_REMOTE | MBTYPE_MOVING)) { /* Can't set quota on a remote mailbox */ r = IMAP_MAILBOX_NOTSUPPORTED; } mboxlist_entry_free(&mbentry); if (r) goto done; } /* safe against quota -f and other root change races */ r = quota_changelock(); if (r) goto done; /* initialise the quota */ memcpy(q.limits, newquotas, sizeof(q.limits)); r = quota_write(&q, &tid); if (r) goto done; /* prepare a QuotaChange event notification */ if (quotachange_event == NULL) quotachange_event = mboxevent_enqueue(EVENT_QUOTA_CHANGE, &mboxevents); for (res = 0; res < QUOTA_NUMRESOURCES; res++) { mboxevent_extract_quota(quotachange_event, &q, res); } quota_commit(&tid); /* recurse through mailboxes, setting the quota and finding * out the usage */ mboxlist_mboxtree(root, mboxlist_changequota, (void *)root, 0); quota_changelockrelease(); done: quota_free(&q); if (r && tid) quota_abort(&tid); if (!r) { sync_log_quota(root); /* send QuotaChange and QuotaWithin event notifications */ mboxevent_notify(&mboxevents); } mboxevent_freequeue(&mboxevents); return r; } /* * Remove a quota root */ EXPORTED int mboxlist_unsetquota(const char *root) { struct quota q; int r=0; if (!root[0] || root[0] == '.' || strchr(root, '/') || strchr(root, '*') || strchr(root, '%') || strchr(root, '?')) { return IMAP_MAILBOX_BADNAME; } quota_init(&q, root); r = quota_read(&q, NULL, 0); /* already unset */ if (r == IMAP_QUOTAROOT_NONEXISTENT) { r = 0; goto done; } if (r) goto done; r = quota_changelock(); /* * Have to remove it from all affected mailboxes */ mboxlist_mboxtree(root, mboxlist_rmquota, (void *)root, /*flags*/0); r = quota_deleteroot(root); quota_changelockrelease(); if (!r) sync_log_quota(root); done: quota_free(&q); return r; } EXPORTED modseq_t mboxlist_foldermodseq_dirty(struct mailbox *mailbox) { mbentry_t *mbentry = NULL; modseq_t ret = 0; if (mboxlist_mylookup(mailbox->name, &mbentry, NULL, 0)) return 0; ret = mbentry->foldermodseq = mailbox_modseq_dirty(mailbox); mboxlist_update(mbentry, 0); mboxlist_entry_free(&mbentry); return ret; } /* * ACL access canonicalization routine which ensures that 'owner' * retains lookup, administer, and create rights over a mailbox. */ EXPORTED int mboxlist_ensureOwnerRights(void *rock, const char *identifier, int myrights) { char *owner = (char *)rock; if (strcmp(identifier, owner) != 0) return myrights; return myrights|config_implicitrights; } /* * Helper function to remove the quota root for 'name' */ static int mboxlist_rmquota(const mbentry_t *mbentry, void *rock) { int r = 0; struct mailbox *mailbox = NULL; const char *oldroot = (const char *) rock; assert(oldroot != NULL); r = mailbox_open_iwl(mbentry->name, &mailbox); if (r) goto done; if (mailbox->quotaroot) { if (strcmp(mailbox->quotaroot, oldroot)) { /* Part of a different quota root */ goto done; } r = mailbox_set_quotaroot(mailbox, NULL); } done: mailbox_close(&mailbox); if (r) { syslog(LOG_ERR, "LOSTQUOTA: unable to remove quota root %s for %s: %s", oldroot, mbentry->name, error_message(r)); } /* not a huge tragedy if we failed, so always return success */ return 0; } /* * Helper function to change the quota root for 'name' to that pointed * to by the static global struct pointer 'mboxlist_newquota'. */ static int mboxlist_changequota(const mbentry_t *mbentry, void *rock) { int r = 0; struct mailbox *mailbox = NULL; const char *root = (const char *) rock; int res; quota_t quota_usage[QUOTA_NUMRESOURCES]; assert(root); r = mailbox_open_iwl(mbentry->name, &mailbox); if (r) goto done; mailbox_get_usage(mailbox, quota_usage); if (mailbox->quotaroot) { quota_t quota_diff[QUOTA_NUMRESOURCES]; if (strlen(mailbox->quotaroot) >= strlen(root)) { /* Part of a child quota root - skip */ goto done; } /* remove usage from the old quotaroot */ for (res = 0; res < QUOTA_NUMRESOURCES ; res++) { quota_diff[res] = -quota_usage[res]; } r = quota_update_useds(mailbox->quotaroot, quota_diff, mailbox->name); } /* update (or set) the quotaroot */ r = mailbox_set_quotaroot(mailbox, root); if (r) goto done; /* update the new quota root */ r = quota_update_useds(root, quota_usage, mailbox->name); done: mailbox_close(&mailbox); if (r) { syslog(LOG_ERR, "LOSTQUOTA: unable to change quota root for %s to %s: %s", mbentry->name, root, error_message(r)); } /* Note, we're a callback, and it's not a huge tragedy if we * fail, so we don't ever return a failure */ return 0; } /* must be called after cyrus_init */ EXPORTED void mboxlist_init(int myflags) { if (myflags & MBOXLIST_SYNC) { cyrusdb_sync(DB); } } EXPORTED void mboxlist_open(const char *fname) { int ret, flags; char *tofree = NULL; if (!fname) fname = config_getstring(IMAPOPT_MBOXLIST_DB_PATH); /* create db file name */ if (!fname) { tofree = strconcat(config_dir, FNAME_MBOXLIST, (char *)NULL); fname = tofree; } flags = CYRUSDB_CREATE; if (config_getswitch(IMAPOPT_IMPROVED_MBOXLIST_SORT)) { flags |= CYRUSDB_MBOXSORT; } ret = cyrusdb_open(DB, fname, flags, &mbdb); if (ret != 0) { syslog(LOG_ERR, "DBERROR: opening %s: %s", fname, cyrusdb_strerror(ret)); /* Exiting TEMPFAIL because Sendmail thinks this EC_OSFILE == permanent failure. */ fatal("can't read mailboxes file", EC_TEMPFAIL); } free(tofree); mboxlist_dbopen = 1; } EXPORTED void mboxlist_close(void) { int r; if (mboxlist_dbopen) { r = cyrusdb_close(mbdb); if (r) { syslog(LOG_ERR, "DBERROR: error closing mailboxes: %s", cyrusdb_strerror(r)); } mboxlist_dbopen = 0; } } EXPORTED void mboxlist_done(void) { /* DB->done() handled by cyrus_done() */ } /* * Open the subscription list for 'userid'. * * On success, returns zero. * On failure, returns an error code. */ static int mboxlist_opensubs(const char *userid, struct db **ret) { int r = 0, flags; char *subsfname; /* Build subscription list filename */ subsfname = user_hash_subs(userid); flags = CYRUSDB_CREATE; if (config_getswitch(IMAPOPT_IMPROVED_MBOXLIST_SORT)) { flags |= CYRUSDB_MBOXSORT; } r = cyrusdb_open(SUBDB, subsfname, flags, ret); if (r != CYRUSDB_OK) { r = IMAP_IOERROR; } free(subsfname); return r; } /* * Close a subscription file */ static void mboxlist_closesubs(struct db *sub) { cyrusdb_close(sub); } /* * Find subscribed mailboxes that match 'pattern'. * 'isadmin' is nonzero if user is a mailbox admin. 'userid' * is the user's login id. For each matching mailbox, calls * 'proc' with the name of the mailbox. */ EXPORTED int mboxlist_findsubmulti(struct namespace *namespace, const strarray_t *patterns, int isadmin, const char *userid, const struct auth_state *auth_state, findall_cb *proc, void *rock, int force) { int r = 0; if (!namespace) namespace = mboxname_get_adminnamespace(); struct find_rock cbrock; memset(&cbrock, 0, sizeof(struct find_rock)); /* open the subscription file that contains the mailboxes the user is subscribed to */ struct db *subs = NULL; r = mboxlist_opensubs(userid, &subs); if (r) return r; cbrock.auth_state = auth_state; cbrock.checkmboxlist = !force; cbrock.db = subs; cbrock.isadmin = isadmin; cbrock.issubs = 1; cbrock.namespace = namespace; cbrock.proc = proc; cbrock.procrock = rock; cbrock.userid = userid; if (userid) { const char *domp = strchr(userid, '@'); if (domp) cbrock.domain = domp + 1; } r = mboxlist_do_find(&cbrock, patterns); mboxlist_closesubs(subs); return r; } EXPORTED int mboxlist_findsub(struct namespace *namespace, const char *pattern, int isadmin, const char *userid, const struct auth_state *auth_state, findall_cb *proc, void *rock, int force) { strarray_t patterns = STRARRAY_INITIALIZER; strarray_append(&patterns, pattern); int r = mboxlist_findsubmulti(namespace, &patterns, isadmin, userid, auth_state, proc, rock, force); strarray_fini(&patterns); return r; } static int subsadd_cb(void *rock, const char *key, size_t keylen, const char *val __attribute__((unused)), size_t vallen __attribute__((unused))) { strarray_t *list = (strarray_t *)rock; strarray_appendm(list, xstrndup(key, keylen)); return 0; } EXPORTED strarray_t *mboxlist_sublist(const char *userid) { struct db *subs = NULL; strarray_t *list = strarray_new(); int r; /* open subs DB */ r = mboxlist_opensubs(userid, &subs); if (r) goto done; /* faster to do it all in a single slurp! */ r = cyrusdb_foreach(subs, "", 0, subsadd_cb, NULL, list, 0); mboxlist_closesubs(subs); done: if (r) { strarray_free(list); return NULL; } return list; } struct submb_rock { struct mboxlist_entry *mbentry; const char *userid; int flags; mboxlist_cb *proc; void *rock; }; static int usersubs_cb(void *rock, const char *key, size_t keylen, const char *data __attribute__((unused)), size_t datalen __attribute__((unused))) { struct submb_rock *mbrock = (struct submb_rock *) rock; char mboxname[MAX_MAILBOX_NAME+1]; int r; /* free previous record */ mboxlist_entry_free(&mbrock->mbentry); snprintf(mboxname, MAX_MAILBOX_NAME, "%.*s", (int) keylen, key); if ((mbrock->flags & MBOXTREE_SKIP_PERSONAL) && mboxname_userownsmailbox(mbrock->userid, mboxname)) return 0; r = mboxlist_lookup(mboxname, &mbrock->mbentry, NULL); if (r) { syslog(LOG_INFO, "mboxlist_lookup(%s) failed: %s", mboxname, error_message(r)); return r; } return mbrock->proc(mbrock->mbentry, mbrock->rock); } EXPORTED int mboxlist_usersubs(const char *userid, mboxlist_cb *proc, void *rock, int flags) { struct db *subs = NULL; struct submb_rock mbrock = { NULL, userid, flags, proc, rock }; int r = 0; /* open subs DB */ r = mboxlist_opensubs(userid, &subs); if (r) return r; /* faster to do it all in a single slurp! */ r = cyrusdb_foreach(subs, "", 0, NULL, usersubs_cb, &mbrock, 0); mboxlist_entry_free(&mbrock.mbentry); mboxlist_closesubs(subs); return r; } /* returns CYRUSDB_NOTFOUND if the folder doesn't exist, and 0 if it does! */ EXPORTED int mboxlist_checksub(const char *name, const char *userid) { int r; struct db *subs; const char *val; size_t vallen; r = mboxlist_opensubs(userid, &subs); if (!r) r = cyrusdb_fetch(subs, name, strlen(name), &val, &vallen, NULL); mboxlist_closesubs(subs); return r; } /* * Change 'user's subscription status for mailbox 'name'. * Subscribes if 'add' is nonzero, unsubscribes otherwise. * if 'force' is set, force the subscription through even if * we don't know about 'name'. */ EXPORTED int mboxlist_changesub(const char *name, const char *userid, const struct auth_state *auth_state, int add, int force, int notify) { mbentry_t *mbentry = NULL; int r; struct db *subs; struct mboxevent *mboxevent; if ((r = mboxlist_opensubs(userid, &subs)) != 0) { return r; } if (add && !force) { /* Ensure mailbox exists and can be seen by user */ if ((r = mboxlist_lookup(name, &mbentry, NULL))!=0) { mboxlist_closesubs(subs); return r; } if ((cyrus_acl_myrights(auth_state, mbentry->acl) & ACL_LOOKUP) == 0) { mboxlist_closesubs(subs); mboxlist_entry_free(&mbentry); return IMAP_MAILBOX_NONEXISTENT; } } if (add) { r = cyrusdb_store(subs, name, strlen(name), "", 0, NULL); } else { r = cyrusdb_delete(subs, name, strlen(name), NULL, 0); /* if it didn't exist, that's ok */ if (r == CYRUSDB_EXISTS) r = CYRUSDB_OK; } switch (r) { case CYRUSDB_OK: r = 0; break; default: r = IMAP_IOERROR; break; } sync_log_subscribe(userid, name); mboxlist_closesubs(subs); mboxlist_entry_free(&mbentry); /* prepare a MailboxSubscribe or MailboxUnSubscribe event notification */ if (notify && r == 0) { mboxevent = mboxevent_new(add ? EVENT_MAILBOX_SUBSCRIBE : EVENT_MAILBOX_UNSUBSCRIBE); mboxevent_set_access(mboxevent, NULL, NULL, userid, name, 1); mboxevent_notify(&mboxevent); mboxevent_free(&mboxevent); } return r; } /* Transaction Handlers */ EXPORTED int mboxlist_commit(struct txn *tid) { assert(tid); return cyrusdb_commit(mbdb, tid); } int mboxlist_abort(struct txn *tid) { assert(tid); return cyrusdb_abort(mbdb, tid); } EXPORTED int mboxlist_delayed_delete_isenabled(void) { enum enum_value config_delete_mode = config_getenum(IMAPOPT_DELETE_MODE); return(config_delete_mode == IMAP_ENUM_DELETE_MODE_DELAYED); }
./CrossVul/dataset_final_sorted/CWE-20/c/bad_2789_0
crossvul-cpp_data_good_3580_0
/* * Functions related to io context handling */ #include <linux/kernel.h> #include <linux/module.h> #include <linux/init.h> #include <linux/bio.h> #include <linux/blkdev.h> #include <linux/bootmem.h> /* for max_pfn/max_low_pfn */ #include "blk.h" /* * For io context allocations */ static struct kmem_cache *iocontext_cachep; static void cfq_dtor(struct io_context *ioc) { if (!hlist_empty(&ioc->cic_list)) { struct cfq_io_context *cic; cic = list_entry(ioc->cic_list.first, struct cfq_io_context, cic_list); cic->dtor(ioc); } } /* * IO Context helper functions. put_io_context() returns 1 if there are no * more users of this io context, 0 otherwise. */ int put_io_context(struct io_context *ioc) { if (ioc == NULL) return 1; BUG_ON(atomic_long_read(&ioc->refcount) == 0); if (atomic_long_dec_and_test(&ioc->refcount)) { rcu_read_lock(); if (ioc->aic && ioc->aic->dtor) ioc->aic->dtor(ioc->aic); cfq_dtor(ioc); rcu_read_unlock(); kmem_cache_free(iocontext_cachep, ioc); return 1; } return 0; } EXPORT_SYMBOL(put_io_context); static void cfq_exit(struct io_context *ioc) { rcu_read_lock(); if (!hlist_empty(&ioc->cic_list)) { struct cfq_io_context *cic; cic = list_entry(ioc->cic_list.first, struct cfq_io_context, cic_list); cic->exit(ioc); } rcu_read_unlock(); } /* Called by the exitting task */ void exit_io_context(void) { struct io_context *ioc; task_lock(current); ioc = current->io_context; current->io_context = NULL; task_unlock(current); if (atomic_dec_and_test(&ioc->nr_tasks)) { if (ioc->aic && ioc->aic->exit) ioc->aic->exit(ioc->aic); cfq_exit(ioc); } put_io_context(ioc); } struct io_context *alloc_io_context(gfp_t gfp_flags, int node) { struct io_context *ret; ret = kmem_cache_alloc_node(iocontext_cachep, gfp_flags, node); if (ret) { atomic_long_set(&ret->refcount, 1); atomic_set(&ret->nr_tasks, 1); spin_lock_init(&ret->lock); ret->ioprio_changed = 0; ret->ioprio = 0; ret->last_waited = jiffies; /* doesn't matter... */ ret->nr_batch_requests = 0; /* because this is 0 */ ret->aic = NULL; INIT_RADIX_TREE(&ret->radix_root, GFP_ATOMIC | __GFP_HIGH); INIT_HLIST_HEAD(&ret->cic_list); ret->ioc_data = NULL; } return ret; } /* * If the current task has no IO context then create one and initialise it. * Otherwise, return its existing IO context. * * This returned IO context doesn't have a specifically elevated refcount, * but since the current task itself holds a reference, the context can be * used in general code, so long as it stays within `current` context. */ struct io_context *current_io_context(gfp_t gfp_flags, int node) { struct task_struct *tsk = current; struct io_context *ret; ret = tsk->io_context; if (likely(ret)) return ret; ret = alloc_io_context(gfp_flags, node); if (ret) { /* make sure set_task_ioprio() sees the settings above */ smp_wmb(); tsk->io_context = ret; } return ret; } /* * If the current task has no IO context then create one and initialise it. * If it does have a context, take a ref on it. * * This is always called in the context of the task which submitted the I/O. */ struct io_context *get_io_context(gfp_t gfp_flags, int node) { struct io_context *ret = NULL; /* * Check for unlikely race with exiting task. ioc ref count is * zero when ioc is being detached. */ do { ret = current_io_context(gfp_flags, node); if (unlikely(!ret)) break; } while (!atomic_long_inc_not_zero(&ret->refcount)); return ret; } EXPORT_SYMBOL(get_io_context); void copy_io_context(struct io_context **pdst, struct io_context **psrc) { struct io_context *src = *psrc; struct io_context *dst = *pdst; if (src) { BUG_ON(atomic_long_read(&src->refcount) == 0); atomic_long_inc(&src->refcount); put_io_context(dst); *pdst = src; } } EXPORT_SYMBOL(copy_io_context); static int __init blk_ioc_init(void) { iocontext_cachep = kmem_cache_create("blkdev_ioc", sizeof(struct io_context), 0, SLAB_PANIC, NULL); return 0; } subsys_initcall(blk_ioc_init);
./CrossVul/dataset_final_sorted/CWE-20/c/good_3580_0
crossvul-cpp_data_bad_1583_0
/* * linux/mm/memory.c * * Copyright (C) 1991, 1992, 1993, 1994 Linus Torvalds */ /* * demand-loading started 01.12.91 - seems it is high on the list of * things wanted, and it should be easy to implement. - Linus */ /* * Ok, demand-loading was easy, shared pages a little bit tricker. Shared * pages started 02.12.91, seems to work. - Linus. * * Tested sharing by executing about 30 /bin/sh: under the old kernel it * would have taken more than the 6M I have free, but it worked well as * far as I could see. * * Also corrected some "invalidate()"s - I wasn't doing enough of them. */ /* * Real VM (paging to/from disk) started 18.12.91. Much more work and * thought has to go into this. Oh, well.. * 19.12.91 - works, somewhat. Sometimes I get faults, don't know why. * Found it. Everything seems to work now. * 20.12.91 - Ok, making the swap-device changeable like the root. */ /* * 05.04.94 - Multi-page memory management added for v1.1. * Idea by Alex Bligh (alex@cconcepts.co.uk) * * 16.07.99 - Support of BIGMEM added by Gerhard Wichert, Siemens AG * (Gerhard.Wichert@pdb.siemens.de) * * Aug/Sep 2004 Changed to four level page tables (Andi Kleen) */ #include <linux/kernel_stat.h> #include <linux/mm.h> #include <linux/hugetlb.h> #include <linux/mman.h> #include <linux/swap.h> #include <linux/highmem.h> #include <linux/pagemap.h> #include <linux/ksm.h> #include <linux/rmap.h> #include <linux/export.h> #include <linux/delayacct.h> #include <linux/init.h> #include <linux/writeback.h> #include <linux/memcontrol.h> #include <linux/mmu_notifier.h> #include <linux/kallsyms.h> #include <linux/swapops.h> #include <linux/elf.h> #include <linux/gfp.h> #include <linux/migrate.h> #include <linux/string.h> #include <linux/dma-debug.h> #include <linux/debugfs.h> #include <asm/io.h> #include <asm/pgalloc.h> #include <asm/uaccess.h> #include <asm/tlb.h> #include <asm/tlbflush.h> #include <asm/pgtable.h> #include "internal.h" #ifdef LAST_CPUPID_NOT_IN_PAGE_FLAGS #warning Unfortunate NUMA and NUMA Balancing config, growing page-frame for last_cpupid. #endif #ifndef CONFIG_NEED_MULTIPLE_NODES /* use the per-pgdat data instead for discontigmem - mbligh */ unsigned long max_mapnr; struct page *mem_map; EXPORT_SYMBOL(max_mapnr); EXPORT_SYMBOL(mem_map); #endif /* * A number of key systems in x86 including ioremap() rely on the assumption * that high_memory defines the upper bound on direct map memory, then end * of ZONE_NORMAL. Under CONFIG_DISCONTIG this means that max_low_pfn and * highstart_pfn must be the same; there must be no gap between ZONE_NORMAL * and ZONE_HIGHMEM. */ void * high_memory; EXPORT_SYMBOL(high_memory); /* * Randomize the address space (stacks, mmaps, brk, etc.). * * ( When CONFIG_COMPAT_BRK=y we exclude brk from randomization, * as ancient (libc5 based) binaries can segfault. ) */ int randomize_va_space __read_mostly = #ifdef CONFIG_COMPAT_BRK 1; #else 2; #endif static int __init disable_randmaps(char *s) { randomize_va_space = 0; return 1; } __setup("norandmaps", disable_randmaps); unsigned long zero_pfn __read_mostly; unsigned long highest_memmap_pfn __read_mostly; EXPORT_SYMBOL(zero_pfn); /* * CONFIG_MMU architectures set up ZERO_PAGE in their paging_init() */ static int __init init_zero_pfn(void) { zero_pfn = page_to_pfn(ZERO_PAGE(0)); return 0; } core_initcall(init_zero_pfn); #if defined(SPLIT_RSS_COUNTING) void sync_mm_rss(struct mm_struct *mm) { int i; for (i = 0; i < NR_MM_COUNTERS; i++) { if (current->rss_stat.count[i]) { add_mm_counter(mm, i, current->rss_stat.count[i]); current->rss_stat.count[i] = 0; } } current->rss_stat.events = 0; } static void add_mm_counter_fast(struct mm_struct *mm, int member, int val) { struct task_struct *task = current; if (likely(task->mm == mm)) task->rss_stat.count[member] += val; else add_mm_counter(mm, member, val); } #define inc_mm_counter_fast(mm, member) add_mm_counter_fast(mm, member, 1) #define dec_mm_counter_fast(mm, member) add_mm_counter_fast(mm, member, -1) /* sync counter once per 64 page faults */ #define TASK_RSS_EVENTS_THRESH (64) static void check_sync_rss_stat(struct task_struct *task) { if (unlikely(task != current)) return; if (unlikely(task->rss_stat.events++ > TASK_RSS_EVENTS_THRESH)) sync_mm_rss(task->mm); } #else /* SPLIT_RSS_COUNTING */ #define inc_mm_counter_fast(mm, member) inc_mm_counter(mm, member) #define dec_mm_counter_fast(mm, member) dec_mm_counter(mm, member) static void check_sync_rss_stat(struct task_struct *task) { } #endif /* SPLIT_RSS_COUNTING */ #ifdef HAVE_GENERIC_MMU_GATHER static int tlb_next_batch(struct mmu_gather *tlb) { struct mmu_gather_batch *batch; batch = tlb->active; if (batch->next) { tlb->active = batch->next; return 1; } if (tlb->batch_count == MAX_GATHER_BATCH_COUNT) return 0; batch = (void *)__get_free_pages(GFP_NOWAIT | __GFP_NOWARN, 0); if (!batch) return 0; tlb->batch_count++; batch->next = NULL; batch->nr = 0; batch->max = MAX_GATHER_BATCH; tlb->active->next = batch; tlb->active = batch; return 1; } /* tlb_gather_mmu * Called to initialize an (on-stack) mmu_gather structure for page-table * tear-down from @mm. The @fullmm argument is used when @mm is without * users and we're going to destroy the full address space (exit/execve). */ void tlb_gather_mmu(struct mmu_gather *tlb, struct mm_struct *mm, unsigned long start, unsigned long end) { tlb->mm = mm; /* Is it from 0 to ~0? */ tlb->fullmm = !(start | (end+1)); tlb->need_flush_all = 0; tlb->local.next = NULL; tlb->local.nr = 0; tlb->local.max = ARRAY_SIZE(tlb->__pages); tlb->active = &tlb->local; tlb->batch_count = 0; #ifdef CONFIG_HAVE_RCU_TABLE_FREE tlb->batch = NULL; #endif __tlb_reset_range(tlb); } static void tlb_flush_mmu_tlbonly(struct mmu_gather *tlb) { if (!tlb->end) return; tlb_flush(tlb); mmu_notifier_invalidate_range(tlb->mm, tlb->start, tlb->end); #ifdef CONFIG_HAVE_RCU_TABLE_FREE tlb_table_flush(tlb); #endif __tlb_reset_range(tlb); } static void tlb_flush_mmu_free(struct mmu_gather *tlb) { struct mmu_gather_batch *batch; for (batch = &tlb->local; batch && batch->nr; batch = batch->next) { free_pages_and_swap_cache(batch->pages, batch->nr); batch->nr = 0; } tlb->active = &tlb->local; } void tlb_flush_mmu(struct mmu_gather *tlb) { tlb_flush_mmu_tlbonly(tlb); tlb_flush_mmu_free(tlb); } /* tlb_finish_mmu * Called at the end of the shootdown operation to free up any resources * that were required. */ void tlb_finish_mmu(struct mmu_gather *tlb, unsigned long start, unsigned long end) { struct mmu_gather_batch *batch, *next; tlb_flush_mmu(tlb); /* keep the page table cache within bounds */ check_pgt_cache(); for (batch = tlb->local.next; batch; batch = next) { next = batch->next; free_pages((unsigned long)batch, 0); } tlb->local.next = NULL; } /* __tlb_remove_page * Must perform the equivalent to __free_pte(pte_get_and_clear(ptep)), while * handling the additional races in SMP caused by other CPUs caching valid * mappings in their TLBs. Returns the number of free page slots left. * When out of page slots we must call tlb_flush_mmu(). */ int __tlb_remove_page(struct mmu_gather *tlb, struct page *page) { struct mmu_gather_batch *batch; VM_BUG_ON(!tlb->end); batch = tlb->active; batch->pages[batch->nr++] = page; if (batch->nr == batch->max) { if (!tlb_next_batch(tlb)) return 0; batch = tlb->active; } VM_BUG_ON_PAGE(batch->nr > batch->max, page); return batch->max - batch->nr; } #endif /* HAVE_GENERIC_MMU_GATHER */ #ifdef CONFIG_HAVE_RCU_TABLE_FREE /* * See the comment near struct mmu_table_batch. */ static void tlb_remove_table_smp_sync(void *arg) { /* Simply deliver the interrupt */ } static void tlb_remove_table_one(void *table) { /* * This isn't an RCU grace period and hence the page-tables cannot be * assumed to be actually RCU-freed. * * It is however sufficient for software page-table walkers that rely on * IRQ disabling. See the comment near struct mmu_table_batch. */ smp_call_function(tlb_remove_table_smp_sync, NULL, 1); __tlb_remove_table(table); } static void tlb_remove_table_rcu(struct rcu_head *head) { struct mmu_table_batch *batch; int i; batch = container_of(head, struct mmu_table_batch, rcu); for (i = 0; i < batch->nr; i++) __tlb_remove_table(batch->tables[i]); free_page((unsigned long)batch); } void tlb_table_flush(struct mmu_gather *tlb) { struct mmu_table_batch **batch = &tlb->batch; if (*batch) { call_rcu_sched(&(*batch)->rcu, tlb_remove_table_rcu); *batch = NULL; } } void tlb_remove_table(struct mmu_gather *tlb, void *table) { struct mmu_table_batch **batch = &tlb->batch; /* * When there's less then two users of this mm there cannot be a * concurrent page-table walk. */ if (atomic_read(&tlb->mm->mm_users) < 2) { __tlb_remove_table(table); return; } if (*batch == NULL) { *batch = (struct mmu_table_batch *)__get_free_page(GFP_NOWAIT | __GFP_NOWARN); if (*batch == NULL) { tlb_remove_table_one(table); return; } (*batch)->nr = 0; } (*batch)->tables[(*batch)->nr++] = table; if ((*batch)->nr == MAX_TABLE_BATCH) tlb_table_flush(tlb); } #endif /* CONFIG_HAVE_RCU_TABLE_FREE */ /* * Note: this doesn't free the actual pages themselves. That * has been handled earlier when unmapping all the memory regions. */ static void free_pte_range(struct mmu_gather *tlb, pmd_t *pmd, unsigned long addr) { pgtable_t token = pmd_pgtable(*pmd); pmd_clear(pmd); pte_free_tlb(tlb, token, addr); atomic_long_dec(&tlb->mm->nr_ptes); } static inline void free_pmd_range(struct mmu_gather *tlb, pud_t *pud, unsigned long addr, unsigned long end, unsigned long floor, unsigned long ceiling) { pmd_t *pmd; unsigned long next; unsigned long start; start = addr; pmd = pmd_offset(pud, addr); do { next = pmd_addr_end(addr, end); if (pmd_none_or_clear_bad(pmd)) continue; free_pte_range(tlb, pmd, addr); } while (pmd++, addr = next, addr != end); start &= PUD_MASK; if (start < floor) return; if (ceiling) { ceiling &= PUD_MASK; if (!ceiling) return; } if (end - 1 > ceiling - 1) return; pmd = pmd_offset(pud, start); pud_clear(pud); pmd_free_tlb(tlb, pmd, start); mm_dec_nr_pmds(tlb->mm); } static inline void free_pud_range(struct mmu_gather *tlb, pgd_t *pgd, unsigned long addr, unsigned long end, unsigned long floor, unsigned long ceiling) { pud_t *pud; unsigned long next; unsigned long start; start = addr; pud = pud_offset(pgd, addr); do { next = pud_addr_end(addr, end); if (pud_none_or_clear_bad(pud)) continue; free_pmd_range(tlb, pud, addr, next, floor, ceiling); } while (pud++, addr = next, addr != end); start &= PGDIR_MASK; if (start < floor) return; if (ceiling) { ceiling &= PGDIR_MASK; if (!ceiling) return; } if (end - 1 > ceiling - 1) return; pud = pud_offset(pgd, start); pgd_clear(pgd); pud_free_tlb(tlb, pud, start); } /* * This function frees user-level page tables of a process. */ void free_pgd_range(struct mmu_gather *tlb, unsigned long addr, unsigned long end, unsigned long floor, unsigned long ceiling) { pgd_t *pgd; unsigned long next; /* * The next few lines have given us lots of grief... * * Why are we testing PMD* at this top level? Because often * there will be no work to do at all, and we'd prefer not to * go all the way down to the bottom just to discover that. * * Why all these "- 1"s? Because 0 represents both the bottom * of the address space and the top of it (using -1 for the * top wouldn't help much: the masks would do the wrong thing). * The rule is that addr 0 and floor 0 refer to the bottom of * the address space, but end 0 and ceiling 0 refer to the top * Comparisons need to use "end - 1" and "ceiling - 1" (though * that end 0 case should be mythical). * * Wherever addr is brought up or ceiling brought down, we must * be careful to reject "the opposite 0" before it confuses the * subsequent tests. But what about where end is brought down * by PMD_SIZE below? no, end can't go down to 0 there. * * Whereas we round start (addr) and ceiling down, by different * masks at different levels, in order to test whether a table * now has no other vmas using it, so can be freed, we don't * bother to round floor or end up - the tests don't need that. */ addr &= PMD_MASK; if (addr < floor) { addr += PMD_SIZE; if (!addr) return; } if (ceiling) { ceiling &= PMD_MASK; if (!ceiling) return; } if (end - 1 > ceiling - 1) end -= PMD_SIZE; if (addr > end - 1) return; pgd = pgd_offset(tlb->mm, addr); do { next = pgd_addr_end(addr, end); if (pgd_none_or_clear_bad(pgd)) continue; free_pud_range(tlb, pgd, addr, next, floor, ceiling); } while (pgd++, addr = next, addr != end); } void free_pgtables(struct mmu_gather *tlb, struct vm_area_struct *vma, unsigned long floor, unsigned long ceiling) { while (vma) { struct vm_area_struct *next = vma->vm_next; unsigned long addr = vma->vm_start; /* * Hide vma from rmap and truncate_pagecache before freeing * pgtables */ unlink_anon_vmas(vma); unlink_file_vma(vma); if (is_vm_hugetlb_page(vma)) { hugetlb_free_pgd_range(tlb, addr, vma->vm_end, floor, next? next->vm_start: ceiling); } else { /* * Optimization: gather nearby vmas into one call down */ while (next && next->vm_start <= vma->vm_end + PMD_SIZE && !is_vm_hugetlb_page(next)) { vma = next; next = vma->vm_next; unlink_anon_vmas(vma); unlink_file_vma(vma); } free_pgd_range(tlb, addr, vma->vm_end, floor, next? next->vm_start: ceiling); } vma = next; } } int __pte_alloc(struct mm_struct *mm, struct vm_area_struct *vma, pmd_t *pmd, unsigned long address) { spinlock_t *ptl; pgtable_t new = pte_alloc_one(mm, address); int wait_split_huge_page; if (!new) return -ENOMEM; /* * Ensure all pte setup (eg. pte page lock and page clearing) are * visible before the pte is made visible to other CPUs by being * put into page tables. * * The other side of the story is the pointer chasing in the page * table walking code (when walking the page table without locking; * ie. most of the time). Fortunately, these data accesses consist * of a chain of data-dependent loads, meaning most CPUs (alpha * being the notable exception) will already guarantee loads are * seen in-order. See the alpha page table accessors for the * smp_read_barrier_depends() barriers in page table walking code. */ smp_wmb(); /* Could be smp_wmb__xxx(before|after)_spin_lock */ ptl = pmd_lock(mm, pmd); wait_split_huge_page = 0; if (likely(pmd_none(*pmd))) { /* Has another populated it ? */ atomic_long_inc(&mm->nr_ptes); pmd_populate(mm, pmd, new); new = NULL; } else if (unlikely(pmd_trans_splitting(*pmd))) wait_split_huge_page = 1; spin_unlock(ptl); if (new) pte_free(mm, new); if (wait_split_huge_page) wait_split_huge_page(vma->anon_vma, pmd); return 0; } int __pte_alloc_kernel(pmd_t *pmd, unsigned long address) { pte_t *new = pte_alloc_one_kernel(&init_mm, address); if (!new) return -ENOMEM; smp_wmb(); /* See comment in __pte_alloc */ spin_lock(&init_mm.page_table_lock); if (likely(pmd_none(*pmd))) { /* Has another populated it ? */ pmd_populate_kernel(&init_mm, pmd, new); new = NULL; } else VM_BUG_ON(pmd_trans_splitting(*pmd)); spin_unlock(&init_mm.page_table_lock); if (new) pte_free_kernel(&init_mm, new); return 0; } static inline void init_rss_vec(int *rss) { memset(rss, 0, sizeof(int) * NR_MM_COUNTERS); } static inline void add_mm_rss_vec(struct mm_struct *mm, int *rss) { int i; if (current->mm == mm) sync_mm_rss(mm); for (i = 0; i < NR_MM_COUNTERS; i++) if (rss[i]) add_mm_counter(mm, i, rss[i]); } /* * This function is called to print an error when a bad pte * is found. For example, we might have a PFN-mapped pte in * a region that doesn't allow it. * * The calling function must still handle the error. */ static void print_bad_pte(struct vm_area_struct *vma, unsigned long addr, pte_t pte, struct page *page) { pgd_t *pgd = pgd_offset(vma->vm_mm, addr); pud_t *pud = pud_offset(pgd, addr); pmd_t *pmd = pmd_offset(pud, addr); struct address_space *mapping; pgoff_t index; static unsigned long resume; static unsigned long nr_shown; static unsigned long nr_unshown; /* * Allow a burst of 60 reports, then keep quiet for that minute; * or allow a steady drip of one report per second. */ if (nr_shown == 60) { if (time_before(jiffies, resume)) { nr_unshown++; return; } if (nr_unshown) { printk(KERN_ALERT "BUG: Bad page map: %lu messages suppressed\n", nr_unshown); nr_unshown = 0; } nr_shown = 0; } if (nr_shown++ == 0) resume = jiffies + 60 * HZ; mapping = vma->vm_file ? vma->vm_file->f_mapping : NULL; index = linear_page_index(vma, addr); printk(KERN_ALERT "BUG: Bad page map in process %s pte:%08llx pmd:%08llx\n", current->comm, (long long)pte_val(pte), (long long)pmd_val(*pmd)); if (page) dump_page(page, "bad pte"); printk(KERN_ALERT "addr:%p vm_flags:%08lx anon_vma:%p mapping:%p index:%lx\n", (void *)addr, vma->vm_flags, vma->anon_vma, mapping, index); /* * Choose text because data symbols depend on CONFIG_KALLSYMS_ALL=y */ pr_alert("file:%pD fault:%pf mmap:%pf readpage:%pf\n", vma->vm_file, vma->vm_ops ? vma->vm_ops->fault : NULL, vma->vm_file ? vma->vm_file->f_op->mmap : NULL, mapping ? mapping->a_ops->readpage : NULL); dump_stack(); add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE); } /* * vm_normal_page -- This function gets the "struct page" associated with a pte. * * "Special" mappings do not wish to be associated with a "struct page" (either * it doesn't exist, or it exists but they don't want to touch it). In this * case, NULL is returned here. "Normal" mappings do have a struct page. * * There are 2 broad cases. Firstly, an architecture may define a pte_special() * pte bit, in which case this function is trivial. Secondly, an architecture * may not have a spare pte bit, which requires a more complicated scheme, * described below. * * A raw VM_PFNMAP mapping (ie. one that is not COWed) is always considered a * special mapping (even if there are underlying and valid "struct pages"). * COWed pages of a VM_PFNMAP are always normal. * * The way we recognize COWed pages within VM_PFNMAP mappings is through the * rules set up by "remap_pfn_range()": the vma will have the VM_PFNMAP bit * set, and the vm_pgoff will point to the first PFN mapped: thus every special * mapping will always honor the rule * * pfn_of_page == vma->vm_pgoff + ((addr - vma->vm_start) >> PAGE_SHIFT) * * And for normal mappings this is false. * * This restricts such mappings to be a linear translation from virtual address * to pfn. To get around this restriction, we allow arbitrary mappings so long * as the vma is not a COW mapping; in that case, we know that all ptes are * special (because none can have been COWed). * * * In order to support COW of arbitrary special mappings, we have VM_MIXEDMAP. * * VM_MIXEDMAP mappings can likewise contain memory with or without "struct * page" backing, however the difference is that _all_ pages with a struct * page (that is, those where pfn_valid is true) are refcounted and considered * normal pages by the VM. The disadvantage is that pages are refcounted * (which can be slower and simply not an option for some PFNMAP users). The * advantage is that we don't have to follow the strict linearity rule of * PFNMAP mappings in order to support COWable mappings. * */ #ifdef __HAVE_ARCH_PTE_SPECIAL # define HAVE_PTE_SPECIAL 1 #else # define HAVE_PTE_SPECIAL 0 #endif struct page *vm_normal_page(struct vm_area_struct *vma, unsigned long addr, pte_t pte) { unsigned long pfn = pte_pfn(pte); if (HAVE_PTE_SPECIAL) { if (likely(!pte_special(pte))) goto check_pfn; if (vma->vm_ops && vma->vm_ops->find_special_page) return vma->vm_ops->find_special_page(vma, addr); if (vma->vm_flags & (VM_PFNMAP | VM_MIXEDMAP)) return NULL; if (!is_zero_pfn(pfn)) print_bad_pte(vma, addr, pte, NULL); return NULL; } /* !HAVE_PTE_SPECIAL case follows: */ if (unlikely(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP))) { if (vma->vm_flags & VM_MIXEDMAP) { if (!pfn_valid(pfn)) return NULL; goto out; } else { unsigned long off; off = (addr - vma->vm_start) >> PAGE_SHIFT; if (pfn == vma->vm_pgoff + off) return NULL; if (!is_cow_mapping(vma->vm_flags)) return NULL; } } if (is_zero_pfn(pfn)) return NULL; check_pfn: if (unlikely(pfn > highest_memmap_pfn)) { print_bad_pte(vma, addr, pte, NULL); return NULL; } /* * NOTE! We still have PageReserved() pages in the page tables. * eg. VDSO mappings can cause them to exist. */ out: return pfn_to_page(pfn); } /* * copy one vm_area from one task to the other. Assumes the page tables * already present in the new task to be cleared in the whole range * covered by this vma. */ static inline unsigned long copy_one_pte(struct mm_struct *dst_mm, struct mm_struct *src_mm, pte_t *dst_pte, pte_t *src_pte, struct vm_area_struct *vma, unsigned long addr, int *rss) { unsigned long vm_flags = vma->vm_flags; pte_t pte = *src_pte; struct page *page; /* pte contains position in swap or file, so copy. */ if (unlikely(!pte_present(pte))) { swp_entry_t entry = pte_to_swp_entry(pte); if (likely(!non_swap_entry(entry))) { if (swap_duplicate(entry) < 0) return entry.val; /* make sure dst_mm is on swapoff's mmlist. */ if (unlikely(list_empty(&dst_mm->mmlist))) { spin_lock(&mmlist_lock); if (list_empty(&dst_mm->mmlist)) list_add(&dst_mm->mmlist, &src_mm->mmlist); spin_unlock(&mmlist_lock); } rss[MM_SWAPENTS]++; } else if (is_migration_entry(entry)) { page = migration_entry_to_page(entry); if (PageAnon(page)) rss[MM_ANONPAGES]++; else rss[MM_FILEPAGES]++; if (is_write_migration_entry(entry) && is_cow_mapping(vm_flags)) { /* * COW mappings require pages in both * parent and child to be set to read. */ make_migration_entry_read(&entry); pte = swp_entry_to_pte(entry); if (pte_swp_soft_dirty(*src_pte)) pte = pte_swp_mksoft_dirty(pte); set_pte_at(src_mm, addr, src_pte, pte); } } goto out_set_pte; } /* * If it's a COW mapping, write protect it both * in the parent and the child */ if (is_cow_mapping(vm_flags)) { ptep_set_wrprotect(src_mm, addr, src_pte); pte = pte_wrprotect(pte); } /* * If it's a shared mapping, mark it clean in * the child */ if (vm_flags & VM_SHARED) pte = pte_mkclean(pte); pte = pte_mkold(pte); page = vm_normal_page(vma, addr, pte); if (page) { get_page(page); page_dup_rmap(page); if (PageAnon(page)) rss[MM_ANONPAGES]++; else rss[MM_FILEPAGES]++; } out_set_pte: set_pte_at(dst_mm, addr, dst_pte, pte); return 0; } static int copy_pte_range(struct mm_struct *dst_mm, struct mm_struct *src_mm, pmd_t *dst_pmd, pmd_t *src_pmd, struct vm_area_struct *vma, unsigned long addr, unsigned long end) { pte_t *orig_src_pte, *orig_dst_pte; pte_t *src_pte, *dst_pte; spinlock_t *src_ptl, *dst_ptl; int progress = 0; int rss[NR_MM_COUNTERS]; swp_entry_t entry = (swp_entry_t){0}; again: init_rss_vec(rss); dst_pte = pte_alloc_map_lock(dst_mm, dst_pmd, addr, &dst_ptl); if (!dst_pte) return -ENOMEM; src_pte = pte_offset_map(src_pmd, addr); src_ptl = pte_lockptr(src_mm, src_pmd); spin_lock_nested(src_ptl, SINGLE_DEPTH_NESTING); orig_src_pte = src_pte; orig_dst_pte = dst_pte; arch_enter_lazy_mmu_mode(); do { /* * We are holding two locks at this point - either of them * could generate latencies in another task on another CPU. */ if (progress >= 32) { progress = 0; if (need_resched() || spin_needbreak(src_ptl) || spin_needbreak(dst_ptl)) break; } if (pte_none(*src_pte)) { progress++; continue; } entry.val = copy_one_pte(dst_mm, src_mm, dst_pte, src_pte, vma, addr, rss); if (entry.val) break; progress += 8; } while (dst_pte++, src_pte++, addr += PAGE_SIZE, addr != end); arch_leave_lazy_mmu_mode(); spin_unlock(src_ptl); pte_unmap(orig_src_pte); add_mm_rss_vec(dst_mm, rss); pte_unmap_unlock(orig_dst_pte, dst_ptl); cond_resched(); if (entry.val) { if (add_swap_count_continuation(entry, GFP_KERNEL) < 0) return -ENOMEM; progress = 0; } if (addr != end) goto again; return 0; } static inline int copy_pmd_range(struct mm_struct *dst_mm, struct mm_struct *src_mm, pud_t *dst_pud, pud_t *src_pud, struct vm_area_struct *vma, unsigned long addr, unsigned long end) { pmd_t *src_pmd, *dst_pmd; unsigned long next; dst_pmd = pmd_alloc(dst_mm, dst_pud, addr); if (!dst_pmd) return -ENOMEM; src_pmd = pmd_offset(src_pud, addr); do { next = pmd_addr_end(addr, end); if (pmd_trans_huge(*src_pmd)) { int err; VM_BUG_ON(next-addr != HPAGE_PMD_SIZE); err = copy_huge_pmd(dst_mm, src_mm, dst_pmd, src_pmd, addr, vma); if (err == -ENOMEM) return -ENOMEM; if (!err) continue; /* fall through */ } if (pmd_none_or_clear_bad(src_pmd)) continue; if (copy_pte_range(dst_mm, src_mm, dst_pmd, src_pmd, vma, addr, next)) return -ENOMEM; } while (dst_pmd++, src_pmd++, addr = next, addr != end); return 0; } static inline int copy_pud_range(struct mm_struct *dst_mm, struct mm_struct *src_mm, pgd_t *dst_pgd, pgd_t *src_pgd, struct vm_area_struct *vma, unsigned long addr, unsigned long end) { pud_t *src_pud, *dst_pud; unsigned long next; dst_pud = pud_alloc(dst_mm, dst_pgd, addr); if (!dst_pud) return -ENOMEM; src_pud = pud_offset(src_pgd, addr); do { next = pud_addr_end(addr, end); if (pud_none_or_clear_bad(src_pud)) continue; if (copy_pmd_range(dst_mm, src_mm, dst_pud, src_pud, vma, addr, next)) return -ENOMEM; } while (dst_pud++, src_pud++, addr = next, addr != end); return 0; } int copy_page_range(struct mm_struct *dst_mm, struct mm_struct *src_mm, struct vm_area_struct *vma) { pgd_t *src_pgd, *dst_pgd; unsigned long next; unsigned long addr = vma->vm_start; unsigned long end = vma->vm_end; unsigned long mmun_start; /* For mmu_notifiers */ unsigned long mmun_end; /* For mmu_notifiers */ bool is_cow; int ret; /* * Don't copy ptes where a page fault will fill them correctly. * Fork becomes much lighter when there are big shared or private * readonly mappings. The tradeoff is that copy_page_range is more * efficient than faulting. */ if (!(vma->vm_flags & (VM_HUGETLB | VM_PFNMAP | VM_MIXEDMAP)) && !vma->anon_vma) return 0; if (is_vm_hugetlb_page(vma)) return copy_hugetlb_page_range(dst_mm, src_mm, vma); if (unlikely(vma->vm_flags & VM_PFNMAP)) { /* * We do not free on error cases below as remove_vma * gets called on error from higher level routine */ ret = track_pfn_copy(vma); if (ret) return ret; } /* * We need to invalidate the secondary MMU mappings only when * there could be a permission downgrade on the ptes of the * parent mm. And a permission downgrade will only happen if * is_cow_mapping() returns true. */ is_cow = is_cow_mapping(vma->vm_flags); mmun_start = addr; mmun_end = end; if (is_cow) mmu_notifier_invalidate_range_start(src_mm, mmun_start, mmun_end); ret = 0; dst_pgd = pgd_offset(dst_mm, addr); src_pgd = pgd_offset(src_mm, addr); do { next = pgd_addr_end(addr, end); if (pgd_none_or_clear_bad(src_pgd)) continue; if (unlikely(copy_pud_range(dst_mm, src_mm, dst_pgd, src_pgd, vma, addr, next))) { ret = -ENOMEM; break; } } while (dst_pgd++, src_pgd++, addr = next, addr != end); if (is_cow) mmu_notifier_invalidate_range_end(src_mm, mmun_start, mmun_end); return ret; } static unsigned long zap_pte_range(struct mmu_gather *tlb, struct vm_area_struct *vma, pmd_t *pmd, unsigned long addr, unsigned long end, struct zap_details *details) { struct mm_struct *mm = tlb->mm; int force_flush = 0; int rss[NR_MM_COUNTERS]; spinlock_t *ptl; pte_t *start_pte; pte_t *pte; swp_entry_t entry; again: init_rss_vec(rss); start_pte = pte_offset_map_lock(mm, pmd, addr, &ptl); pte = start_pte; arch_enter_lazy_mmu_mode(); do { pte_t ptent = *pte; if (pte_none(ptent)) { continue; } if (pte_present(ptent)) { struct page *page; page = vm_normal_page(vma, addr, ptent); if (unlikely(details) && page) { /* * unmap_shared_mapping_pages() wants to * invalidate cache without truncating: * unmap shared but keep private pages. */ if (details->check_mapping && details->check_mapping != page->mapping) continue; } ptent = ptep_get_and_clear_full(mm, addr, pte, tlb->fullmm); tlb_remove_tlb_entry(tlb, pte, addr); if (unlikely(!page)) continue; if (PageAnon(page)) rss[MM_ANONPAGES]--; else { if (pte_dirty(ptent)) { force_flush = 1; set_page_dirty(page); } if (pte_young(ptent) && likely(!(vma->vm_flags & VM_SEQ_READ))) mark_page_accessed(page); rss[MM_FILEPAGES]--; } page_remove_rmap(page); if (unlikely(page_mapcount(page) < 0)) print_bad_pte(vma, addr, ptent, page); if (unlikely(!__tlb_remove_page(tlb, page))) { force_flush = 1; addr += PAGE_SIZE; break; } continue; } /* If details->check_mapping, we leave swap entries. */ if (unlikely(details)) continue; entry = pte_to_swp_entry(ptent); if (!non_swap_entry(entry)) rss[MM_SWAPENTS]--; else if (is_migration_entry(entry)) { struct page *page; page = migration_entry_to_page(entry); if (PageAnon(page)) rss[MM_ANONPAGES]--; else rss[MM_FILEPAGES]--; } if (unlikely(!free_swap_and_cache(entry))) print_bad_pte(vma, addr, ptent, NULL); pte_clear_not_present_full(mm, addr, pte, tlb->fullmm); } while (pte++, addr += PAGE_SIZE, addr != end); add_mm_rss_vec(mm, rss); arch_leave_lazy_mmu_mode(); /* Do the actual TLB flush before dropping ptl */ if (force_flush) tlb_flush_mmu_tlbonly(tlb); pte_unmap_unlock(start_pte, ptl); /* * If we forced a TLB flush (either due to running out of * batch buffers or because we needed to flush dirty TLB * entries before releasing the ptl), free the batched * memory too. Restart if we didn't do everything. */ if (force_flush) { force_flush = 0; tlb_flush_mmu_free(tlb); if (addr != end) goto again; } return addr; } static inline unsigned long zap_pmd_range(struct mmu_gather *tlb, struct vm_area_struct *vma, pud_t *pud, unsigned long addr, unsigned long end, struct zap_details *details) { pmd_t *pmd; unsigned long next; pmd = pmd_offset(pud, addr); do { next = pmd_addr_end(addr, end); if (pmd_trans_huge(*pmd)) { if (next - addr != HPAGE_PMD_SIZE) { #ifdef CONFIG_DEBUG_VM if (!rwsem_is_locked(&tlb->mm->mmap_sem)) { pr_err("%s: mmap_sem is unlocked! addr=0x%lx end=0x%lx vma->vm_start=0x%lx vma->vm_end=0x%lx\n", __func__, addr, end, vma->vm_start, vma->vm_end); BUG(); } #endif split_huge_page_pmd(vma, addr, pmd); } else if (zap_huge_pmd(tlb, vma, pmd, addr)) goto next; /* fall through */ } /* * Here there can be other concurrent MADV_DONTNEED or * trans huge page faults running, and if the pmd is * none or trans huge it can change under us. This is * because MADV_DONTNEED holds the mmap_sem in read * mode. */ if (pmd_none_or_trans_huge_or_clear_bad(pmd)) goto next; next = zap_pte_range(tlb, vma, pmd, addr, next, details); next: cond_resched(); } while (pmd++, addr = next, addr != end); return addr; } static inline unsigned long zap_pud_range(struct mmu_gather *tlb, struct vm_area_struct *vma, pgd_t *pgd, unsigned long addr, unsigned long end, struct zap_details *details) { pud_t *pud; unsigned long next; pud = pud_offset(pgd, addr); do { next = pud_addr_end(addr, end); if (pud_none_or_clear_bad(pud)) continue; next = zap_pmd_range(tlb, vma, pud, addr, next, details); } while (pud++, addr = next, addr != end); return addr; } static void unmap_page_range(struct mmu_gather *tlb, struct vm_area_struct *vma, unsigned long addr, unsigned long end, struct zap_details *details) { pgd_t *pgd; unsigned long next; if (details && !details->check_mapping) details = NULL; BUG_ON(addr >= end); tlb_start_vma(tlb, vma); pgd = pgd_offset(vma->vm_mm, addr); do { next = pgd_addr_end(addr, end); if (pgd_none_or_clear_bad(pgd)) continue; next = zap_pud_range(tlb, vma, pgd, addr, next, details); } while (pgd++, addr = next, addr != end); tlb_end_vma(tlb, vma); } static void unmap_single_vma(struct mmu_gather *tlb, struct vm_area_struct *vma, unsigned long start_addr, unsigned long end_addr, struct zap_details *details) { unsigned long start = max(vma->vm_start, start_addr); unsigned long end; if (start >= vma->vm_end) return; end = min(vma->vm_end, end_addr); if (end <= vma->vm_start) return; if (vma->vm_file) uprobe_munmap(vma, start, end); if (unlikely(vma->vm_flags & VM_PFNMAP)) untrack_pfn(vma, 0, 0); if (start != end) { if (unlikely(is_vm_hugetlb_page(vma))) { /* * It is undesirable to test vma->vm_file as it * should be non-null for valid hugetlb area. * However, vm_file will be NULL in the error * cleanup path of mmap_region. When * hugetlbfs ->mmap method fails, * mmap_region() nullifies vma->vm_file * before calling this function to clean up. * Since no pte has actually been setup, it is * safe to do nothing in this case. */ if (vma->vm_file) { i_mmap_lock_write(vma->vm_file->f_mapping); __unmap_hugepage_range_final(tlb, vma, start, end, NULL); i_mmap_unlock_write(vma->vm_file->f_mapping); } } else unmap_page_range(tlb, vma, start, end, details); } } /** * unmap_vmas - unmap a range of memory covered by a list of vma's * @tlb: address of the caller's struct mmu_gather * @vma: the starting vma * @start_addr: virtual address at which to start unmapping * @end_addr: virtual address at which to end unmapping * * Unmap all pages in the vma list. * * Only addresses between `start' and `end' will be unmapped. * * The VMA list must be sorted in ascending virtual address order. * * unmap_vmas() assumes that the caller will flush the whole unmapped address * range after unmap_vmas() returns. So the only responsibility here is to * ensure that any thus-far unmapped pages are flushed before unmap_vmas() * drops the lock and schedules. */ void unmap_vmas(struct mmu_gather *tlb, struct vm_area_struct *vma, unsigned long start_addr, unsigned long end_addr) { struct mm_struct *mm = vma->vm_mm; mmu_notifier_invalidate_range_start(mm, start_addr, end_addr); for ( ; vma && vma->vm_start < end_addr; vma = vma->vm_next) unmap_single_vma(tlb, vma, start_addr, end_addr, NULL); mmu_notifier_invalidate_range_end(mm, start_addr, end_addr); } /** * zap_page_range - remove user pages in a given range * @vma: vm_area_struct holding the applicable pages * @start: starting address of pages to zap * @size: number of bytes to zap * @details: details of shared cache invalidation * * Caller must protect the VMA list */ void zap_page_range(struct vm_area_struct *vma, unsigned long start, unsigned long size, struct zap_details *details) { struct mm_struct *mm = vma->vm_mm; struct mmu_gather tlb; unsigned long end = start + size; lru_add_drain(); tlb_gather_mmu(&tlb, mm, start, end); update_hiwater_rss(mm); mmu_notifier_invalidate_range_start(mm, start, end); for ( ; vma && vma->vm_start < end; vma = vma->vm_next) unmap_single_vma(&tlb, vma, start, end, details); mmu_notifier_invalidate_range_end(mm, start, end); tlb_finish_mmu(&tlb, start, end); } /** * zap_page_range_single - remove user pages in a given range * @vma: vm_area_struct holding the applicable pages * @address: starting address of pages to zap * @size: number of bytes to zap * @details: details of shared cache invalidation * * The range must fit into one VMA. */ static void zap_page_range_single(struct vm_area_struct *vma, unsigned long address, unsigned long size, struct zap_details *details) { struct mm_struct *mm = vma->vm_mm; struct mmu_gather tlb; unsigned long end = address + size; lru_add_drain(); tlb_gather_mmu(&tlb, mm, address, end); update_hiwater_rss(mm); mmu_notifier_invalidate_range_start(mm, address, end); unmap_single_vma(&tlb, vma, address, end, details); mmu_notifier_invalidate_range_end(mm, address, end); tlb_finish_mmu(&tlb, address, end); } /** * zap_vma_ptes - remove ptes mapping the vma * @vma: vm_area_struct holding ptes to be zapped * @address: starting address of pages to zap * @size: number of bytes to zap * * This function only unmaps ptes assigned to VM_PFNMAP vmas. * * The entire address range must be fully contained within the vma. * * Returns 0 if successful. */ int zap_vma_ptes(struct vm_area_struct *vma, unsigned long address, unsigned long size) { if (address < vma->vm_start || address + size > vma->vm_end || !(vma->vm_flags & VM_PFNMAP)) return -1; zap_page_range_single(vma, address, size, NULL); return 0; } EXPORT_SYMBOL_GPL(zap_vma_ptes); pte_t *__get_locked_pte(struct mm_struct *mm, unsigned long addr, spinlock_t **ptl) { pgd_t * pgd = pgd_offset(mm, addr); pud_t * pud = pud_alloc(mm, pgd, addr); if (pud) { pmd_t * pmd = pmd_alloc(mm, pud, addr); if (pmd) { VM_BUG_ON(pmd_trans_huge(*pmd)); return pte_alloc_map_lock(mm, pmd, addr, ptl); } } return NULL; } /* * This is the old fallback for page remapping. * * For historical reasons, it only allows reserved pages. Only * old drivers should use this, and they needed to mark their * pages reserved for the old functions anyway. */ static int insert_page(struct vm_area_struct *vma, unsigned long addr, struct page *page, pgprot_t prot) { struct mm_struct *mm = vma->vm_mm; int retval; pte_t *pte; spinlock_t *ptl; retval = -EINVAL; if (PageAnon(page)) goto out; retval = -ENOMEM; flush_dcache_page(page); pte = get_locked_pte(mm, addr, &ptl); if (!pte) goto out; retval = -EBUSY; if (!pte_none(*pte)) goto out_unlock; /* Ok, finally just insert the thing.. */ get_page(page); inc_mm_counter_fast(mm, MM_FILEPAGES); page_add_file_rmap(page); set_pte_at(mm, addr, pte, mk_pte(page, prot)); retval = 0; pte_unmap_unlock(pte, ptl); return retval; out_unlock: pte_unmap_unlock(pte, ptl); out: return retval; } /** * vm_insert_page - insert single page into user vma * @vma: user vma to map to * @addr: target user address of this page * @page: source kernel page * * This allows drivers to insert individual pages they've allocated * into a user vma. * * The page has to be a nice clean _individual_ kernel allocation. * If you allocate a compound page, you need to have marked it as * such (__GFP_COMP), or manually just split the page up yourself * (see split_page()). * * NOTE! Traditionally this was done with "remap_pfn_range()" which * took an arbitrary page protection parameter. This doesn't allow * that. Your vma protection will have to be set up correctly, which * means that if you want a shared writable mapping, you'd better * ask for a shared writable mapping! * * The page does not need to be reserved. * * Usually this function is called from f_op->mmap() handler * under mm->mmap_sem write-lock, so it can change vma->vm_flags. * Caller must set VM_MIXEDMAP on vma if it wants to call this * function from other places, for example from page-fault handler. */ int vm_insert_page(struct vm_area_struct *vma, unsigned long addr, struct page *page) { if (addr < vma->vm_start || addr >= vma->vm_end) return -EFAULT; if (!page_count(page)) return -EINVAL; if (!(vma->vm_flags & VM_MIXEDMAP)) { BUG_ON(down_read_trylock(&vma->vm_mm->mmap_sem)); BUG_ON(vma->vm_flags & VM_PFNMAP); vma->vm_flags |= VM_MIXEDMAP; } return insert_page(vma, addr, page, vma->vm_page_prot); } EXPORT_SYMBOL(vm_insert_page); static int insert_pfn(struct vm_area_struct *vma, unsigned long addr, unsigned long pfn, pgprot_t prot) { struct mm_struct *mm = vma->vm_mm; int retval; pte_t *pte, entry; spinlock_t *ptl; retval = -ENOMEM; pte = get_locked_pte(mm, addr, &ptl); if (!pte) goto out; retval = -EBUSY; if (!pte_none(*pte)) goto out_unlock; /* Ok, finally just insert the thing.. */ entry = pte_mkspecial(pfn_pte(pfn, prot)); set_pte_at(mm, addr, pte, entry); update_mmu_cache(vma, addr, pte); /* XXX: why not for insert_page? */ retval = 0; out_unlock: pte_unmap_unlock(pte, ptl); out: return retval; } /** * vm_insert_pfn - insert single pfn into user vma * @vma: user vma to map to * @addr: target user address of this page * @pfn: source kernel pfn * * Similar to vm_insert_page, this allows drivers to insert individual pages * they've allocated into a user vma. Same comments apply. * * This function should only be called from a vm_ops->fault handler, and * in that case the handler should return NULL. * * vma cannot be a COW mapping. * * As this is called only for pages that do not currently exist, we * do not need to flush old virtual caches or the TLB. */ int vm_insert_pfn(struct vm_area_struct *vma, unsigned long addr, unsigned long pfn) { int ret; pgprot_t pgprot = vma->vm_page_prot; /* * Technically, architectures with pte_special can avoid all these * restrictions (same for remap_pfn_range). However we would like * consistency in testing and feature parity among all, so we should * try to keep these invariants in place for everybody. */ BUG_ON(!(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP))); BUG_ON((vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)) == (VM_PFNMAP|VM_MIXEDMAP)); BUG_ON((vma->vm_flags & VM_PFNMAP) && is_cow_mapping(vma->vm_flags)); BUG_ON((vma->vm_flags & VM_MIXEDMAP) && pfn_valid(pfn)); if (addr < vma->vm_start || addr >= vma->vm_end) return -EFAULT; if (track_pfn_insert(vma, &pgprot, pfn)) return -EINVAL; ret = insert_pfn(vma, addr, pfn, pgprot); return ret; } EXPORT_SYMBOL(vm_insert_pfn); int vm_insert_mixed(struct vm_area_struct *vma, unsigned long addr, unsigned long pfn) { BUG_ON(!(vma->vm_flags & VM_MIXEDMAP)); if (addr < vma->vm_start || addr >= vma->vm_end) return -EFAULT; /* * If we don't have pte special, then we have to use the pfn_valid() * based VM_MIXEDMAP scheme (see vm_normal_page), and thus we *must* * refcount the page if pfn_valid is true (hence insert_page rather * than insert_pfn). If a zero_pfn were inserted into a VM_MIXEDMAP * without pte special, it would there be refcounted as a normal page. */ if (!HAVE_PTE_SPECIAL && pfn_valid(pfn)) { struct page *page; page = pfn_to_page(pfn); return insert_page(vma, addr, page, vma->vm_page_prot); } return insert_pfn(vma, addr, pfn, vma->vm_page_prot); } EXPORT_SYMBOL(vm_insert_mixed); /* * maps a range of physical memory into the requested pages. the old * mappings are removed. any references to nonexistent pages results * in null mappings (currently treated as "copy-on-access") */ static int remap_pte_range(struct mm_struct *mm, pmd_t *pmd, unsigned long addr, unsigned long end, unsigned long pfn, pgprot_t prot) { pte_t *pte; spinlock_t *ptl; pte = pte_alloc_map_lock(mm, pmd, addr, &ptl); if (!pte) return -ENOMEM; arch_enter_lazy_mmu_mode(); do { BUG_ON(!pte_none(*pte)); set_pte_at(mm, addr, pte, pte_mkspecial(pfn_pte(pfn, prot))); pfn++; } while (pte++, addr += PAGE_SIZE, addr != end); arch_leave_lazy_mmu_mode(); pte_unmap_unlock(pte - 1, ptl); return 0; } static inline int remap_pmd_range(struct mm_struct *mm, pud_t *pud, unsigned long addr, unsigned long end, unsigned long pfn, pgprot_t prot) { pmd_t *pmd; unsigned long next; pfn -= addr >> PAGE_SHIFT; pmd = pmd_alloc(mm, pud, addr); if (!pmd) return -ENOMEM; VM_BUG_ON(pmd_trans_huge(*pmd)); do { next = pmd_addr_end(addr, end); if (remap_pte_range(mm, pmd, addr, next, pfn + (addr >> PAGE_SHIFT), prot)) return -ENOMEM; } while (pmd++, addr = next, addr != end); return 0; } static inline int remap_pud_range(struct mm_struct *mm, pgd_t *pgd, unsigned long addr, unsigned long end, unsigned long pfn, pgprot_t prot) { pud_t *pud; unsigned long next; pfn -= addr >> PAGE_SHIFT; pud = pud_alloc(mm, pgd, addr); if (!pud) return -ENOMEM; do { next = pud_addr_end(addr, end); if (remap_pmd_range(mm, pud, addr, next, pfn + (addr >> PAGE_SHIFT), prot)) return -ENOMEM; } while (pud++, addr = next, addr != end); return 0; } /** * remap_pfn_range - remap kernel memory to userspace * @vma: user vma to map to * @addr: target user address to start at * @pfn: physical address of kernel memory * @size: size of map area * @prot: page protection flags for this mapping * * Note: this is only safe if the mm semaphore is held when called. */ int remap_pfn_range(struct vm_area_struct *vma, unsigned long addr, unsigned long pfn, unsigned long size, pgprot_t prot) { pgd_t *pgd; unsigned long next; unsigned long end = addr + PAGE_ALIGN(size); struct mm_struct *mm = vma->vm_mm; int err; /* * Physically remapped pages are special. Tell the * rest of the world about it: * VM_IO tells people not to look at these pages * (accesses can have side effects). * VM_PFNMAP tells the core MM that the base pages are just * raw PFN mappings, and do not have a "struct page" associated * with them. * VM_DONTEXPAND * Disable vma merging and expanding with mremap(). * VM_DONTDUMP * Omit vma from core dump, even when VM_IO turned off. * * There's a horrible special case to handle copy-on-write * behaviour that some programs depend on. We mark the "original" * un-COW'ed pages by matching them up with "vma->vm_pgoff". * See vm_normal_page() for details. */ if (is_cow_mapping(vma->vm_flags)) { if (addr != vma->vm_start || end != vma->vm_end) return -EINVAL; vma->vm_pgoff = pfn; } err = track_pfn_remap(vma, &prot, pfn, addr, PAGE_ALIGN(size)); if (err) return -EINVAL; vma->vm_flags |= VM_IO | VM_PFNMAP | VM_DONTEXPAND | VM_DONTDUMP; BUG_ON(addr >= end); pfn -= addr >> PAGE_SHIFT; pgd = pgd_offset(mm, addr); flush_cache_range(vma, addr, end); do { next = pgd_addr_end(addr, end); err = remap_pud_range(mm, pgd, addr, next, pfn + (addr >> PAGE_SHIFT), prot); if (err) break; } while (pgd++, addr = next, addr != end); if (err) untrack_pfn(vma, pfn, PAGE_ALIGN(size)); return err; } EXPORT_SYMBOL(remap_pfn_range); /** * vm_iomap_memory - remap memory to userspace * @vma: user vma to map to * @start: start of area * @len: size of area * * This is a simplified io_remap_pfn_range() for common driver use. The * driver just needs to give us the physical memory range to be mapped, * we'll figure out the rest from the vma information. * * NOTE! Some drivers might want to tweak vma->vm_page_prot first to get * whatever write-combining details or similar. */ int vm_iomap_memory(struct vm_area_struct *vma, phys_addr_t start, unsigned long len) { unsigned long vm_len, pfn, pages; /* Check that the physical memory area passed in looks valid */ if (start + len < start) return -EINVAL; /* * You *really* shouldn't map things that aren't page-aligned, * but we've historically allowed it because IO memory might * just have smaller alignment. */ len += start & ~PAGE_MASK; pfn = start >> PAGE_SHIFT; pages = (len + ~PAGE_MASK) >> PAGE_SHIFT; if (pfn + pages < pfn) return -EINVAL; /* We start the mapping 'vm_pgoff' pages into the area */ if (vma->vm_pgoff > pages) return -EINVAL; pfn += vma->vm_pgoff; pages -= vma->vm_pgoff; /* Can we fit all of the mapping? */ vm_len = vma->vm_end - vma->vm_start; if (vm_len >> PAGE_SHIFT > pages) return -EINVAL; /* Ok, let it rip */ return io_remap_pfn_range(vma, vma->vm_start, pfn, vm_len, vma->vm_page_prot); } EXPORT_SYMBOL(vm_iomap_memory); static int apply_to_pte_range(struct mm_struct *mm, pmd_t *pmd, unsigned long addr, unsigned long end, pte_fn_t fn, void *data) { pte_t *pte; int err; pgtable_t token; spinlock_t *uninitialized_var(ptl); pte = (mm == &init_mm) ? pte_alloc_kernel(pmd, addr) : pte_alloc_map_lock(mm, pmd, addr, &ptl); if (!pte) return -ENOMEM; BUG_ON(pmd_huge(*pmd)); arch_enter_lazy_mmu_mode(); token = pmd_pgtable(*pmd); do { err = fn(pte++, token, addr, data); if (err) break; } while (addr += PAGE_SIZE, addr != end); arch_leave_lazy_mmu_mode(); if (mm != &init_mm) pte_unmap_unlock(pte-1, ptl); return err; } static int apply_to_pmd_range(struct mm_struct *mm, pud_t *pud, unsigned long addr, unsigned long end, pte_fn_t fn, void *data) { pmd_t *pmd; unsigned long next; int err; BUG_ON(pud_huge(*pud)); pmd = pmd_alloc(mm, pud, addr); if (!pmd) return -ENOMEM; do { next = pmd_addr_end(addr, end); err = apply_to_pte_range(mm, pmd, addr, next, fn, data); if (err) break; } while (pmd++, addr = next, addr != end); return err; } static int apply_to_pud_range(struct mm_struct *mm, pgd_t *pgd, unsigned long addr, unsigned long end, pte_fn_t fn, void *data) { pud_t *pud; unsigned long next; int err; pud = pud_alloc(mm, pgd, addr); if (!pud) return -ENOMEM; do { next = pud_addr_end(addr, end); err = apply_to_pmd_range(mm, pud, addr, next, fn, data); if (err) break; } while (pud++, addr = next, addr != end); return err; } /* * Scan a region of virtual memory, filling in page tables as necessary * and calling a provided function on each leaf page table. */ int apply_to_page_range(struct mm_struct *mm, unsigned long addr, unsigned long size, pte_fn_t fn, void *data) { pgd_t *pgd; unsigned long next; unsigned long end = addr + size; int err; BUG_ON(addr >= end); pgd = pgd_offset(mm, addr); do { next = pgd_addr_end(addr, end); err = apply_to_pud_range(mm, pgd, addr, next, fn, data); if (err) break; } while (pgd++, addr = next, addr != end); return err; } EXPORT_SYMBOL_GPL(apply_to_page_range); /* * handle_pte_fault chooses page fault handler according to an entry which was * read non-atomically. Before making any commitment, on those architectures * or configurations (e.g. i386 with PAE) which might give a mix of unmatched * parts, do_swap_page must check under lock before unmapping the pte and * proceeding (but do_wp_page is only called after already making such a check; * and do_anonymous_page can safely check later on). */ static inline int pte_unmap_same(struct mm_struct *mm, pmd_t *pmd, pte_t *page_table, pte_t orig_pte) { int same = 1; #if defined(CONFIG_SMP) || defined(CONFIG_PREEMPT) if (sizeof(pte_t) > sizeof(unsigned long)) { spinlock_t *ptl = pte_lockptr(mm, pmd); spin_lock(ptl); same = pte_same(*page_table, orig_pte); spin_unlock(ptl); } #endif pte_unmap(page_table); return same; } static inline void cow_user_page(struct page *dst, struct page *src, unsigned long va, struct vm_area_struct *vma) { debug_dma_assert_idle(src); /* * If the source page was a PFN mapping, we don't have * a "struct page" for it. We do a best-effort copy by * just copying from the original user address. If that * fails, we just zero-fill it. Live with it. */ if (unlikely(!src)) { void *kaddr = kmap_atomic(dst); void __user *uaddr = (void __user *)(va & PAGE_MASK); /* * This really shouldn't fail, because the page is there * in the page tables. But it might just be unreadable, * in which case we just give up and fill the result with * zeroes. */ if (__copy_from_user_inatomic(kaddr, uaddr, PAGE_SIZE)) clear_page(kaddr); kunmap_atomic(kaddr); flush_dcache_page(dst); } else copy_user_highpage(dst, src, va, vma); } /* * Notify the address space that the page is about to become writable so that * it can prohibit this or wait for the page to get into an appropriate state. * * We do this without the lock held, so that it can sleep if it needs to. */ static int do_page_mkwrite(struct vm_area_struct *vma, struct page *page, unsigned long address) { struct vm_fault vmf; int ret; vmf.virtual_address = (void __user *)(address & PAGE_MASK); vmf.pgoff = page->index; vmf.flags = FAULT_FLAG_WRITE|FAULT_FLAG_MKWRITE; vmf.page = page; vmf.cow_page = NULL; ret = vma->vm_ops->page_mkwrite(vma, &vmf); if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE))) return ret; if (unlikely(!(ret & VM_FAULT_LOCKED))) { lock_page(page); if (!page->mapping) { unlock_page(page); return 0; /* retry */ } ret |= VM_FAULT_LOCKED; } else VM_BUG_ON_PAGE(!PageLocked(page), page); return ret; } /* * Handle write page faults for pages that can be reused in the current vma * * This can happen either due to the mapping being with the VM_SHARED flag, * or due to us being the last reference standing to the page. In either * case, all we need to do here is to mark the page as writable and update * any related book-keeping. */ static inline int wp_page_reuse(struct mm_struct *mm, struct vm_area_struct *vma, unsigned long address, pte_t *page_table, spinlock_t *ptl, pte_t orig_pte, struct page *page, int page_mkwrite, int dirty_shared) __releases(ptl) { pte_t entry; /* * Clear the pages cpupid information as the existing * information potentially belongs to a now completely * unrelated process. */ if (page) page_cpupid_xchg_last(page, (1 << LAST_CPUPID_SHIFT) - 1); flush_cache_page(vma, address, pte_pfn(orig_pte)); entry = pte_mkyoung(orig_pte); entry = maybe_mkwrite(pte_mkdirty(entry), vma); if (ptep_set_access_flags(vma, address, page_table, entry, 1)) update_mmu_cache(vma, address, page_table); pte_unmap_unlock(page_table, ptl); if (dirty_shared) { struct address_space *mapping; int dirtied; if (!page_mkwrite) lock_page(page); dirtied = set_page_dirty(page); VM_BUG_ON_PAGE(PageAnon(page), page); mapping = page->mapping; unlock_page(page); page_cache_release(page); if ((dirtied || page_mkwrite) && mapping) { /* * Some device drivers do not set page.mapping * but still dirty their pages */ balance_dirty_pages_ratelimited(mapping); } if (!page_mkwrite) file_update_time(vma->vm_file); } return VM_FAULT_WRITE; } /* * Handle the case of a page which we actually need to copy to a new page. * * Called with mmap_sem locked and the old page referenced, but * without the ptl held. * * High level logic flow: * * - Allocate a page, copy the content of the old page to the new one. * - Handle book keeping and accounting - cgroups, mmu-notifiers, etc. * - Take the PTL. If the pte changed, bail out and release the allocated page * - If the pte is still the way we remember it, update the page table and all * relevant references. This includes dropping the reference the page-table * held to the old page, as well as updating the rmap. * - In any case, unlock the PTL and drop the reference we took to the old page. */ static int wp_page_copy(struct mm_struct *mm, struct vm_area_struct *vma, unsigned long address, pte_t *page_table, pmd_t *pmd, pte_t orig_pte, struct page *old_page) { struct page *new_page = NULL; spinlock_t *ptl = NULL; pte_t entry; int page_copied = 0; const unsigned long mmun_start = address & PAGE_MASK; /* For mmu_notifiers */ const unsigned long mmun_end = mmun_start + PAGE_SIZE; /* For mmu_notifiers */ struct mem_cgroup *memcg; if (unlikely(anon_vma_prepare(vma))) goto oom; if (is_zero_pfn(pte_pfn(orig_pte))) { new_page = alloc_zeroed_user_highpage_movable(vma, address); if (!new_page) goto oom; } else { new_page = alloc_page_vma(GFP_HIGHUSER_MOVABLE, vma, address); if (!new_page) goto oom; cow_user_page(new_page, old_page, address, vma); } if (mem_cgroup_try_charge(new_page, mm, GFP_KERNEL, &memcg)) goto oom_free_new; __SetPageUptodate(new_page); mmu_notifier_invalidate_range_start(mm, mmun_start, mmun_end); /* * Re-check the pte - we dropped the lock */ page_table = pte_offset_map_lock(mm, pmd, address, &ptl); if (likely(pte_same(*page_table, orig_pte))) { if (old_page) { if (!PageAnon(old_page)) { dec_mm_counter_fast(mm, MM_FILEPAGES); inc_mm_counter_fast(mm, MM_ANONPAGES); } } else { inc_mm_counter_fast(mm, MM_ANONPAGES); } flush_cache_page(vma, address, pte_pfn(orig_pte)); entry = mk_pte(new_page, vma->vm_page_prot); entry = maybe_mkwrite(pte_mkdirty(entry), vma); /* * Clear the pte entry and flush it first, before updating the * pte with the new entry. This will avoid a race condition * seen in the presence of one thread doing SMC and another * thread doing COW. */ ptep_clear_flush_notify(vma, address, page_table); page_add_new_anon_rmap(new_page, vma, address); mem_cgroup_commit_charge(new_page, memcg, false); lru_cache_add_active_or_unevictable(new_page, vma); /* * We call the notify macro here because, when using secondary * mmu page tables (such as kvm shadow page tables), we want the * new page to be mapped directly into the secondary page table. */ set_pte_at_notify(mm, address, page_table, entry); update_mmu_cache(vma, address, page_table); if (old_page) { /* * Only after switching the pte to the new page may * we remove the mapcount here. Otherwise another * process may come and find the rmap count decremented * before the pte is switched to the new page, and * "reuse" the old page writing into it while our pte * here still points into it and can be read by other * threads. * * The critical issue is to order this * page_remove_rmap with the ptp_clear_flush above. * Those stores are ordered by (if nothing else,) * the barrier present in the atomic_add_negative * in page_remove_rmap. * * Then the TLB flush in ptep_clear_flush ensures that * no process can access the old page before the * decremented mapcount is visible. And the old page * cannot be reused until after the decremented * mapcount is visible. So transitively, TLBs to * old page will be flushed before it can be reused. */ page_remove_rmap(old_page); } /* Free the old page.. */ new_page = old_page; page_copied = 1; } else { mem_cgroup_cancel_charge(new_page, memcg); } if (new_page) page_cache_release(new_page); pte_unmap_unlock(page_table, ptl); mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end); if (old_page) { /* * Don't let another task, with possibly unlocked vma, * keep the mlocked page. */ if (page_copied && (vma->vm_flags & VM_LOCKED)) { lock_page(old_page); /* LRU manipulation */ munlock_vma_page(old_page); unlock_page(old_page); } page_cache_release(old_page); } return page_copied ? VM_FAULT_WRITE : 0; oom_free_new: page_cache_release(new_page); oom: if (old_page) page_cache_release(old_page); return VM_FAULT_OOM; } /* * Handle write page faults for VM_MIXEDMAP or VM_PFNMAP for a VM_SHARED * mapping */ static int wp_pfn_shared(struct mm_struct *mm, struct vm_area_struct *vma, unsigned long address, pte_t *page_table, spinlock_t *ptl, pte_t orig_pte, pmd_t *pmd) { if (vma->vm_ops && vma->vm_ops->pfn_mkwrite) { struct vm_fault vmf = { .page = NULL, .pgoff = linear_page_index(vma, address), .virtual_address = (void __user *)(address & PAGE_MASK), .flags = FAULT_FLAG_WRITE | FAULT_FLAG_MKWRITE, }; int ret; pte_unmap_unlock(page_table, ptl); ret = vma->vm_ops->pfn_mkwrite(vma, &vmf); if (ret & VM_FAULT_ERROR) return ret; page_table = pte_offset_map_lock(mm, pmd, address, &ptl); /* * We might have raced with another page fault while we * released the pte_offset_map_lock. */ if (!pte_same(*page_table, orig_pte)) { pte_unmap_unlock(page_table, ptl); return 0; } } return wp_page_reuse(mm, vma, address, page_table, ptl, orig_pte, NULL, 0, 0); } static int wp_page_shared(struct mm_struct *mm, struct vm_area_struct *vma, unsigned long address, pte_t *page_table, pmd_t *pmd, spinlock_t *ptl, pte_t orig_pte, struct page *old_page) __releases(ptl) { int page_mkwrite = 0; page_cache_get(old_page); /* * Only catch write-faults on shared writable pages, * read-only shared pages can get COWed by * get_user_pages(.write=1, .force=1). */ if (vma->vm_ops && vma->vm_ops->page_mkwrite) { int tmp; pte_unmap_unlock(page_table, ptl); tmp = do_page_mkwrite(vma, old_page, address); if (unlikely(!tmp || (tmp & (VM_FAULT_ERROR | VM_FAULT_NOPAGE)))) { page_cache_release(old_page); return tmp; } /* * Since we dropped the lock we need to revalidate * the PTE as someone else may have changed it. If * they did, we just return, as we can count on the * MMU to tell us if they didn't also make it writable. */ page_table = pte_offset_map_lock(mm, pmd, address, &ptl); if (!pte_same(*page_table, orig_pte)) { unlock_page(old_page); pte_unmap_unlock(page_table, ptl); page_cache_release(old_page); return 0; } page_mkwrite = 1; } return wp_page_reuse(mm, vma, address, page_table, ptl, orig_pte, old_page, page_mkwrite, 1); } /* * This routine handles present pages, when users try to write * to a shared page. It is done by copying the page to a new address * and decrementing the shared-page counter for the old page. * * Note that this routine assumes that the protection checks have been * done by the caller (the low-level page fault routine in most cases). * Thus we can safely just mark it writable once we've done any necessary * COW. * * We also mark the page dirty at this point even though the page will * change only once the write actually happens. This avoids a few races, * and potentially makes it more efficient. * * We enter with non-exclusive mmap_sem (to exclude vma changes, * but allow concurrent faults), with pte both mapped and locked. * We return with mmap_sem still held, but pte unmapped and unlocked. */ static int do_wp_page(struct mm_struct *mm, struct vm_area_struct *vma, unsigned long address, pte_t *page_table, pmd_t *pmd, spinlock_t *ptl, pte_t orig_pte) __releases(ptl) { struct page *old_page; old_page = vm_normal_page(vma, address, orig_pte); if (!old_page) { /* * VM_MIXEDMAP !pfn_valid() case, or VM_SOFTDIRTY clear on a * VM_PFNMAP VMA. * * We should not cow pages in a shared writeable mapping. * Just mark the pages writable and/or call ops->pfn_mkwrite. */ if ((vma->vm_flags & (VM_WRITE|VM_SHARED)) == (VM_WRITE|VM_SHARED)) return wp_pfn_shared(mm, vma, address, page_table, ptl, orig_pte, pmd); pte_unmap_unlock(page_table, ptl); return wp_page_copy(mm, vma, address, page_table, pmd, orig_pte, old_page); } /* * Take out anonymous pages first, anonymous shared vmas are * not dirty accountable. */ if (PageAnon(old_page) && !PageKsm(old_page)) { if (!trylock_page(old_page)) { page_cache_get(old_page); pte_unmap_unlock(page_table, ptl); lock_page(old_page); page_table = pte_offset_map_lock(mm, pmd, address, &ptl); if (!pte_same(*page_table, orig_pte)) { unlock_page(old_page); pte_unmap_unlock(page_table, ptl); page_cache_release(old_page); return 0; } page_cache_release(old_page); } if (reuse_swap_page(old_page)) { /* * The page is all ours. Move it to our anon_vma so * the rmap code will not search our parent or siblings. * Protected against the rmap code by the page lock. */ page_move_anon_rmap(old_page, vma, address); unlock_page(old_page); return wp_page_reuse(mm, vma, address, page_table, ptl, orig_pte, old_page, 0, 0); } unlock_page(old_page); } else if (unlikely((vma->vm_flags & (VM_WRITE|VM_SHARED)) == (VM_WRITE|VM_SHARED))) { return wp_page_shared(mm, vma, address, page_table, pmd, ptl, orig_pte, old_page); } /* * Ok, we need to copy. Oh, well.. */ page_cache_get(old_page); pte_unmap_unlock(page_table, ptl); return wp_page_copy(mm, vma, address, page_table, pmd, orig_pte, old_page); } static void unmap_mapping_range_vma(struct vm_area_struct *vma, unsigned long start_addr, unsigned long end_addr, struct zap_details *details) { zap_page_range_single(vma, start_addr, end_addr - start_addr, details); } static inline void unmap_mapping_range_tree(struct rb_root *root, struct zap_details *details) { struct vm_area_struct *vma; pgoff_t vba, vea, zba, zea; vma_interval_tree_foreach(vma, root, details->first_index, details->last_index) { vba = vma->vm_pgoff; vea = vba + vma_pages(vma) - 1; /* Assume for now that PAGE_CACHE_SHIFT == PAGE_SHIFT */ zba = details->first_index; if (zba < vba) zba = vba; zea = details->last_index; if (zea > vea) zea = vea; unmap_mapping_range_vma(vma, ((zba - vba) << PAGE_SHIFT) + vma->vm_start, ((zea - vba + 1) << PAGE_SHIFT) + vma->vm_start, details); } } /** * unmap_mapping_range - unmap the portion of all mmaps in the specified * address_space corresponding to the specified page range in the underlying * file. * * @mapping: the address space containing mmaps to be unmapped. * @holebegin: byte in first page to unmap, relative to the start of * the underlying file. This will be rounded down to a PAGE_SIZE * boundary. Note that this is different from truncate_pagecache(), which * must keep the partial page. In contrast, we must get rid of * partial pages. * @holelen: size of prospective hole in bytes. This will be rounded * up to a PAGE_SIZE boundary. A holelen of zero truncates to the * end of the file. * @even_cows: 1 when truncating a file, unmap even private COWed pages; * but 0 when invalidating pagecache, don't throw away private data. */ void unmap_mapping_range(struct address_space *mapping, loff_t const holebegin, loff_t const holelen, int even_cows) { struct zap_details details; pgoff_t hba = holebegin >> PAGE_SHIFT; pgoff_t hlen = (holelen + PAGE_SIZE - 1) >> PAGE_SHIFT; /* Check for overflow. */ if (sizeof(holelen) > sizeof(hlen)) { long long holeend = (holebegin + holelen + PAGE_SIZE - 1) >> PAGE_SHIFT; if (holeend & ~(long long)ULONG_MAX) hlen = ULONG_MAX - hba + 1; } details.check_mapping = even_cows? NULL: mapping; details.first_index = hba; details.last_index = hba + hlen - 1; if (details.last_index < details.first_index) details.last_index = ULONG_MAX; /* DAX uses i_mmap_lock to serialise file truncate vs page fault */ i_mmap_lock_write(mapping); if (unlikely(!RB_EMPTY_ROOT(&mapping->i_mmap))) unmap_mapping_range_tree(&mapping->i_mmap, &details); i_mmap_unlock_write(mapping); } EXPORT_SYMBOL(unmap_mapping_range); /* * We enter with non-exclusive mmap_sem (to exclude vma changes, * but allow concurrent faults), and pte mapped but not yet locked. * We return with pte unmapped and unlocked. * * We return with the mmap_sem locked or unlocked in the same cases * as does filemap_fault(). */ static int do_swap_page(struct mm_struct *mm, struct vm_area_struct *vma, unsigned long address, pte_t *page_table, pmd_t *pmd, unsigned int flags, pte_t orig_pte) { spinlock_t *ptl; struct page *page, *swapcache; struct mem_cgroup *memcg; swp_entry_t entry; pte_t pte; int locked; int exclusive = 0; int ret = 0; if (!pte_unmap_same(mm, pmd, page_table, orig_pte)) goto out; entry = pte_to_swp_entry(orig_pte); if (unlikely(non_swap_entry(entry))) { if (is_migration_entry(entry)) { migration_entry_wait(mm, pmd, address); } else if (is_hwpoison_entry(entry)) { ret = VM_FAULT_HWPOISON; } else { print_bad_pte(vma, address, orig_pte, NULL); ret = VM_FAULT_SIGBUS; } goto out; } delayacct_set_flag(DELAYACCT_PF_SWAPIN); page = lookup_swap_cache(entry); if (!page) { page = swapin_readahead(entry, GFP_HIGHUSER_MOVABLE, vma, address); if (!page) { /* * Back out if somebody else faulted in this pte * while we released the pte lock. */ page_table = pte_offset_map_lock(mm, pmd, address, &ptl); if (likely(pte_same(*page_table, orig_pte))) ret = VM_FAULT_OOM; delayacct_clear_flag(DELAYACCT_PF_SWAPIN); goto unlock; } /* Had to read the page from swap area: Major fault */ ret = VM_FAULT_MAJOR; count_vm_event(PGMAJFAULT); mem_cgroup_count_vm_event(mm, PGMAJFAULT); } else if (PageHWPoison(page)) { /* * hwpoisoned dirty swapcache pages are kept for killing * owner processes (which may be unknown at hwpoison time) */ ret = VM_FAULT_HWPOISON; delayacct_clear_flag(DELAYACCT_PF_SWAPIN); swapcache = page; goto out_release; } swapcache = page; locked = lock_page_or_retry(page, mm, flags); delayacct_clear_flag(DELAYACCT_PF_SWAPIN); if (!locked) { ret |= VM_FAULT_RETRY; goto out_release; } /* * Make sure try_to_free_swap or reuse_swap_page or swapoff did not * release the swapcache from under us. The page pin, and pte_same * test below, are not enough to exclude that. Even if it is still * swapcache, we need to check that the page's swap has not changed. */ if (unlikely(!PageSwapCache(page) || page_private(page) != entry.val)) goto out_page; page = ksm_might_need_to_copy(page, vma, address); if (unlikely(!page)) { ret = VM_FAULT_OOM; page = swapcache; goto out_page; } if (mem_cgroup_try_charge(page, mm, GFP_KERNEL, &memcg)) { ret = VM_FAULT_OOM; goto out_page; } /* * Back out if somebody else already faulted in this pte. */ page_table = pte_offset_map_lock(mm, pmd, address, &ptl); if (unlikely(!pte_same(*page_table, orig_pte))) goto out_nomap; if (unlikely(!PageUptodate(page))) { ret = VM_FAULT_SIGBUS; goto out_nomap; } /* * The page isn't present yet, go ahead with the fault. * * Be careful about the sequence of operations here. * To get its accounting right, reuse_swap_page() must be called * while the page is counted on swap but not yet in mapcount i.e. * before page_add_anon_rmap() and swap_free(); try_to_free_swap() * must be called after the swap_free(), or it will never succeed. */ inc_mm_counter_fast(mm, MM_ANONPAGES); dec_mm_counter_fast(mm, MM_SWAPENTS); pte = mk_pte(page, vma->vm_page_prot); if ((flags & FAULT_FLAG_WRITE) && reuse_swap_page(page)) { pte = maybe_mkwrite(pte_mkdirty(pte), vma); flags &= ~FAULT_FLAG_WRITE; ret |= VM_FAULT_WRITE; exclusive = 1; } flush_icache_page(vma, page); if (pte_swp_soft_dirty(orig_pte)) pte = pte_mksoft_dirty(pte); set_pte_at(mm, address, page_table, pte); if (page == swapcache) { do_page_add_anon_rmap(page, vma, address, exclusive); mem_cgroup_commit_charge(page, memcg, true); } else { /* ksm created a completely new copy */ page_add_new_anon_rmap(page, vma, address); mem_cgroup_commit_charge(page, memcg, false); lru_cache_add_active_or_unevictable(page, vma); } swap_free(entry); if (vm_swap_full() || (vma->vm_flags & VM_LOCKED) || PageMlocked(page)) try_to_free_swap(page); unlock_page(page); if (page != swapcache) { /* * Hold the lock to avoid the swap entry to be reused * until we take the PT lock for the pte_same() check * (to avoid false positives from pte_same). For * further safety release the lock after the swap_free * so that the swap count won't change under a * parallel locked swapcache. */ unlock_page(swapcache); page_cache_release(swapcache); } if (flags & FAULT_FLAG_WRITE) { ret |= do_wp_page(mm, vma, address, page_table, pmd, ptl, pte); if (ret & VM_FAULT_ERROR) ret &= VM_FAULT_ERROR; goto out; } /* No need to invalidate - it was non-present before */ update_mmu_cache(vma, address, page_table); unlock: pte_unmap_unlock(page_table, ptl); out: return ret; out_nomap: mem_cgroup_cancel_charge(page, memcg); pte_unmap_unlock(page_table, ptl); out_page: unlock_page(page); out_release: page_cache_release(page); if (page != swapcache) { unlock_page(swapcache); page_cache_release(swapcache); } return ret; } /* * This is like a special single-page "expand_{down|up}wards()", * except we must first make sure that 'address{-|+}PAGE_SIZE' * doesn't hit another vma. */ static inline int check_stack_guard_page(struct vm_area_struct *vma, unsigned long address) { address &= PAGE_MASK; if ((vma->vm_flags & VM_GROWSDOWN) && address == vma->vm_start) { struct vm_area_struct *prev = vma->vm_prev; /* * Is there a mapping abutting this one below? * * That's only ok if it's the same stack mapping * that has gotten split.. */ if (prev && prev->vm_end == address) return prev->vm_flags & VM_GROWSDOWN ? 0 : -ENOMEM; return expand_downwards(vma, address - PAGE_SIZE); } if ((vma->vm_flags & VM_GROWSUP) && address + PAGE_SIZE == vma->vm_end) { struct vm_area_struct *next = vma->vm_next; /* As VM_GROWSDOWN but s/below/above/ */ if (next && next->vm_start == address + PAGE_SIZE) return next->vm_flags & VM_GROWSUP ? 0 : -ENOMEM; return expand_upwards(vma, address + PAGE_SIZE); } return 0; } /* * We enter with non-exclusive mmap_sem (to exclude vma changes, * but allow concurrent faults), and pte mapped but not yet locked. * We return with mmap_sem still held, but pte unmapped and unlocked. */ static int do_anonymous_page(struct mm_struct *mm, struct vm_area_struct *vma, unsigned long address, pte_t *page_table, pmd_t *pmd, unsigned int flags) { struct mem_cgroup *memcg; struct page *page; spinlock_t *ptl; pte_t entry; pte_unmap(page_table); /* Check if we need to add a guard page to the stack */ if (check_stack_guard_page(vma, address) < 0) return VM_FAULT_SIGSEGV; /* Use the zero-page for reads */ if (!(flags & FAULT_FLAG_WRITE) && !mm_forbids_zeropage(mm)) { entry = pte_mkspecial(pfn_pte(my_zero_pfn(address), vma->vm_page_prot)); page_table = pte_offset_map_lock(mm, pmd, address, &ptl); if (!pte_none(*page_table)) goto unlock; goto setpte; } /* Allocate our own private page. */ if (unlikely(anon_vma_prepare(vma))) goto oom; page = alloc_zeroed_user_highpage_movable(vma, address); if (!page) goto oom; if (mem_cgroup_try_charge(page, mm, GFP_KERNEL, &memcg)) goto oom_free_page; /* * The memory barrier inside __SetPageUptodate makes sure that * preceeding stores to the page contents become visible before * the set_pte_at() write. */ __SetPageUptodate(page); entry = mk_pte(page, vma->vm_page_prot); if (vma->vm_flags & VM_WRITE) entry = pte_mkwrite(pte_mkdirty(entry)); page_table = pte_offset_map_lock(mm, pmd, address, &ptl); if (!pte_none(*page_table)) goto release; inc_mm_counter_fast(mm, MM_ANONPAGES); page_add_new_anon_rmap(page, vma, address); mem_cgroup_commit_charge(page, memcg, false); lru_cache_add_active_or_unevictable(page, vma); setpte: set_pte_at(mm, address, page_table, entry); /* No need to invalidate - it was non-present before */ update_mmu_cache(vma, address, page_table); unlock: pte_unmap_unlock(page_table, ptl); return 0; release: mem_cgroup_cancel_charge(page, memcg); page_cache_release(page); goto unlock; oom_free_page: page_cache_release(page); oom: return VM_FAULT_OOM; } /* * The mmap_sem must have been held on entry, and may have been * released depending on flags and vma->vm_ops->fault() return value. * See filemap_fault() and __lock_page_retry(). */ static int __do_fault(struct vm_area_struct *vma, unsigned long address, pgoff_t pgoff, unsigned int flags, struct page *cow_page, struct page **page) { struct vm_fault vmf; int ret; vmf.virtual_address = (void __user *)(address & PAGE_MASK); vmf.pgoff = pgoff; vmf.flags = flags; vmf.page = NULL; vmf.cow_page = cow_page; ret = vma->vm_ops->fault(vma, &vmf); if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY))) return ret; if (!vmf.page) goto out; if (unlikely(PageHWPoison(vmf.page))) { if (ret & VM_FAULT_LOCKED) unlock_page(vmf.page); page_cache_release(vmf.page); return VM_FAULT_HWPOISON; } if (unlikely(!(ret & VM_FAULT_LOCKED))) lock_page(vmf.page); else VM_BUG_ON_PAGE(!PageLocked(vmf.page), vmf.page); out: *page = vmf.page; return ret; } /** * do_set_pte - setup new PTE entry for given page and add reverse page mapping. * * @vma: virtual memory area * @address: user virtual address * @page: page to map * @pte: pointer to target page table entry * @write: true, if new entry is writable * @anon: true, if it's anonymous page * * Caller must hold page table lock relevant for @pte. * * Target users are page handler itself and implementations of * vm_ops->map_pages. */ void do_set_pte(struct vm_area_struct *vma, unsigned long address, struct page *page, pte_t *pte, bool write, bool anon) { pte_t entry; flush_icache_page(vma, page); entry = mk_pte(page, vma->vm_page_prot); if (write) entry = maybe_mkwrite(pte_mkdirty(entry), vma); if (anon) { inc_mm_counter_fast(vma->vm_mm, MM_ANONPAGES); page_add_new_anon_rmap(page, vma, address); } else { inc_mm_counter_fast(vma->vm_mm, MM_FILEPAGES); page_add_file_rmap(page); } set_pte_at(vma->vm_mm, address, pte, entry); /* no need to invalidate: a not-present page won't be cached */ update_mmu_cache(vma, address, pte); } static unsigned long fault_around_bytes __read_mostly = rounddown_pow_of_two(65536); #ifdef CONFIG_DEBUG_FS static int fault_around_bytes_get(void *data, u64 *val) { *val = fault_around_bytes; return 0; } /* * fault_around_pages() and fault_around_mask() expects fault_around_bytes * rounded down to nearest page order. It's what do_fault_around() expects to * see. */ static int fault_around_bytes_set(void *data, u64 val) { if (val / PAGE_SIZE > PTRS_PER_PTE) return -EINVAL; if (val > PAGE_SIZE) fault_around_bytes = rounddown_pow_of_two(val); else fault_around_bytes = PAGE_SIZE; /* rounddown_pow_of_two(0) is undefined */ return 0; } DEFINE_SIMPLE_ATTRIBUTE(fault_around_bytes_fops, fault_around_bytes_get, fault_around_bytes_set, "%llu\n"); static int __init fault_around_debugfs(void) { void *ret; ret = debugfs_create_file("fault_around_bytes", 0644, NULL, NULL, &fault_around_bytes_fops); if (!ret) pr_warn("Failed to create fault_around_bytes in debugfs"); return 0; } late_initcall(fault_around_debugfs); #endif /* * do_fault_around() tries to map few pages around the fault address. The hope * is that the pages will be needed soon and this will lower the number of * faults to handle. * * It uses vm_ops->map_pages() to map the pages, which skips the page if it's * not ready to be mapped: not up-to-date, locked, etc. * * This function is called with the page table lock taken. In the split ptlock * case the page table lock only protects only those entries which belong to * the page table corresponding to the fault address. * * This function doesn't cross the VMA boundaries, in order to call map_pages() * only once. * * fault_around_pages() defines how many pages we'll try to map. * do_fault_around() expects it to return a power of two less than or equal to * PTRS_PER_PTE. * * The virtual address of the area that we map is naturally aligned to the * fault_around_pages() value (and therefore to page order). This way it's * easier to guarantee that we don't cross page table boundaries. */ static void do_fault_around(struct vm_area_struct *vma, unsigned long address, pte_t *pte, pgoff_t pgoff, unsigned int flags) { unsigned long start_addr, nr_pages, mask; pgoff_t max_pgoff; struct vm_fault vmf; int off; nr_pages = READ_ONCE(fault_around_bytes) >> PAGE_SHIFT; mask = ~(nr_pages * PAGE_SIZE - 1) & PAGE_MASK; start_addr = max(address & mask, vma->vm_start); off = ((address - start_addr) >> PAGE_SHIFT) & (PTRS_PER_PTE - 1); pte -= off; pgoff -= off; /* * max_pgoff is either end of page table or end of vma * or fault_around_pages() from pgoff, depending what is nearest. */ max_pgoff = pgoff - ((start_addr >> PAGE_SHIFT) & (PTRS_PER_PTE - 1)) + PTRS_PER_PTE - 1; max_pgoff = min3(max_pgoff, vma_pages(vma) + vma->vm_pgoff - 1, pgoff + nr_pages - 1); /* Check if it makes any sense to call ->map_pages */ while (!pte_none(*pte)) { if (++pgoff > max_pgoff) return; start_addr += PAGE_SIZE; if (start_addr >= vma->vm_end) return; pte++; } vmf.virtual_address = (void __user *) start_addr; vmf.pte = pte; vmf.pgoff = pgoff; vmf.max_pgoff = max_pgoff; vmf.flags = flags; vma->vm_ops->map_pages(vma, &vmf); } static int do_read_fault(struct mm_struct *mm, struct vm_area_struct *vma, unsigned long address, pmd_t *pmd, pgoff_t pgoff, unsigned int flags, pte_t orig_pte) { struct page *fault_page; spinlock_t *ptl; pte_t *pte; int ret = 0; /* * Let's call ->map_pages() first and use ->fault() as fallback * if page by the offset is not ready to be mapped (cold cache or * something). */ if (vma->vm_ops->map_pages && fault_around_bytes >> PAGE_SHIFT > 1) { pte = pte_offset_map_lock(mm, pmd, address, &ptl); do_fault_around(vma, address, pte, pgoff, flags); if (!pte_same(*pte, orig_pte)) goto unlock_out; pte_unmap_unlock(pte, ptl); } ret = __do_fault(vma, address, pgoff, flags, NULL, &fault_page); if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY))) return ret; pte = pte_offset_map_lock(mm, pmd, address, &ptl); if (unlikely(!pte_same(*pte, orig_pte))) { pte_unmap_unlock(pte, ptl); unlock_page(fault_page); page_cache_release(fault_page); return ret; } do_set_pte(vma, address, fault_page, pte, false, false); unlock_page(fault_page); unlock_out: pte_unmap_unlock(pte, ptl); return ret; } static int do_cow_fault(struct mm_struct *mm, struct vm_area_struct *vma, unsigned long address, pmd_t *pmd, pgoff_t pgoff, unsigned int flags, pte_t orig_pte) { struct page *fault_page, *new_page; struct mem_cgroup *memcg; spinlock_t *ptl; pte_t *pte; int ret; if (unlikely(anon_vma_prepare(vma))) return VM_FAULT_OOM; new_page = alloc_page_vma(GFP_HIGHUSER_MOVABLE, vma, address); if (!new_page) return VM_FAULT_OOM; if (mem_cgroup_try_charge(new_page, mm, GFP_KERNEL, &memcg)) { page_cache_release(new_page); return VM_FAULT_OOM; } ret = __do_fault(vma, address, pgoff, flags, new_page, &fault_page); if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY))) goto uncharge_out; if (fault_page) copy_user_highpage(new_page, fault_page, address, vma); __SetPageUptodate(new_page); pte = pte_offset_map_lock(mm, pmd, address, &ptl); if (unlikely(!pte_same(*pte, orig_pte))) { pte_unmap_unlock(pte, ptl); if (fault_page) { unlock_page(fault_page); page_cache_release(fault_page); } else { /* * The fault handler has no page to lock, so it holds * i_mmap_lock for read to protect against truncate. */ i_mmap_unlock_read(vma->vm_file->f_mapping); } goto uncharge_out; } do_set_pte(vma, address, new_page, pte, true, true); mem_cgroup_commit_charge(new_page, memcg, false); lru_cache_add_active_or_unevictable(new_page, vma); pte_unmap_unlock(pte, ptl); if (fault_page) { unlock_page(fault_page); page_cache_release(fault_page); } else { /* * The fault handler has no page to lock, so it holds * i_mmap_lock for read to protect against truncate. */ i_mmap_unlock_read(vma->vm_file->f_mapping); } return ret; uncharge_out: mem_cgroup_cancel_charge(new_page, memcg); page_cache_release(new_page); return ret; } static int do_shared_fault(struct mm_struct *mm, struct vm_area_struct *vma, unsigned long address, pmd_t *pmd, pgoff_t pgoff, unsigned int flags, pte_t orig_pte) { struct page *fault_page; struct address_space *mapping; spinlock_t *ptl; pte_t *pte; int dirtied = 0; int ret, tmp; ret = __do_fault(vma, address, pgoff, flags, NULL, &fault_page); if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY))) return ret; /* * Check if the backing address space wants to know that the page is * about to become writable */ if (vma->vm_ops->page_mkwrite) { unlock_page(fault_page); tmp = do_page_mkwrite(vma, fault_page, address); if (unlikely(!tmp || (tmp & (VM_FAULT_ERROR | VM_FAULT_NOPAGE)))) { page_cache_release(fault_page); return tmp; } } pte = pte_offset_map_lock(mm, pmd, address, &ptl); if (unlikely(!pte_same(*pte, orig_pte))) { pte_unmap_unlock(pte, ptl); unlock_page(fault_page); page_cache_release(fault_page); return ret; } do_set_pte(vma, address, fault_page, pte, true, false); pte_unmap_unlock(pte, ptl); if (set_page_dirty(fault_page)) dirtied = 1; /* * Take a local copy of the address_space - page.mapping may be zeroed * by truncate after unlock_page(). The address_space itself remains * pinned by vma->vm_file's reference. We rely on unlock_page()'s * release semantics to prevent the compiler from undoing this copying. */ mapping = fault_page->mapping; unlock_page(fault_page); if ((dirtied || vma->vm_ops->page_mkwrite) && mapping) { /* * Some device drivers do not set page.mapping but still * dirty their pages */ balance_dirty_pages_ratelimited(mapping); } if (!vma->vm_ops->page_mkwrite) file_update_time(vma->vm_file); return ret; } /* * We enter with non-exclusive mmap_sem (to exclude vma changes, * but allow concurrent faults). * The mmap_sem may have been released depending on flags and our * return value. See filemap_fault() and __lock_page_or_retry(). */ static int do_fault(struct mm_struct *mm, struct vm_area_struct *vma, unsigned long address, pte_t *page_table, pmd_t *pmd, unsigned int flags, pte_t orig_pte) { pgoff_t pgoff = (((address & PAGE_MASK) - vma->vm_start) >> PAGE_SHIFT) + vma->vm_pgoff; pte_unmap(page_table); if (!(flags & FAULT_FLAG_WRITE)) return do_read_fault(mm, vma, address, pmd, pgoff, flags, orig_pte); if (!(vma->vm_flags & VM_SHARED)) return do_cow_fault(mm, vma, address, pmd, pgoff, flags, orig_pte); return do_shared_fault(mm, vma, address, pmd, pgoff, flags, orig_pte); } static int numa_migrate_prep(struct page *page, struct vm_area_struct *vma, unsigned long addr, int page_nid, int *flags) { get_page(page); count_vm_numa_event(NUMA_HINT_FAULTS); if (page_nid == numa_node_id()) { count_vm_numa_event(NUMA_HINT_FAULTS_LOCAL); *flags |= TNF_FAULT_LOCAL; } return mpol_misplaced(page, vma, addr); } static int do_numa_page(struct mm_struct *mm, struct vm_area_struct *vma, unsigned long addr, pte_t pte, pte_t *ptep, pmd_t *pmd) { struct page *page = NULL; spinlock_t *ptl; int page_nid = -1; int last_cpupid; int target_nid; bool migrated = false; bool was_writable = pte_write(pte); int flags = 0; /* A PROT_NONE fault should not end up here */ BUG_ON(!(vma->vm_flags & (VM_READ | VM_EXEC | VM_WRITE))); /* * The "pte" at this point cannot be used safely without * validation through pte_unmap_same(). It's of NUMA type but * the pfn may be screwed if the read is non atomic. * * We can safely just do a "set_pte_at()", because the old * page table entry is not accessible, so there would be no * concurrent hardware modifications to the PTE. */ ptl = pte_lockptr(mm, pmd); spin_lock(ptl); if (unlikely(!pte_same(*ptep, pte))) { pte_unmap_unlock(ptep, ptl); goto out; } /* Make it present again */ pte = pte_modify(pte, vma->vm_page_prot); pte = pte_mkyoung(pte); if (was_writable) pte = pte_mkwrite(pte); set_pte_at(mm, addr, ptep, pte); update_mmu_cache(vma, addr, ptep); page = vm_normal_page(vma, addr, pte); if (!page) { pte_unmap_unlock(ptep, ptl); return 0; } /* * Avoid grouping on RO pages in general. RO pages shouldn't hurt as * much anyway since they can be in shared cache state. This misses * the case where a mapping is writable but the process never writes * to it but pte_write gets cleared during protection updates and * pte_dirty has unpredictable behaviour between PTE scan updates, * background writeback, dirty balancing and application behaviour. */ if (!(vma->vm_flags & VM_WRITE)) flags |= TNF_NO_GROUP; /* * Flag if the page is shared between multiple address spaces. This * is later used when determining whether to group tasks together */ if (page_mapcount(page) > 1 && (vma->vm_flags & VM_SHARED)) flags |= TNF_SHARED; last_cpupid = page_cpupid_last(page); page_nid = page_to_nid(page); target_nid = numa_migrate_prep(page, vma, addr, page_nid, &flags); pte_unmap_unlock(ptep, ptl); if (target_nid == -1) { put_page(page); goto out; } /* Migrate to the requested node */ migrated = migrate_misplaced_page(page, vma, target_nid); if (migrated) { page_nid = target_nid; flags |= TNF_MIGRATED; } else flags |= TNF_MIGRATE_FAIL; out: if (page_nid != -1) task_numa_fault(last_cpupid, page_nid, 1, flags); return 0; } /* * These routines also need to handle stuff like marking pages dirty * and/or accessed for architectures that don't do it in hardware (most * RISC architectures). The early dirtying is also good on the i386. * * There is also a hook called "update_mmu_cache()" that architectures * with external mmu caches can use to update those (ie the Sparc or * PowerPC hashed page tables that act as extended TLBs). * * We enter with non-exclusive mmap_sem (to exclude vma changes, * but allow concurrent faults), and pte mapped but not yet locked. * We return with pte unmapped and unlocked. * * The mmap_sem may have been released depending on flags and our * return value. See filemap_fault() and __lock_page_or_retry(). */ static int handle_pte_fault(struct mm_struct *mm, struct vm_area_struct *vma, unsigned long address, pte_t *pte, pmd_t *pmd, unsigned int flags) { pte_t entry; spinlock_t *ptl; /* * some architectures can have larger ptes than wordsize, * e.g.ppc44x-defconfig has CONFIG_PTE_64BIT=y and CONFIG_32BIT=y, * so READ_ONCE or ACCESS_ONCE cannot guarantee atomic accesses. * The code below just needs a consistent view for the ifs and * we later double check anyway with the ptl lock held. So here * a barrier will do. */ entry = *pte; barrier(); if (!pte_present(entry)) { if (pte_none(entry)) { if (vma->vm_ops) { if (likely(vma->vm_ops->fault)) return do_fault(mm, vma, address, pte, pmd, flags, entry); } return do_anonymous_page(mm, vma, address, pte, pmd, flags); } return do_swap_page(mm, vma, address, pte, pmd, flags, entry); } if (pte_protnone(entry)) return do_numa_page(mm, vma, address, entry, pte, pmd); ptl = pte_lockptr(mm, pmd); spin_lock(ptl); if (unlikely(!pte_same(*pte, entry))) goto unlock; if (flags & FAULT_FLAG_WRITE) { if (!pte_write(entry)) return do_wp_page(mm, vma, address, pte, pmd, ptl, entry); entry = pte_mkdirty(entry); } entry = pte_mkyoung(entry); if (ptep_set_access_flags(vma, address, pte, entry, flags & FAULT_FLAG_WRITE)) { update_mmu_cache(vma, address, pte); } else { /* * This is needed only for protection faults but the arch code * is not yet telling us if this is a protection fault or not. * This still avoids useless tlb flushes for .text page faults * with threads. */ if (flags & FAULT_FLAG_WRITE) flush_tlb_fix_spurious_fault(vma, address); } unlock: pte_unmap_unlock(pte, ptl); return 0; } /* * By the time we get here, we already hold the mm semaphore * * The mmap_sem may have been released depending on flags and our * return value. See filemap_fault() and __lock_page_or_retry(). */ static int __handle_mm_fault(struct mm_struct *mm, struct vm_area_struct *vma, unsigned long address, unsigned int flags) { pgd_t *pgd; pud_t *pud; pmd_t *pmd; pte_t *pte; if (unlikely(is_vm_hugetlb_page(vma))) return hugetlb_fault(mm, vma, address, flags); pgd = pgd_offset(mm, address); pud = pud_alloc(mm, pgd, address); if (!pud) return VM_FAULT_OOM; pmd = pmd_alloc(mm, pud, address); if (!pmd) return VM_FAULT_OOM; if (pmd_none(*pmd) && transparent_hugepage_enabled(vma)) { int ret = VM_FAULT_FALLBACK; if (!vma->vm_ops) ret = do_huge_pmd_anonymous_page(mm, vma, address, pmd, flags); if (!(ret & VM_FAULT_FALLBACK)) return ret; } else { pmd_t orig_pmd = *pmd; int ret; barrier(); if (pmd_trans_huge(orig_pmd)) { unsigned int dirty = flags & FAULT_FLAG_WRITE; /* * If the pmd is splitting, return and retry the * the fault. Alternative: wait until the split * is done, and goto retry. */ if (pmd_trans_splitting(orig_pmd)) return 0; if (pmd_protnone(orig_pmd)) return do_huge_pmd_numa_page(mm, vma, address, orig_pmd, pmd); if (dirty && !pmd_write(orig_pmd)) { ret = do_huge_pmd_wp_page(mm, vma, address, pmd, orig_pmd); if (!(ret & VM_FAULT_FALLBACK)) return ret; } else { huge_pmd_set_accessed(mm, vma, address, pmd, orig_pmd, dirty); return 0; } } } /* * Use __pte_alloc instead of pte_alloc_map, because we can't * run pte_offset_map on the pmd, if an huge pmd could * materialize from under us from a different thread. */ if (unlikely(pmd_none(*pmd)) && unlikely(__pte_alloc(mm, vma, pmd, address))) return VM_FAULT_OOM; /* if an huge pmd materialized from under us just retry later */ if (unlikely(pmd_trans_huge(*pmd))) return 0; /* * A regular pmd is established and it can't morph into a huge pmd * from under us anymore at this point because we hold the mmap_sem * read mode and khugepaged takes it in write mode. So now it's * safe to run pte_offset_map(). */ pte = pte_offset_map(pmd, address); return handle_pte_fault(mm, vma, address, pte, pmd, flags); } /* * By the time we get here, we already hold the mm semaphore * * The mmap_sem may have been released depending on flags and our * return value. See filemap_fault() and __lock_page_or_retry(). */ int handle_mm_fault(struct mm_struct *mm, struct vm_area_struct *vma, unsigned long address, unsigned int flags) { int ret; __set_current_state(TASK_RUNNING); count_vm_event(PGFAULT); mem_cgroup_count_vm_event(mm, PGFAULT); /* do counter updates before entering really critical section. */ check_sync_rss_stat(current); /* * Enable the memcg OOM handling for faults triggered in user * space. Kernel faults are handled more gracefully. */ if (flags & FAULT_FLAG_USER) mem_cgroup_oom_enable(); ret = __handle_mm_fault(mm, vma, address, flags); if (flags & FAULT_FLAG_USER) { mem_cgroup_oom_disable(); /* * The task may have entered a memcg OOM situation but * if the allocation error was handled gracefully (no * VM_FAULT_OOM), there is no need to kill anything. * Just clean up the OOM state peacefully. */ if (task_in_memcg_oom(current) && !(ret & VM_FAULT_OOM)) mem_cgroup_oom_synchronize(false); } return ret; } EXPORT_SYMBOL_GPL(handle_mm_fault); #ifndef __PAGETABLE_PUD_FOLDED /* * Allocate page upper directory. * We've already handled the fast-path in-line. */ int __pud_alloc(struct mm_struct *mm, pgd_t *pgd, unsigned long address) { pud_t *new = pud_alloc_one(mm, address); if (!new) return -ENOMEM; smp_wmb(); /* See comment in __pte_alloc */ spin_lock(&mm->page_table_lock); if (pgd_present(*pgd)) /* Another has populated it */ pud_free(mm, new); else pgd_populate(mm, pgd, new); spin_unlock(&mm->page_table_lock); return 0; } #endif /* __PAGETABLE_PUD_FOLDED */ #ifndef __PAGETABLE_PMD_FOLDED /* * Allocate page middle directory. * We've already handled the fast-path in-line. */ int __pmd_alloc(struct mm_struct *mm, pud_t *pud, unsigned long address) { pmd_t *new = pmd_alloc_one(mm, address); if (!new) return -ENOMEM; smp_wmb(); /* See comment in __pte_alloc */ spin_lock(&mm->page_table_lock); #ifndef __ARCH_HAS_4LEVEL_HACK if (!pud_present(*pud)) { mm_inc_nr_pmds(mm); pud_populate(mm, pud, new); } else /* Another has populated it */ pmd_free(mm, new); #else if (!pgd_present(*pud)) { mm_inc_nr_pmds(mm); pgd_populate(mm, pud, new); } else /* Another has populated it */ pmd_free(mm, new); #endif /* __ARCH_HAS_4LEVEL_HACK */ spin_unlock(&mm->page_table_lock); return 0; } #endif /* __PAGETABLE_PMD_FOLDED */ static int __follow_pte(struct mm_struct *mm, unsigned long address, pte_t **ptepp, spinlock_t **ptlp) { pgd_t *pgd; pud_t *pud; pmd_t *pmd; pte_t *ptep; pgd = pgd_offset(mm, address); if (pgd_none(*pgd) || unlikely(pgd_bad(*pgd))) goto out; pud = pud_offset(pgd, address); if (pud_none(*pud) || unlikely(pud_bad(*pud))) goto out; pmd = pmd_offset(pud, address); VM_BUG_ON(pmd_trans_huge(*pmd)); if (pmd_none(*pmd) || unlikely(pmd_bad(*pmd))) goto out; /* We cannot handle huge page PFN maps. Luckily they don't exist. */ if (pmd_huge(*pmd)) goto out; ptep = pte_offset_map_lock(mm, pmd, address, ptlp); if (!ptep) goto out; if (!pte_present(*ptep)) goto unlock; *ptepp = ptep; return 0; unlock: pte_unmap_unlock(ptep, *ptlp); out: return -EINVAL; } static inline int follow_pte(struct mm_struct *mm, unsigned long address, pte_t **ptepp, spinlock_t **ptlp) { int res; /* (void) is needed to make gcc happy */ (void) __cond_lock(*ptlp, !(res = __follow_pte(mm, address, ptepp, ptlp))); return res; } /** * follow_pfn - look up PFN at a user virtual address * @vma: memory mapping * @address: user virtual address * @pfn: location to store found PFN * * Only IO mappings and raw PFN mappings are allowed. * * Returns zero and the pfn at @pfn on success, -ve otherwise. */ int follow_pfn(struct vm_area_struct *vma, unsigned long address, unsigned long *pfn) { int ret = -EINVAL; spinlock_t *ptl; pte_t *ptep; if (!(vma->vm_flags & (VM_IO | VM_PFNMAP))) return ret; ret = follow_pte(vma->vm_mm, address, &ptep, &ptl); if (ret) return ret; *pfn = pte_pfn(*ptep); pte_unmap_unlock(ptep, ptl); return 0; } EXPORT_SYMBOL(follow_pfn); #ifdef CONFIG_HAVE_IOREMAP_PROT int follow_phys(struct vm_area_struct *vma, unsigned long address, unsigned int flags, unsigned long *prot, resource_size_t *phys) { int ret = -EINVAL; pte_t *ptep, pte; spinlock_t *ptl; if (!(vma->vm_flags & (VM_IO | VM_PFNMAP))) goto out; if (follow_pte(vma->vm_mm, address, &ptep, &ptl)) goto out; pte = *ptep; if ((flags & FOLL_WRITE) && !pte_write(pte)) goto unlock; *prot = pgprot_val(pte_pgprot(pte)); *phys = (resource_size_t)pte_pfn(pte) << PAGE_SHIFT; ret = 0; unlock: pte_unmap_unlock(ptep, ptl); out: return ret; } int generic_access_phys(struct vm_area_struct *vma, unsigned long addr, void *buf, int len, int write) { resource_size_t phys_addr; unsigned long prot = 0; void __iomem *maddr; int offset = addr & (PAGE_SIZE-1); if (follow_phys(vma, addr, write, &prot, &phys_addr)) return -EINVAL; maddr = ioremap_prot(phys_addr, PAGE_ALIGN(len + offset), prot); if (write) memcpy_toio(maddr + offset, buf, len); else memcpy_fromio(buf, maddr + offset, len); iounmap(maddr); return len; } EXPORT_SYMBOL_GPL(generic_access_phys); #endif /* * Access another process' address space as given in mm. If non-NULL, use the * given task for page fault accounting. */ static int __access_remote_vm(struct task_struct *tsk, struct mm_struct *mm, unsigned long addr, void *buf, int len, int write) { struct vm_area_struct *vma; void *old_buf = buf; down_read(&mm->mmap_sem); /* ignore errors, just check how much was successfully transferred */ while (len) { int bytes, ret, offset; void *maddr; struct page *page = NULL; ret = get_user_pages(tsk, mm, addr, 1, write, 1, &page, &vma); if (ret <= 0) { #ifndef CONFIG_HAVE_IOREMAP_PROT break; #else /* * Check if this is a VM_IO | VM_PFNMAP VMA, which * we can access using slightly different code. */ vma = find_vma(mm, addr); if (!vma || vma->vm_start > addr) break; if (vma->vm_ops && vma->vm_ops->access) ret = vma->vm_ops->access(vma, addr, buf, len, write); if (ret <= 0) break; bytes = ret; #endif } else { bytes = len; offset = addr & (PAGE_SIZE-1); if (bytes > PAGE_SIZE-offset) bytes = PAGE_SIZE-offset; maddr = kmap(page); if (write) { copy_to_user_page(vma, page, addr, maddr + offset, buf, bytes); set_page_dirty_lock(page); } else { copy_from_user_page(vma, page, addr, buf, maddr + offset, bytes); } kunmap(page); page_cache_release(page); } len -= bytes; buf += bytes; addr += bytes; } up_read(&mm->mmap_sem); return buf - old_buf; } /** * access_remote_vm - access another process' address space * @mm: the mm_struct of the target address space * @addr: start address to access * @buf: source or destination buffer * @len: number of bytes to transfer * @write: whether the access is a write * * The caller must hold a reference on @mm. */ int access_remote_vm(struct mm_struct *mm, unsigned long addr, void *buf, int len, int write) { return __access_remote_vm(NULL, mm, addr, buf, len, write); } /* * Access another process' address space. * Source/target buffer must be kernel space, * Do not walk the page table directly, use get_user_pages */ int access_process_vm(struct task_struct *tsk, unsigned long addr, void *buf, int len, int write) { struct mm_struct *mm; int ret; mm = get_task_mm(tsk); if (!mm) return 0; ret = __access_remote_vm(tsk, mm, addr, buf, len, write); mmput(mm); return ret; } /* * Print the name of a VMA. */ void print_vma_addr(char *prefix, unsigned long ip) { struct mm_struct *mm = current->mm; struct vm_area_struct *vma; /* * Do not print if we are in atomic * contexts (in exception stacks, etc.): */ if (preempt_count()) return; down_read(&mm->mmap_sem); vma = find_vma(mm, ip); if (vma && vma->vm_file) { struct file *f = vma->vm_file; char *buf = (char *)__get_free_page(GFP_KERNEL); if (buf) { char *p; p = file_path(f, buf, PAGE_SIZE); if (IS_ERR(p)) p = "?"; printk("%s%s[%lx+%lx]", prefix, kbasename(p), vma->vm_start, vma->vm_end - vma->vm_start); free_page((unsigned long)buf); } } up_read(&mm->mmap_sem); } #if defined(CONFIG_PROVE_LOCKING) || defined(CONFIG_DEBUG_ATOMIC_SLEEP) void __might_fault(const char *file, int line) { /* * Some code (nfs/sunrpc) uses socket ops on kernel memory while * holding the mmap_sem, this is safe because kernel memory doesn't * get paged out, therefore we'll never actually fault, and the * below annotations will generate false positives. */ if (segment_eq(get_fs(), KERNEL_DS)) return; if (pagefault_disabled()) return; __might_sleep(file, line, 0); #if defined(CONFIG_DEBUG_ATOMIC_SLEEP) if (current->mm) might_lock_read(&current->mm->mmap_sem); #endif } EXPORT_SYMBOL(__might_fault); #endif #if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_HUGETLBFS) static void clear_gigantic_page(struct page *page, unsigned long addr, unsigned int pages_per_huge_page) { int i; struct page *p = page; might_sleep(); for (i = 0; i < pages_per_huge_page; i++, p = mem_map_next(p, page, i)) { cond_resched(); clear_user_highpage(p, addr + i * PAGE_SIZE); } } void clear_huge_page(struct page *page, unsigned long addr, unsigned int pages_per_huge_page) { int i; if (unlikely(pages_per_huge_page > MAX_ORDER_NR_PAGES)) { clear_gigantic_page(page, addr, pages_per_huge_page); return; } might_sleep(); for (i = 0; i < pages_per_huge_page; i++) { cond_resched(); clear_user_highpage(page + i, addr + i * PAGE_SIZE); } } static void copy_user_gigantic_page(struct page *dst, struct page *src, unsigned long addr, struct vm_area_struct *vma, unsigned int pages_per_huge_page) { int i; struct page *dst_base = dst; struct page *src_base = src; for (i = 0; i < pages_per_huge_page; ) { cond_resched(); copy_user_highpage(dst, src, addr + i*PAGE_SIZE, vma); i++; dst = mem_map_next(dst, dst_base, i); src = mem_map_next(src, src_base, i); } } void copy_user_huge_page(struct page *dst, struct page *src, unsigned long addr, struct vm_area_struct *vma, unsigned int pages_per_huge_page) { int i; if (unlikely(pages_per_huge_page > MAX_ORDER_NR_PAGES)) { copy_user_gigantic_page(dst, src, addr, vma, pages_per_huge_page); return; } might_sleep(); for (i = 0; i < pages_per_huge_page; i++) { cond_resched(); copy_user_highpage(dst + i, src + i, addr + i*PAGE_SIZE, vma); } } #endif /* CONFIG_TRANSPARENT_HUGEPAGE || CONFIG_HUGETLBFS */ #if USE_SPLIT_PTE_PTLOCKS && ALLOC_SPLIT_PTLOCKS static struct kmem_cache *page_ptl_cachep; void __init ptlock_cache_init(void) { page_ptl_cachep = kmem_cache_create("page->ptl", sizeof(spinlock_t), 0, SLAB_PANIC, NULL); } bool ptlock_alloc(struct page *page) { spinlock_t *ptl; ptl = kmem_cache_alloc(page_ptl_cachep, GFP_KERNEL); if (!ptl) return false; page->ptl = ptl; return true; } void ptlock_free(struct page *page) { kmem_cache_free(page_ptl_cachep, page->ptl); } #endif
./CrossVul/dataset_final_sorted/CWE-20/c/bad_1583_0
crossvul-cpp_data_good_722_0
/* Copyright (C) 2007-2014 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * 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 * version 2 along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ /** * \file * * \author Victor Julien <victor@inliniac.net> * \author Anoop Saldanha <anoopsaldanha@gmail.com> */ #include "suricata-common.h" #include "debug.h" #include "decode.h" #include "threads.h" #include "threadvars.h" #include "tm-threads.h" #include "detect.h" #include "detect-engine-port.h" #include "detect-parse.h" #include "detect-engine.h" #include "detect-content.h" #include "detect-engine-mpm.h" #include "detect-engine-state.h" #include "util-print.h" #include "util-pool.h" #include "util-unittest.h" #include "util-unittest-helper.h" #include "flow.h" #include "flow-util.h" #include "flow-private.h" #include "stream-tcp-private.h" #include "stream-tcp-reassemble.h" #include "stream-tcp.h" #include "stream.h" #include "app-layer.h" #include "app-layer-protos.h" #include "app-layer-parser.h" #include "app-layer-detect-proto.h" #include "app-layer-expectation.h" #include "conf.h" #include "util-memcmp.h" #include "util-spm.h" #include "util-debug.h" #include "runmodes.h" typedef struct AppLayerProtoDetectProbingParserElement_ { AppProto alproto; /* \todo don't really need it. See if you can get rid of it */ uint16_t port; /* \todo calculate at runtime and get rid of this var */ uint32_t alproto_mask; /* \todo check if we can reduce the bottom 2 vars to uint16_t */ /* the min length of data that has to be supplied to invoke the parser */ uint32_t min_depth; /* the max length of data after which this parser won't be invoked */ uint32_t max_depth; /* the to_server probing parser function */ ProbingParserFPtr ProbingParserTs; /* the to_client probing parser function */ ProbingParserFPtr ProbingParserTc; struct AppLayerProtoDetectProbingParserElement_ *next; } AppLayerProtoDetectProbingParserElement; typedef struct AppLayerProtoDetectProbingParserPort_ { /* the port no for which probing parser(s) are invoked */ uint16_t port; uint32_t alproto_mask; /* the max depth for all the probing parsers registered for this port */ uint16_t dp_max_depth; uint16_t sp_max_depth; AppLayerProtoDetectProbingParserElement *dp; AppLayerProtoDetectProbingParserElement *sp; struct AppLayerProtoDetectProbingParserPort_ *next; } AppLayerProtoDetectProbingParserPort; typedef struct AppLayerProtoDetectProbingParser_ { uint8_t ipproto; AppLayerProtoDetectProbingParserPort *port; struct AppLayerProtoDetectProbingParser_ *next; } AppLayerProtoDetectProbingParser; typedef struct AppLayerProtoDetectPMSignature_ { AppProto alproto; SigIntId id; /* \todo Change this into a non-pointer */ DetectContentData *cd; struct AppLayerProtoDetectPMSignature_ *next; } AppLayerProtoDetectPMSignature; typedef struct AppLayerProtoDetectPMCtx_ { uint16_t max_len; uint16_t min_len; MpmCtx mpm_ctx; /** Mapping between pattern id and signature. As each signature has a * unique pattern with a unique id, we can lookup the signature by * the pattern id. */ AppLayerProtoDetectPMSignature **map; AppLayerProtoDetectPMSignature *head; /* \todo we don't need this except at setup time. Get rid of it. */ PatIntId max_pat_id; SigIntId max_sig_id; } AppLayerProtoDetectPMCtx; typedef struct AppLayerProtoDetectCtxIpproto_ { /* 0 - toserver, 1 - toclient */ AppLayerProtoDetectPMCtx ctx_pm[2]; } AppLayerProtoDetectCtxIpproto; /** * \brief The app layer protocol detection context. */ typedef struct AppLayerProtoDetectCtx_ { /* Context per ip_proto. * \todo Modify ctx_ipp to hold for only tcp and udp. The rest can be * implemented if needed. Waste of space otherwise. */ AppLayerProtoDetectCtxIpproto ctx_ipp[FLOW_PROTO_DEFAULT]; /* Global SPM thread context prototype. */ SpmGlobalThreadCtx *spm_global_thread_ctx; AppLayerProtoDetectProbingParser *ctx_pp; /* Indicates the protocols that have registered themselves * for protocol detection. This table is independent of the * ipproto. */ const char *alproto_names[ALPROTO_MAX]; } AppLayerProtoDetectCtx; /** * \brief The app layer protocol detection thread context. */ struct AppLayerProtoDetectThreadCtx_ { PrefilterRuleStore pmq; /* The value 2 is for direction(0 - toserver, 1 - toclient). */ MpmThreadCtx mpm_tctx[FLOW_PROTO_DEFAULT][2]; SpmThreadCtx *spm_thread_ctx; }; /* The global app layer proto detection context. */ static AppLayerProtoDetectCtx alpd_ctx; static void AppLayerProtoDetectPEGetIpprotos(AppProto alproto, uint8_t *ipprotos); /***** Static Internal Calls: Protocol Retrieval *****/ /** \internal * \brief Handle SPM search for Signature */ static AppProto AppLayerProtoDetectPMMatchSignature(const AppLayerProtoDetectPMSignature *s, AppLayerProtoDetectThreadCtx *tctx, uint8_t *buf, uint16_t buflen, uint8_t ipproto) { SCEnter(); AppProto proto = ALPROTO_UNKNOWN; uint8_t *found = NULL; if (s->cd->offset > buflen) { SCLogDebug("s->co->offset (%"PRIu16") > buflen (%"PRIu16")", s->cd->offset, buflen); goto end; } if (s->cd->depth > buflen) { SCLogDebug("s->co->depth (%"PRIu16") > buflen (%"PRIu16")", s->cd->depth, buflen); goto end; } uint8_t *sbuf = buf + s->cd->offset; uint16_t sbuflen = s->cd->depth - s->cd->offset; SCLogDebug("s->co->offset (%"PRIu16") s->cd->depth (%"PRIu16")", s->cd->offset, s->cd->depth); found = SpmScan(s->cd->spm_ctx, tctx->spm_thread_ctx, sbuf, sbuflen); if (found != NULL) proto = s->alproto; end: SCReturnUInt(proto); } /** \internal * \brief Run Pattern Sigs against buffer * \param pm_results[out] AppProto array of size ALPROTO_MAX */ static AppProto AppLayerProtoDetectPMGetProto(AppLayerProtoDetectThreadCtx *tctx, Flow *f, uint8_t *buf, uint16_t buflen, uint8_t direction, uint8_t ipproto, AppProto *pm_results) { SCEnter(); pm_results[0] = ALPROTO_UNKNOWN; AppLayerProtoDetectPMCtx *pm_ctx; MpmThreadCtx *mpm_tctx; uint16_t pm_matches = 0; uint8_t cnt; uint16_t searchlen; if (f->protomap >= FLOW_PROTO_DEFAULT) return ALPROTO_UNKNOWN; if (direction & STREAM_TOSERVER) { pm_ctx = &alpd_ctx.ctx_ipp[f->protomap].ctx_pm[0]; mpm_tctx = &tctx->mpm_tctx[f->protomap][0]; } else { pm_ctx = &alpd_ctx.ctx_ipp[f->protomap].ctx_pm[1]; mpm_tctx = &tctx->mpm_tctx[f->protomap][1]; } if (pm_ctx->mpm_ctx.pattern_cnt == 0) goto end; searchlen = buflen; if (searchlen > pm_ctx->max_len) searchlen = pm_ctx->max_len; uint32_t search_cnt = 0; /* do the mpm search */ search_cnt = mpm_table[pm_ctx->mpm_ctx.mpm_type].Search(&pm_ctx->mpm_ctx, mpm_tctx, &tctx->pmq, buf, searchlen); if (search_cnt == 0) goto end; /* alproto bit field */ uint8_t pm_results_bf[(ALPROTO_MAX / 8) + 1]; memset(pm_results_bf, 0, sizeof(pm_results_bf)); /* loop through unique pattern id's. Can't use search_cnt here, * as that contains all matches, tctx->pmq.pattern_id_array_cnt * contains only *unique* matches. */ for (cnt = 0; cnt < tctx->pmq.rule_id_array_cnt; cnt++) { const AppLayerProtoDetectPMSignature *s = pm_ctx->map[tctx->pmq.rule_id_array[cnt]]; while (s != NULL) { AppProto proto = AppLayerProtoDetectPMMatchSignature(s, tctx, buf, searchlen, ipproto); /* store each unique proto once */ if (proto != ALPROTO_UNKNOWN && !(pm_results_bf[proto / 8] & (1 << (proto % 8))) ) { pm_results[pm_matches++] = proto; pm_results_bf[proto / 8] |= 1 << (proto % 8); } s = s->next; } } end: PmqReset(&tctx->pmq); if (buflen >= pm_ctx->max_len) FLOW_SET_PM_DONE(f, direction); SCReturnUInt(pm_matches); } static AppLayerProtoDetectProbingParserPort *AppLayerProtoDetectGetProbingParsers(AppLayerProtoDetectProbingParser *pp, uint8_t ipproto, uint16_t port) { AppLayerProtoDetectProbingParserPort *pp_port = NULL; while (pp != NULL) { if (pp->ipproto == ipproto) break; pp = pp->next; } if (pp == NULL) goto end; pp_port = pp->port; while (pp_port != NULL) { if (pp_port->port == port || pp_port->port == 0) { break; } pp_port = pp_port->next; } end: SCReturnPtr(pp_port, "AppLayerProtoDetectProbingParserPort *"); } /** * \brief Call the probing expectation to see if there is some for this flow. * */ static AppProto AppLayerProtoDetectPEGetProto(Flow *f, uint8_t ipproto, uint8_t direction) { AppProto alproto = ALPROTO_UNKNOWN; SCLogDebug("expectation check for %p (dir %d)", f, direction); FLOW_SET_PE_DONE(f, direction); alproto = AppLayerExpectationHandle(f, direction); return alproto; } /** * \brief Call the probing parser if it exists for this flow. * * First we check the flow's dp as it's most likely to match. If that didn't * lead to a PP, we try the sp. * */ static AppProto AppLayerProtoDetectPPGetProto(Flow *f, uint8_t *buf, uint32_t buflen, uint8_t ipproto, uint8_t direction) { const AppLayerProtoDetectProbingParserPort *pp_port_dp = NULL; const AppLayerProtoDetectProbingParserPort *pp_port_sp = NULL; const AppLayerProtoDetectProbingParserElement *pe = NULL; const AppLayerProtoDetectProbingParserElement *pe1 = NULL; const AppLayerProtoDetectProbingParserElement *pe2 = NULL; AppProto alproto = ALPROTO_UNKNOWN; uint32_t *alproto_masks; uint32_t mask = 0; const uint16_t dp = f->protodetect_dp ? f->protodetect_dp : f->dp; const uint16_t sp = f->sp; if (direction & STREAM_TOSERVER) { /* first try the destination port */ pp_port_dp = AppLayerProtoDetectGetProbingParsers(alpd_ctx.ctx_pp, ipproto, dp); alproto_masks = &f->probing_parser_toserver_alproto_masks; if (pp_port_dp != NULL) { SCLogDebug("toserver - Probing parser found for destination port %"PRIu16, dp); /* found based on destination port, so use dp registration */ pe1 = pp_port_dp->dp; } else { SCLogDebug("toserver - No probing parser registered for dest port %"PRIu16, dp); } pp_port_sp = AppLayerProtoDetectGetProbingParsers(alpd_ctx.ctx_pp, ipproto, sp); if (pp_port_sp != NULL) { SCLogDebug("toserver - Probing parser found for source port %"PRIu16, sp); /* found based on source port, so use sp registration */ pe2 = pp_port_sp->sp; } else { SCLogDebug("toserver - No probing parser registered for source port %"PRIu16, sp); } } else { /* first try the destination port */ pp_port_dp = AppLayerProtoDetectGetProbingParsers(alpd_ctx.ctx_pp, ipproto, dp); alproto_masks = &f->probing_parser_toclient_alproto_masks; if (pp_port_dp != NULL) { SCLogDebug("toclient - Probing parser found for destination port %"PRIu16, dp); /* found based on destination port, so use dp registration */ pe1 = pp_port_dp->dp; } else { SCLogDebug("toclient - No probing parser registered for dest port %"PRIu16, dp); } pp_port_sp = AppLayerProtoDetectGetProbingParsers(alpd_ctx.ctx_pp, ipproto, sp); if (pp_port_sp != NULL) { SCLogDebug("toclient - Probing parser found for source port %"PRIu16, sp); pe2 = pp_port_sp->sp; } else { SCLogDebug("toclient - No probing parser registered for source port %"PRIu16, sp); } } if (pe1 == NULL && pe2 == NULL) { SCLogDebug("%s - No probing parsers found for either port", (direction & STREAM_TOSERVER) ? "toserver":"toclient"); FLOW_SET_PP_DONE(f, direction); goto end; } /* run the parser(s) */ pe = pe1; while (pe != NULL) { if ((buflen < pe->min_depth) || (alproto_masks[0] & pe->alproto_mask)) { pe = pe->next; continue; } if (direction & STREAM_TOSERVER && pe->ProbingParserTs != NULL) { alproto = pe->ProbingParserTs(f, buf, buflen); } else if (pe->ProbingParserTc != NULL) { alproto = pe->ProbingParserTc(f, buf, buflen); } if (alproto != ALPROTO_UNKNOWN && alproto != ALPROTO_FAILED) goto end; if (alproto == ALPROTO_FAILED || (pe->max_depth != 0 && buflen > pe->max_depth)) { alproto_masks[0] |= pe->alproto_mask; } pe = pe->next; } pe = pe2; while (pe != NULL) { if ((buflen < pe->min_depth) || (alproto_masks[0] & pe->alproto_mask)) { pe = pe->next; continue; } if (direction & STREAM_TOSERVER && pe->ProbingParserTs != NULL) { alproto = pe->ProbingParserTs(f, buf, buflen); } else if (pe->ProbingParserTc != NULL) { alproto = pe->ProbingParserTc(f, buf, buflen); } if (alproto != ALPROTO_UNKNOWN && alproto != ALPROTO_FAILED) goto end; if (alproto == ALPROTO_FAILED || (pe->max_depth != 0 && buflen > pe->max_depth)) { alproto_masks[0] |= pe->alproto_mask; } pe = pe->next; } /* get the mask we need for this direction */ if (pp_port_dp && pp_port_sp) mask = pp_port_dp->alproto_mask|pp_port_sp->alproto_mask; else if (pp_port_dp) mask = pp_port_dp->alproto_mask; else if (pp_port_sp) mask = pp_port_sp->alproto_mask; if (alproto_masks[0] == mask) { FLOW_SET_PP_DONE(f, direction); SCLogDebug("%s, mask is now %08x, needed %08x, so done", (direction & STREAM_TOSERVER) ? "toserver":"toclient", alproto_masks[0], mask); } else { SCLogDebug("%s, mask is now %08x, need %08x", (direction & STREAM_TOSERVER) ? "toserver":"toclient", alproto_masks[0], mask); } end: SCLogDebug("%s, mask is now %08x", (direction & STREAM_TOSERVER) ? "toserver":"toclient", alproto_masks[0]); SCReturnUInt(alproto); } /***** Static Internal Calls: PP registration *****/ static void AppLayerProtoDetectPPGetIpprotos(AppProto alproto, uint8_t *ipprotos) { SCEnter(); const AppLayerProtoDetectProbingParser *pp; const AppLayerProtoDetectProbingParserPort *pp_port; const AppLayerProtoDetectProbingParserElement *pp_pe; for (pp = alpd_ctx.ctx_pp; pp != NULL; pp = pp->next) { for (pp_port = pp->port; pp_port != NULL; pp_port = pp_port->next) { for (pp_pe = pp_port->dp; pp_pe != NULL; pp_pe = pp_pe->next) { if (alproto == pp_pe->alproto) ipprotos[pp->ipproto / 8] |= 1 << (pp->ipproto % 8); } for (pp_pe = pp_port->sp; pp_pe != NULL; pp_pe = pp_pe->next) { if (alproto == pp_pe->alproto) ipprotos[pp->ipproto / 8] |= 1 << (pp->ipproto % 8); } } } SCReturn; } static uint32_t AppLayerProtoDetectProbingParserGetMask(AppProto alproto) { SCEnter(); if (!(alproto > ALPROTO_UNKNOWN && alproto < ALPROTO_FAILED)) { SCLogError(SC_ERR_ALPARSER, "Unknown protocol detected - %"PRIu16, alproto); exit(EXIT_FAILURE); } SCReturnUInt(1 << alproto); } static AppLayerProtoDetectProbingParserElement *AppLayerProtoDetectProbingParserElementAlloc(void) { SCEnter(); AppLayerProtoDetectProbingParserElement *p = SCMalloc(sizeof(AppLayerProtoDetectProbingParserElement)); if (unlikely(p == NULL)) { exit(EXIT_FAILURE); } memset(p, 0, sizeof(AppLayerProtoDetectProbingParserElement)); SCReturnPtr(p, "AppLayerProtoDetectProbingParserElement"); } static void AppLayerProtoDetectProbingParserElementFree(AppLayerProtoDetectProbingParserElement *p) { SCEnter(); SCFree(p); SCReturn; } static AppLayerProtoDetectProbingParserPort *AppLayerProtoDetectProbingParserPortAlloc(void) { SCEnter(); AppLayerProtoDetectProbingParserPort *p = SCMalloc(sizeof(AppLayerProtoDetectProbingParserPort)); if (unlikely(p == NULL)) { exit(EXIT_FAILURE); } memset(p, 0, sizeof(AppLayerProtoDetectProbingParserPort)); SCReturnPtr(p, "AppLayerProtoDetectProbingParserPort"); } static void AppLayerProtoDetectProbingParserPortFree(AppLayerProtoDetectProbingParserPort *p) { SCEnter(); AppLayerProtoDetectProbingParserElement *e; e = p->dp; while (e != NULL) { AppLayerProtoDetectProbingParserElement *e_next = e->next; AppLayerProtoDetectProbingParserElementFree(e); e = e_next; } e = p->sp; while (e != NULL) { AppLayerProtoDetectProbingParserElement *e_next = e->next; AppLayerProtoDetectProbingParserElementFree(e); e = e_next; } SCFree(p); SCReturn; } static AppLayerProtoDetectProbingParser *AppLayerProtoDetectProbingParserAlloc(void) { SCEnter(); AppLayerProtoDetectProbingParser *p = SCMalloc(sizeof(AppLayerProtoDetectProbingParser)); if (unlikely(p == NULL)) { exit(EXIT_FAILURE); } memset(p, 0, sizeof(AppLayerProtoDetectProbingParser)); SCReturnPtr(p, "AppLayerProtoDetectProbingParser"); } static void AppLayerProtoDetectProbingParserFree(AppLayerProtoDetectProbingParser *p) { SCEnter(); AppLayerProtoDetectProbingParserPort *pt = p->port; while (pt != NULL) { AppLayerProtoDetectProbingParserPort *pt_next = pt->next; AppLayerProtoDetectProbingParserPortFree(pt); pt = pt_next; } SCFree(p); SCReturn; } static AppLayerProtoDetectProbingParserElement * AppLayerProtoDetectProbingParserElementCreate(AppProto alproto, uint16_t port, uint16_t min_depth, uint16_t max_depth) { AppLayerProtoDetectProbingParserElement *pe = AppLayerProtoDetectProbingParserElementAlloc(); pe->alproto = alproto; pe->port = port; pe->alproto_mask = AppLayerProtoDetectProbingParserGetMask(alproto); pe->min_depth = min_depth; pe->max_depth = max_depth; pe->next = NULL; if (max_depth != 0 && min_depth >= max_depth) { SCLogError(SC_ERR_ALPARSER, "Invalid arguments sent to " "register the probing parser. min_depth >= max_depth"); goto error; } if (alproto <= ALPROTO_UNKNOWN || alproto >= ALPROTO_MAX) { SCLogError(SC_ERR_ALPARSER, "Invalid arguments sent to register " "the probing parser. Invalid alproto - %d", alproto); goto error; } SCReturnPtr(pe, "AppLayerProtoDetectProbingParserElement"); error: AppLayerProtoDetectProbingParserElementFree(pe); SCReturnPtr(NULL, "AppLayerProtoDetectProbingParserElement"); } static AppLayerProtoDetectProbingParserElement * AppLayerProtoDetectProbingParserElementDuplicate(AppLayerProtoDetectProbingParserElement *pe) { SCEnter(); AppLayerProtoDetectProbingParserElement *new_pe = AppLayerProtoDetectProbingParserElementAlloc(); new_pe->alproto = pe->alproto; new_pe->port = pe->port; new_pe->alproto_mask = pe->alproto_mask; new_pe->min_depth = pe->min_depth; new_pe->max_depth = pe->max_depth; new_pe->ProbingParserTs = pe->ProbingParserTs; new_pe->ProbingParserTc = pe->ProbingParserTc; new_pe->next = NULL; SCReturnPtr(new_pe, "AppLayerProtoDetectProbingParserElement"); } #ifdef DEBUG static void AppLayerProtoDetectPrintProbingParsers(AppLayerProtoDetectProbingParser *pp) { SCEnter(); AppLayerProtoDetectProbingParserPort *pp_port = NULL; AppLayerProtoDetectProbingParserElement *pp_pe = NULL; printf("\nProtocol Detection Configuration\n"); for ( ; pp != NULL; pp = pp->next) { /* print ip protocol */ if (pp->ipproto == IPPROTO_TCP) printf("IPProto: TCP\n"); else if (pp->ipproto == IPPROTO_UDP) printf("IPProto: UDP\n"); else printf("IPProto: %"PRIu8"\n", pp->ipproto); pp_port = pp->port; for ( ; pp_port != NULL; pp_port = pp_port->next) { if (pp_port->dp != NULL) { printf(" Port: %"PRIu16 "\n", pp_port->port); printf(" Destination port: (max-depth: %"PRIu16 ", " "mask - %"PRIu32")\n", pp_port->dp_max_depth, pp_port->alproto_mask); pp_pe = pp_port->dp; for ( ; pp_pe != NULL; pp_pe = pp_pe->next) { if (pp_pe->alproto == ALPROTO_HTTP) printf(" alproto: ALPROTO_HTTP\n"); else if (pp_pe->alproto == ALPROTO_FTP) printf(" alproto: ALPROTO_FTP\n"); else if (pp_pe->alproto == ALPROTO_FTPDATA) printf(" alproto: ALPROTO_FTPDATA\n"); else if (pp_pe->alproto == ALPROTO_SMTP) printf(" alproto: ALPROTO_SMTP\n"); else if (pp_pe->alproto == ALPROTO_TLS) printf(" alproto: ALPROTO_TLS\n"); else if (pp_pe->alproto == ALPROTO_SSH) printf(" alproto: ALPROTO_SSH\n"); else if (pp_pe->alproto == ALPROTO_IMAP) printf(" alproto: ALPROTO_IMAP\n"); else if (pp_pe->alproto == ALPROTO_MSN) printf(" alproto: ALPROTO_MSN\n"); else if (pp_pe->alproto == ALPROTO_JABBER) printf(" alproto: ALPROTO_JABBER\n"); else if (pp_pe->alproto == ALPROTO_SMB) printf(" alproto: ALPROTO_SMB\n"); else if (pp_pe->alproto == ALPROTO_SMB2) printf(" alproto: ALPROTO_SMB2\n"); else if (pp_pe->alproto == ALPROTO_DCERPC) printf(" alproto: ALPROTO_DCERPC\n"); else if (pp_pe->alproto == ALPROTO_IRC) printf(" alproto: ALPROTO_IRC\n"); else if (pp_pe->alproto == ALPROTO_DNS) printf(" alproto: ALPROTO_DNS\n"); else if (pp_pe->alproto == ALPROTO_MODBUS) printf(" alproto: ALPROTO_MODBUS\n"); else if (pp_pe->alproto == ALPROTO_ENIP) printf(" alproto: ALPROTO_ENIP\n"); else if (pp_pe->alproto == ALPROTO_NFS) printf(" alproto: ALPROTO_NFS\n"); else if (pp_pe->alproto == ALPROTO_NTP) printf(" alproto: ALPROTO_NTP\n"); else if (pp_pe->alproto == ALPROTO_TFTP) printf(" alproto: ALPROTO_TFTP\n"); else if (pp_pe->alproto == ALPROTO_IKEV2) printf(" alproto: ALPROTO_IKEV2\n"); else if (pp_pe->alproto == ALPROTO_KRB5) printf(" alproto: ALPROTO_KRB5\n"); else if (pp_pe->alproto == ALPROTO_DHCP) printf(" alproto: ALPROTO_DHCP\n"); else if (pp_pe->alproto == ALPROTO_TEMPLATE_RUST) printf(" alproto: ALPROTO_TEMPLATE_RUST\n"); else if (pp_pe->alproto == ALPROTO_TEMPLATE) printf(" alproto: ALPROTO_TEMPLATE\n"); else if (pp_pe->alproto == ALPROTO_DNP3) printf(" alproto: ALPROTO_DNP3\n"); else printf("impossible\n"); printf(" port: %"PRIu16 "\n", pp_pe->port); printf(" mask: %"PRIu32 "\n", pp_pe->alproto_mask); printf(" min_depth: %"PRIu32 "\n", pp_pe->min_depth); printf(" max_depth: %"PRIu32 "\n", pp_pe->max_depth); printf("\n"); } } if (pp_port->sp == NULL) { continue; } printf(" Source port: (max-depth: %"PRIu16 ", " "mask - %"PRIu32")\n", pp_port->sp_max_depth, pp_port->alproto_mask); pp_pe = pp_port->sp; for ( ; pp_pe != NULL; pp_pe = pp_pe->next) { if (pp_pe->alproto == ALPROTO_HTTP) printf(" alproto: ALPROTO_HTTP\n"); else if (pp_pe->alproto == ALPROTO_FTP) printf(" alproto: ALPROTO_FTP\n"); else if (pp_pe->alproto == ALPROTO_FTPDATA) printf(" alproto: ALPROTO_FTPDATA\n"); else if (pp_pe->alproto == ALPROTO_SMTP) printf(" alproto: ALPROTO_SMTP\n"); else if (pp_pe->alproto == ALPROTO_TLS) printf(" alproto: ALPROTO_TLS\n"); else if (pp_pe->alproto == ALPROTO_SSH) printf(" alproto: ALPROTO_SSH\n"); else if (pp_pe->alproto == ALPROTO_IMAP) printf(" alproto: ALPROTO_IMAP\n"); else if (pp_pe->alproto == ALPROTO_MSN) printf(" alproto: ALPROTO_MSN\n"); else if (pp_pe->alproto == ALPROTO_JABBER) printf(" alproto: ALPROTO_JABBER\n"); else if (pp_pe->alproto == ALPROTO_SMB) printf(" alproto: ALPROTO_SMB\n"); else if (pp_pe->alproto == ALPROTO_SMB2) printf(" alproto: ALPROTO_SMB2\n"); else if (pp_pe->alproto == ALPROTO_DCERPC) printf(" alproto: ALPROTO_DCERPC\n"); else if (pp_pe->alproto == ALPROTO_IRC) printf(" alproto: ALPROTO_IRC\n"); else if (pp_pe->alproto == ALPROTO_DNS) printf(" alproto: ALPROTO_DNS\n"); else if (pp_pe->alproto == ALPROTO_MODBUS) printf(" alproto: ALPROTO_MODBUS\n"); else if (pp_pe->alproto == ALPROTO_ENIP) printf(" alproto: ALPROTO_ENIP\n"); else if (pp_pe->alproto == ALPROTO_NFS) printf(" alproto: ALPROTO_NFS\n"); else if (pp_pe->alproto == ALPROTO_NTP) printf(" alproto: ALPROTO_NTP\n"); else if (pp_pe->alproto == ALPROTO_TFTP) printf(" alproto: ALPROTO_TFTP\n"); else if (pp_pe->alproto == ALPROTO_IKEV2) printf(" alproto: ALPROTO_IKEV2\n"); else if (pp_pe->alproto == ALPROTO_KRB5) printf(" alproto: ALPROTO_KRB5\n"); else if (pp_pe->alproto == ALPROTO_DHCP) printf(" alproto: ALPROTO_DHCP\n"); else if (pp_pe->alproto == ALPROTO_TEMPLATE_RUST) printf(" alproto: ALPROTO_TEMPLATE_RUST\n"); else if (pp_pe->alproto == ALPROTO_TEMPLATE) printf(" alproto: ALPROTO_TEMPLATE\n"); else if (pp_pe->alproto == ALPROTO_DNP3) printf(" alproto: ALPROTO_DNP3\n"); else printf("impossible\n"); printf(" port: %"PRIu16 "\n", pp_pe->port); printf(" mask: %"PRIu32 "\n", pp_pe->alproto_mask); printf(" min_depth: %"PRIu32 "\n", pp_pe->min_depth); printf(" max_depth: %"PRIu32 "\n", pp_pe->max_depth); printf("\n"); } } } SCReturn; } #endif static void AppLayerProtoDetectProbingParserElementAppend(AppLayerProtoDetectProbingParserElement **head_pe, AppLayerProtoDetectProbingParserElement *new_pe) { SCEnter(); if (*head_pe == NULL) { *head_pe = new_pe; goto end; } if ((*head_pe)->port == 0) { if (new_pe->port != 0) { new_pe->next = *head_pe; *head_pe = new_pe; } else { AppLayerProtoDetectProbingParserElement *temp_pe = *head_pe; while (temp_pe->next != NULL) temp_pe = temp_pe->next; temp_pe->next = new_pe; } } else { AppLayerProtoDetectProbingParserElement *temp_pe = *head_pe; if (new_pe->port == 0) { while (temp_pe->next != NULL) temp_pe = temp_pe->next; temp_pe->next = new_pe; } else { while (temp_pe->next != NULL && temp_pe->next->port != 0) temp_pe = temp_pe->next; new_pe->next = temp_pe->next; temp_pe->next = new_pe; } } end: SCReturn; } static void AppLayerProtoDetectProbingParserAppend(AppLayerProtoDetectProbingParser **head_pp, AppLayerProtoDetectProbingParser *new_pp) { SCEnter(); if (*head_pp == NULL) { *head_pp = new_pp; goto end; } AppLayerProtoDetectProbingParser *temp_pp = *head_pp; while (temp_pp->next != NULL) temp_pp = temp_pp->next; temp_pp->next = new_pp; end: SCReturn; } static void AppLayerProtoDetectProbingParserPortAppend(AppLayerProtoDetectProbingParserPort **head_port, AppLayerProtoDetectProbingParserPort *new_port) { SCEnter(); if (*head_port == NULL) { *head_port = new_port; goto end; } if ((*head_port)->port == 0) { new_port->next = *head_port; *head_port = new_port; } else { AppLayerProtoDetectProbingParserPort *temp_port = *head_port; while (temp_port->next != NULL && temp_port->next->port != 0) { temp_port = temp_port->next; } new_port->next = temp_port->next; temp_port->next = new_port; } end: SCReturn; } static void AppLayerProtoDetectInsertNewProbingParser(AppLayerProtoDetectProbingParser **pp, uint8_t ipproto, uint16_t port, AppProto alproto, uint16_t min_depth, uint16_t max_depth, uint8_t direction, ProbingParserFPtr ProbingParser1, ProbingParserFPtr ProbingParser2) { SCEnter(); /* get the top level ipproto pp */ AppLayerProtoDetectProbingParser *curr_pp = *pp; while (curr_pp != NULL) { if (curr_pp->ipproto == ipproto) break; curr_pp = curr_pp->next; } if (curr_pp == NULL) { AppLayerProtoDetectProbingParser *new_pp = AppLayerProtoDetectProbingParserAlloc(); new_pp->ipproto = ipproto; AppLayerProtoDetectProbingParserAppend(pp, new_pp); curr_pp = new_pp; } /* get the top level port pp */ AppLayerProtoDetectProbingParserPort *curr_port = curr_pp->port; while (curr_port != NULL) { if (curr_port->port == port) break; curr_port = curr_port->next; } if (curr_port == NULL) { AppLayerProtoDetectProbingParserPort *new_port = AppLayerProtoDetectProbingParserPortAlloc(); new_port->port = port; AppLayerProtoDetectProbingParserPortAppend(&curr_pp->port, new_port); curr_port = new_port; if (direction & STREAM_TOSERVER) { curr_port->dp_max_depth = max_depth; } else { curr_port->sp_max_depth = max_depth; } AppLayerProtoDetectProbingParserPort *zero_port; zero_port = curr_pp->port; while (zero_port != NULL && zero_port->port != 0) { zero_port = zero_port->next; } if (zero_port != NULL) { AppLayerProtoDetectProbingParserElement *zero_pe; zero_pe = zero_port->dp; for ( ; zero_pe != NULL; zero_pe = zero_pe->next) { if (curr_port->dp == NULL) curr_port->dp_max_depth = zero_pe->max_depth; if (zero_pe->max_depth == 0) curr_port->dp_max_depth = zero_pe->max_depth; if (curr_port->dp_max_depth != 0 && curr_port->dp_max_depth < zero_pe->max_depth) { curr_port->dp_max_depth = zero_pe->max_depth; } AppLayerProtoDetectProbingParserElement *dup_pe = AppLayerProtoDetectProbingParserElementDuplicate(zero_pe); AppLayerProtoDetectProbingParserElementAppend(&curr_port->dp, dup_pe); curr_port->alproto_mask |= dup_pe->alproto_mask; } zero_pe = zero_port->sp; for ( ; zero_pe != NULL; zero_pe = zero_pe->next) { if (curr_port->sp == NULL) curr_port->sp_max_depth = zero_pe->max_depth; if (zero_pe->max_depth == 0) curr_port->sp_max_depth = zero_pe->max_depth; if (curr_port->sp_max_depth != 0 && curr_port->sp_max_depth < zero_pe->max_depth) { curr_port->sp_max_depth = zero_pe->max_depth; } AppLayerProtoDetectProbingParserElement *dup_pe = AppLayerProtoDetectProbingParserElementDuplicate(zero_pe); AppLayerProtoDetectProbingParserElementAppend(&curr_port->sp, dup_pe); curr_port->alproto_mask |= dup_pe->alproto_mask; } } /* if (zero_port != NULL) */ } /* if (curr_port == NULL) */ /* insert the pe_pp */ AppLayerProtoDetectProbingParserElement *curr_pe; if (direction & STREAM_TOSERVER) curr_pe = curr_port->dp; else curr_pe = curr_port->sp; while (curr_pe != NULL) { if (curr_pe->alproto == alproto) { SCLogError(SC_ERR_ALPARSER, "Duplicate pp registered - " "ipproto - %"PRIu8" Port - %"PRIu16" " "App Protocol - NULL, App Protocol(ID) - " "%"PRIu16" min_depth - %"PRIu16" " "max_dept - %"PRIu16".", ipproto, port, alproto, min_depth, max_depth); goto error; } curr_pe = curr_pe->next; } /* Get a new parser element */ AppLayerProtoDetectProbingParserElement *new_pe = AppLayerProtoDetectProbingParserElementCreate(alproto, curr_port->port, min_depth, max_depth); if (new_pe == NULL) goto error; curr_pe = new_pe; AppLayerProtoDetectProbingParserElement **head_pe; if (direction & STREAM_TOSERVER) { curr_pe->ProbingParserTs = ProbingParser1; curr_pe->ProbingParserTc = ProbingParser2; if (curr_port->dp == NULL) curr_port->dp_max_depth = new_pe->max_depth; if (new_pe->max_depth == 0) curr_port->dp_max_depth = new_pe->max_depth; if (curr_port->dp_max_depth != 0 && curr_port->dp_max_depth < new_pe->max_depth) { curr_port->dp_max_depth = new_pe->max_depth; } curr_port->alproto_mask |= new_pe->alproto_mask; head_pe = &curr_port->dp; } else { curr_pe->ProbingParserTs = ProbingParser2; curr_pe->ProbingParserTc = ProbingParser1; if (curr_port->sp == NULL) curr_port->sp_max_depth = new_pe->max_depth; if (new_pe->max_depth == 0) curr_port->sp_max_depth = new_pe->max_depth; if (curr_port->sp_max_depth != 0 && curr_port->sp_max_depth < new_pe->max_depth) { curr_port->sp_max_depth = new_pe->max_depth; } curr_port->alproto_mask |= new_pe->alproto_mask; head_pe = &curr_port->sp; } AppLayerProtoDetectProbingParserElementAppend(head_pe, new_pe); if (curr_port->port == 0) { AppLayerProtoDetectProbingParserPort *temp_port = curr_pp->port; while (temp_port != NULL && temp_port->port != 0) { if (direction & STREAM_TOSERVER) { if (temp_port->dp == NULL) temp_port->dp_max_depth = curr_pe->max_depth; if (curr_pe->max_depth == 0) temp_port->dp_max_depth = curr_pe->max_depth; if (temp_port->dp_max_depth != 0 && temp_port->dp_max_depth < curr_pe->max_depth) { temp_port->dp_max_depth = curr_pe->max_depth; } AppLayerProtoDetectProbingParserElementAppend(&temp_port->dp, AppLayerProtoDetectProbingParserElementDuplicate(curr_pe)); temp_port->alproto_mask |= curr_pe->alproto_mask; } else { if (temp_port->sp == NULL) temp_port->sp_max_depth = curr_pe->max_depth; if (curr_pe->max_depth == 0) temp_port->sp_max_depth = curr_pe->max_depth; if (temp_port->sp_max_depth != 0 && temp_port->sp_max_depth < curr_pe->max_depth) { temp_port->sp_max_depth = curr_pe->max_depth; } AppLayerProtoDetectProbingParserElementAppend(&temp_port->sp, AppLayerProtoDetectProbingParserElementDuplicate(curr_pe)); temp_port->alproto_mask |= curr_pe->alproto_mask; } temp_port = temp_port->next; } /* while */ } /* if */ error: SCReturn; } /***** Static Internal Calls: PM registration *****/ static void AppLayerProtoDetectPMGetIpprotos(AppProto alproto, uint8_t *ipprotos) { SCEnter(); const AppLayerProtoDetectPMSignature *s = NULL; int i, j; uint8_t ipproto; for (i = 0; i < FLOW_PROTO_DEFAULT; i++) { ipproto = FlowGetReverseProtoMapping(i); for (j = 0; j < 2; j++) { AppLayerProtoDetectPMCtx *pm_ctx = &alpd_ctx.ctx_ipp[i].ctx_pm[j]; SigIntId x; for (x = 0; x < pm_ctx->max_sig_id;x++) { s = pm_ctx->map[x]; if (s->alproto == alproto) ipprotos[ipproto / 8] |= 1 << (ipproto % 8); } } } SCReturn; } static int AppLayerProtoDetectPMSetContentIDs(AppLayerProtoDetectPMCtx *ctx) { SCEnter(); typedef struct TempContainer_ { PatIntId id; uint16_t content_len; uint8_t *content; } TempContainer; AppLayerProtoDetectPMSignature *s = NULL; uint32_t struct_total_size = 0; uint32_t content_total_size = 0; /* array hash buffer */ uint8_t *ahb = NULL; uint8_t *content = NULL; uint8_t content_len = 0; PatIntId max_id = 0; TempContainer *struct_offset = NULL; uint8_t *content_offset = NULL; int ret = 0; if (ctx->head == NULL) goto end; for (s = ctx->head; s != NULL; s = s->next) { struct_total_size += sizeof(TempContainer); content_total_size += s->cd->content_len; ctx->max_sig_id++; } ahb = SCMalloc(sizeof(uint8_t) * (struct_total_size + content_total_size)); if (unlikely(ahb == NULL)) goto error; struct_offset = (TempContainer *)ahb; content_offset = ahb + struct_total_size; for (s = ctx->head; s != NULL; s = s->next) { TempContainer *tcdup = (TempContainer *)ahb; content = s->cd->content; content_len = s->cd->content_len; for (; tcdup != struct_offset; tcdup++) { if (tcdup->content_len != content_len || SCMemcmp(tcdup->content, content, tcdup->content_len) != 0) { continue; } break; } if (tcdup != struct_offset) { s->cd->id = tcdup->id; continue; } struct_offset->content_len = content_len; struct_offset->content = content_offset; content_offset += content_len; memcpy(struct_offset->content, content, content_len); struct_offset->id = max_id++; s->cd->id = struct_offset->id; struct_offset++; } ctx->max_pat_id = max_id; goto end; error: ret = -1; end: if (ahb != NULL) SCFree(ahb); SCReturnInt(ret); } static int AppLayerProtoDetectPMMapSignatures(AppLayerProtoDetectPMCtx *ctx) { SCEnter(); int ret = 0; AppLayerProtoDetectPMSignature *s, *next_s; int mpm_ret; SigIntId id = 0; ctx->map = SCMalloc(ctx->max_sig_id * sizeof(AppLayerProtoDetectPMSignature *)); if (ctx->map == NULL) goto error; memset(ctx->map, 0, ctx->max_sig_id * sizeof(AppLayerProtoDetectPMSignature *)); /* add an array indexed by rule id to look up the sig */ for (s = ctx->head; s != NULL; ) { next_s = s->next; s->id = id++; SCLogDebug("s->id %u", s->id); if (s->cd->flags & DETECT_CONTENT_NOCASE) { mpm_ret = MpmAddPatternCI(&ctx->mpm_ctx, s->cd->content, s->cd->content_len, 0, 0, s->cd->id, s->id, 0); if (mpm_ret < 0) goto error; } else { mpm_ret = MpmAddPatternCS(&ctx->mpm_ctx, s->cd->content, s->cd->content_len, 0, 0, s->cd->id, s->id, 0); if (mpm_ret < 0) goto error; } ctx->map[s->id] = s; s->next = NULL; s = next_s; } ctx->head = NULL; goto end; error: ret = -1; end: SCReturnInt(ret); } static int AppLayerProtoDetectPMPrepareMpm(AppLayerProtoDetectPMCtx *ctx) { SCEnter(); int ret = 0; MpmCtx *mpm_ctx = &ctx->mpm_ctx; if (mpm_table[mpm_ctx->mpm_type].Prepare(mpm_ctx) < 0) goto error; goto end; error: ret = -1; end: SCReturnInt(ret); } static void AppLayerProtoDetectPMFreeSignature(AppLayerProtoDetectPMSignature *sig) { SCEnter(); if (sig == NULL) SCReturn; if (sig->cd) DetectContentFree(sig->cd); SCFree(sig); SCReturn; } static int AppLayerProtoDetectPMAddSignature(AppLayerProtoDetectPMCtx *ctx, DetectContentData *cd, AppProto alproto) { SCEnter(); int ret = 0; AppLayerProtoDetectPMSignature *s = SCMalloc(sizeof(*s)); if (unlikely(s == NULL)) goto error; memset(s, 0, sizeof(*s)); s->alproto = alproto; s->cd = cd; /* prepend to the list */ s->next = ctx->head; ctx->head = s; goto end; error: ret = -1; end: SCReturnInt(ret); } static int AppLayerProtoDetectPMRegisterPattern(uint8_t ipproto, AppProto alproto, const char *pattern, uint16_t depth, uint16_t offset, uint8_t direction, uint8_t is_cs) { SCEnter(); AppLayerProtoDetectCtxIpproto *ctx_ipp = &alpd_ctx.ctx_ipp[FlowGetProtoMapping(ipproto)]; AppLayerProtoDetectPMCtx *ctx_pm = NULL; DetectContentData *cd; int ret = 0; cd = DetectContentParseEncloseQuotes(alpd_ctx.spm_global_thread_ctx, pattern); if (cd == NULL) goto error; cd->depth = depth; cd->offset = offset; if (!is_cs) { /* Rebuild as nocase */ SpmDestroyCtx(cd->spm_ctx); cd->spm_ctx = SpmInitCtx(cd->content, cd->content_len, 1, alpd_ctx.spm_global_thread_ctx); if (cd->spm_ctx == NULL) { goto error; } cd->flags |= DETECT_CONTENT_NOCASE; } if (depth < cd->content_len) goto error; if (direction & STREAM_TOSERVER) ctx_pm = (AppLayerProtoDetectPMCtx *)&ctx_ipp->ctx_pm[0]; else ctx_pm = (AppLayerProtoDetectPMCtx *)&ctx_ipp->ctx_pm[1]; if (depth > ctx_pm->max_len) ctx_pm->max_len = depth; if (depth < ctx_pm->min_len) ctx_pm->min_len = depth; /* Finally turn it into a signature and add to the ctx. */ AppLayerProtoDetectPMAddSignature(ctx_pm, cd, alproto); goto end; error: ret = -1; end: SCReturnInt(ret); } /***** Protocol Retrieval *****/ AppProto AppLayerProtoDetectGetProto(AppLayerProtoDetectThreadCtx *tctx, Flow *f, uint8_t *buf, uint32_t buflen, uint8_t ipproto, uint8_t direction) { SCEnter(); SCLogDebug("buflen %u for %s direction", buflen, (direction & STREAM_TOSERVER) ? "toserver" : "toclient"); AppProto alproto = ALPROTO_UNKNOWN; AppProto pm_alproto = ALPROTO_UNKNOWN; if (!FLOW_IS_PM_DONE(f, direction)) { AppProto pm_results[ALPROTO_MAX]; uint16_t pm_matches = AppLayerProtoDetectPMGetProto(tctx, f, buf, buflen, direction, ipproto, pm_results); if (pm_matches > 0) { alproto = pm_results[0]; /* HACK: if detected protocol is dcerpc/udp, we run PP as well * to avoid misdetecting DNS as DCERPC. */ if (!(ipproto == IPPROTO_UDP && alproto == ALPROTO_DCERPC)) goto end; pm_alproto = alproto; /* fall through */ } } if (!FLOW_IS_PP_DONE(f, direction)) { alproto = AppLayerProtoDetectPPGetProto(f, buf, buflen, ipproto, direction); if (alproto != ALPROTO_UNKNOWN) goto end; } /* Look if flow can be found in expectation list */ if (!FLOW_IS_PE_DONE(f, direction)) { alproto = AppLayerProtoDetectPEGetProto(f, ipproto, direction); } end: if (alproto == ALPROTO_UNKNOWN) alproto = pm_alproto; SCReturnUInt(alproto); } static void AppLayerProtoDetectFreeProbingParsers(AppLayerProtoDetectProbingParser *pp) { SCEnter(); AppLayerProtoDetectProbingParser *tmp_pp = NULL; if (pp == NULL) goto end; while (pp != NULL) { tmp_pp = pp->next; AppLayerProtoDetectProbingParserFree(pp); pp = tmp_pp; } end: SCReturn; } /***** State Preparation *****/ int AppLayerProtoDetectPrepareState(void) { SCEnter(); AppLayerProtoDetectPMCtx *ctx_pm; int i, j; int ret = 0; for (i = 0; i < FLOW_PROTO_DEFAULT; i++) { for (j = 0; j < 2; j++) { ctx_pm = &alpd_ctx.ctx_ipp[i].ctx_pm[j]; if (AppLayerProtoDetectPMSetContentIDs(ctx_pm) < 0) goto error; if (ctx_pm->max_sig_id == 0) continue; if (AppLayerProtoDetectPMMapSignatures(ctx_pm) < 0) goto error; if (AppLayerProtoDetectPMPrepareMpm(ctx_pm) < 0) goto error; } } #ifdef DEBUG if (SCLogDebugEnabled()) { AppLayerProtoDetectPrintProbingParsers(alpd_ctx.ctx_pp); } #endif goto end; error: ret = -1; end: SCReturnInt(ret); } /***** PP registration *****/ /** \brief register parser at a port * * \param direction STREAM_TOSERVER or STREAM_TOCLIENT for dp or sp */ void AppLayerProtoDetectPPRegister(uint8_t ipproto, const char *portstr, AppProto alproto, uint16_t min_depth, uint16_t max_depth, uint8_t direction, ProbingParserFPtr ProbingParser1, ProbingParserFPtr ProbingParser2) { SCEnter(); DetectPort *head = NULL; DetectPortParse(NULL,&head, portstr); DetectPort *temp_dp = head; while (temp_dp != NULL) { uint32_t port = temp_dp->port; if (port == 0 && temp_dp->port2 != 0) port++; for ( ; port <= temp_dp->port2; port++) { AppLayerProtoDetectInsertNewProbingParser(&alpd_ctx.ctx_pp, ipproto, port, alproto, min_depth, max_depth, direction, ProbingParser1, ProbingParser2); } temp_dp = temp_dp->next; } DetectPortCleanupList(NULL,head); SCReturn; } int AppLayerProtoDetectPPParseConfPorts(const char *ipproto_name, uint8_t ipproto, const char *alproto_name, AppProto alproto, uint16_t min_depth, uint16_t max_depth, ProbingParserFPtr ProbingParserTs, ProbingParserFPtr ProbingParserTc) { SCEnter(); char param[100]; int r; ConfNode *node; ConfNode *port_node = NULL; int config = 0; r = snprintf(param, sizeof(param), "%s%s%s", "app-layer.protocols.", alproto_name, ".detection-ports"); if (r < 0) { SCLogError(SC_ERR_FATAL, "snprintf failure."); exit(EXIT_FAILURE); } else if (r > (int)sizeof(param)) { SCLogError(SC_ERR_FATAL, "buffer not big enough to write param."); exit(EXIT_FAILURE); } node = ConfGetNode(param); if (node == NULL) { SCLogDebug("Entry for %s not found.", param); r = snprintf(param, sizeof(param), "%s%s%s%s%s", "app-layer.protocols.", alproto_name, ".", ipproto_name, ".detection-ports"); if (r < 0) { SCLogError(SC_ERR_FATAL, "snprintf failure."); exit(EXIT_FAILURE); } else if (r > (int)sizeof(param)) { SCLogError(SC_ERR_FATAL, "buffer not big enough to write param."); exit(EXIT_FAILURE); } node = ConfGetNode(param); if (node == NULL) goto end; } /* detect by destination port of the flow (e.g. port 53 for DNS) */ port_node = ConfNodeLookupChild(node, "dp"); if (port_node == NULL) port_node = ConfNodeLookupChild(node, "toserver"); if (port_node != NULL && port_node->val != NULL) { AppLayerProtoDetectPPRegister(ipproto, port_node->val, alproto, min_depth, max_depth, STREAM_TOSERVER, /* to indicate dp */ ProbingParserTs, ProbingParserTc); } /* detect by source port of flow */ port_node = ConfNodeLookupChild(node, "sp"); if (port_node == NULL) port_node = ConfNodeLookupChild(node, "toclient"); if (port_node != NULL && port_node->val != NULL) { AppLayerProtoDetectPPRegister(ipproto, port_node->val, alproto, min_depth, max_depth, STREAM_TOCLIENT, /* to indicate sp */ ProbingParserTc, ProbingParserTs); } config = 1; end: SCReturnInt(config); } /***** PM registration *****/ int AppLayerProtoDetectPMRegisterPatternCS(uint8_t ipproto, AppProto alproto, const char *pattern, uint16_t depth, uint16_t offset, uint8_t direction) { SCEnter(); int r = 0; r = AppLayerProtoDetectPMRegisterPattern(ipproto, alproto, pattern, depth, offset, direction, 1 /* case-sensitive */); SCReturnInt(r); } int AppLayerProtoDetectPMRegisterPatternCI(uint8_t ipproto, AppProto alproto, const char *pattern, uint16_t depth, uint16_t offset, uint8_t direction) { SCEnter(); int r = 0; r = AppLayerProtoDetectPMRegisterPattern(ipproto, alproto, pattern, depth, offset, direction, 0 /* !case-sensitive */); SCReturnInt(r); } /***** Setup/General Registration *****/ int AppLayerProtoDetectSetup(void) { SCEnter(); int i, j; memset(&alpd_ctx, 0, sizeof(alpd_ctx)); uint16_t spm_matcher = SinglePatternMatchDefaultMatcher(); uint16_t mpm_matcher = PatternMatchDefaultMatcher(); alpd_ctx.spm_global_thread_ctx = SpmInitGlobalThreadCtx(spm_matcher); if (alpd_ctx.spm_global_thread_ctx == NULL) { SCLogError(SC_ERR_FATAL, "Unable to alloc SpmGlobalThreadCtx."); exit(EXIT_FAILURE); } for (i = 0; i < FLOW_PROTO_DEFAULT; i++) { for (j = 0; j < 2; j++) { MpmInitCtx(&alpd_ctx.ctx_ipp[i].ctx_pm[j].mpm_ctx, mpm_matcher); } } AppLayerExpectationSetup(); SCReturnInt(0); } /** * \todo incomplete. Need more work. */ int AppLayerProtoDetectDeSetup(void) { SCEnter(); int ipproto_map = 0; int dir = 0; PatIntId id = 0; AppLayerProtoDetectPMCtx *pm_ctx = NULL; AppLayerProtoDetectPMSignature *sig = NULL; for (ipproto_map = 0; ipproto_map < FLOW_PROTO_DEFAULT; ipproto_map++) { for (dir = 0; dir < 2; dir++) { pm_ctx = &alpd_ctx.ctx_ipp[ipproto_map].ctx_pm[dir]; mpm_table[pm_ctx->mpm_ctx.mpm_type].DestroyCtx(&pm_ctx->mpm_ctx); for (id = 0; id < pm_ctx->max_sig_id; id++) { sig = pm_ctx->map[id]; AppLayerProtoDetectPMFreeSignature(sig); } } } SpmDestroyGlobalThreadCtx(alpd_ctx.spm_global_thread_ctx); AppLayerProtoDetectFreeProbingParsers(alpd_ctx.ctx_pp); SCReturnInt(0); } void AppLayerProtoDetectRegisterProtocol(AppProto alproto, const char *alproto_name) { SCEnter(); if (alpd_ctx.alproto_names[alproto] == NULL) alpd_ctx.alproto_names[alproto] = alproto_name; SCReturn; } /** \brief request applayer to wrap up this protocol and rerun protocol * detection. * * When this is called, the old session is reset unconditionally. A * 'detect/log' flush packet is generated for both direction before * the reset, so allow for final detection and logging. * * \param f flow to act on * \param dp destination port to use in protocol detection. Set to 443 * for start tls, set to the HTTP uri port for CONNECT and * set to 0 to not use it. * \param expect_proto expected protocol. AppLayer event will be set if * detected protocol differs from this. */ void AppLayerRequestProtocolChange(Flow *f, uint16_t dp, AppProto expect_proto) { FlowSetChangeProtoFlag(f); f->protodetect_dp = dp; f->alproto_expect = expect_proto; } /** \brief request applayer to wrap up this protocol and rerun protocol * detection with expectation of TLS. Used by STARTTLS. * * Sets detection port to 443 to make port based TLS detection work for * SMTP, FTP etc as well. * * \param f flow to act on */ void AppLayerRequestProtocolTLSUpgrade(Flow *f) { AppLayerRequestProtocolChange(f, 443, ALPROTO_TLS); } void AppLayerProtoDetectReset(Flow *f) { FlowUnsetChangeProtoFlag(f); FLOW_RESET_PM_DONE(f, STREAM_TOSERVER); FLOW_RESET_PM_DONE(f, STREAM_TOCLIENT); FLOW_RESET_PP_DONE(f, STREAM_TOSERVER); FLOW_RESET_PP_DONE(f, STREAM_TOCLIENT); FLOW_RESET_PE_DONE(f, STREAM_TOSERVER); FLOW_RESET_PE_DONE(f, STREAM_TOCLIENT); f->probing_parser_toserver_alproto_masks = 0; f->probing_parser_toclient_alproto_masks = 0; AppLayerParserStateCleanup(f, f->alstate, f->alparser); f->alstate = NULL; f->alparser = NULL; f->alproto = ALPROTO_UNKNOWN; f->alproto_ts = ALPROTO_UNKNOWN; f->alproto_tc = ALPROTO_UNKNOWN; } int AppLayerProtoDetectConfProtoDetectionEnabled(const char *ipproto, const char *alproto) { SCEnter(); BUG_ON(ipproto == NULL || alproto == NULL); int enabled = 1; char param[100]; ConfNode *node; int r; #ifdef AFLFUZZ_APPLAYER goto enabled; #endif if (RunmodeIsUnittests()) goto enabled; r = snprintf(param, sizeof(param), "%s%s%s", "app-layer.protocols.", alproto, ".enabled"); if (r < 0) { SCLogError(SC_ERR_FATAL, "snprintf failure."); exit(EXIT_FAILURE); } else if (r > (int)sizeof(param)) { SCLogError(SC_ERR_FATAL, "buffer not big enough to write param."); exit(EXIT_FAILURE); } node = ConfGetNode(param); if (node == NULL) { SCLogDebug("Entry for %s not found.", param); r = snprintf(param, sizeof(param), "%s%s%s%s%s", "app-layer.protocols.", alproto, ".", ipproto, ".enabled"); if (r < 0) { SCLogError(SC_ERR_FATAL, "snprintf failure."); exit(EXIT_FAILURE); } else if (r > (int)sizeof(param)) { SCLogError(SC_ERR_FATAL, "buffer not big enough to write param."); exit(EXIT_FAILURE); } node = ConfGetNode(param); if (node == NULL) { SCLogDebug("Entry for %s not found.", param); goto enabled; } } if (node->val) { if (ConfValIsTrue(node->val)) { goto enabled; } else if (ConfValIsFalse(node->val)) { goto disabled; } else if (strcasecmp(node->val, "detection-only") == 0) { goto enabled; } } /* Invalid or null value. */ SCLogError(SC_ERR_FATAL, "Invalid value found for %s.", param); exit(EXIT_FAILURE); disabled: enabled = 0; enabled: SCReturnInt(enabled); } AppLayerProtoDetectThreadCtx *AppLayerProtoDetectGetCtxThread(void) { SCEnter(); AppLayerProtoDetectThreadCtx *alpd_tctx = NULL; MpmCtx *mpm_ctx; MpmThreadCtx *mpm_tctx; int i, j; PatIntId max_pat_id = 0; for (i = 0; i < FLOW_PROTO_DEFAULT; i++) { for (j = 0; j < 2; j++) { if (max_pat_id == 0) { max_pat_id = alpd_ctx.ctx_ipp[i].ctx_pm[j].max_pat_id; } else if (alpd_ctx.ctx_ipp[i].ctx_pm[j].max_pat_id && max_pat_id < alpd_ctx.ctx_ipp[i].ctx_pm[j].max_pat_id) { max_pat_id = alpd_ctx.ctx_ipp[i].ctx_pm[j].max_pat_id; } } } alpd_tctx = SCMalloc(sizeof(*alpd_tctx)); if (alpd_tctx == NULL) goto error; memset(alpd_tctx, 0, sizeof(*alpd_tctx)); /* Get the max pat id for all the mpm ctxs. */ if (PmqSetup(&alpd_tctx->pmq) < 0) goto error; for (i = 0; i < FLOW_PROTO_DEFAULT; i++) { for (j = 0; j < 2; j++) { mpm_ctx = &alpd_ctx.ctx_ipp[i].ctx_pm[j].mpm_ctx; mpm_tctx = &alpd_tctx->mpm_tctx[i][j]; mpm_table[mpm_ctx->mpm_type].InitThreadCtx(mpm_ctx, mpm_tctx); } } alpd_tctx->spm_thread_ctx = SpmMakeThreadCtx(alpd_ctx.spm_global_thread_ctx); if (alpd_tctx->spm_thread_ctx == NULL) { goto error; } goto end; error: if (alpd_tctx != NULL) AppLayerProtoDetectDestroyCtxThread(alpd_tctx); alpd_tctx = NULL; end: SCReturnPtr(alpd_tctx, "AppLayerProtoDetectThreadCtx"); } void AppLayerProtoDetectDestroyCtxThread(AppLayerProtoDetectThreadCtx *alpd_tctx) { SCEnter(); MpmCtx *mpm_ctx; MpmThreadCtx *mpm_tctx; int ipproto_map, dir; for (ipproto_map = 0; ipproto_map < FLOW_PROTO_DEFAULT; ipproto_map++) { for (dir = 0; dir < 2; dir++) { mpm_ctx = &alpd_ctx.ctx_ipp[ipproto_map].ctx_pm[dir].mpm_ctx; mpm_tctx = &alpd_tctx->mpm_tctx[ipproto_map][dir]; mpm_table[mpm_ctx->mpm_type].DestroyThreadCtx(mpm_ctx, mpm_tctx); } } PmqFree(&alpd_tctx->pmq); if (alpd_tctx->spm_thread_ctx != NULL) { SpmDestroyThreadCtx(alpd_tctx->spm_thread_ctx); } SCFree(alpd_tctx); SCReturn; } /***** Utility *****/ void AppLayerProtoDetectSupportedIpprotos(AppProto alproto, uint8_t *ipprotos) { SCEnter(); AppLayerProtoDetectPMGetIpprotos(alproto, ipprotos); AppLayerProtoDetectPPGetIpprotos(alproto, ipprotos); AppLayerProtoDetectPEGetIpprotos(alproto, ipprotos); SCReturn; } AppProto AppLayerProtoDetectGetProtoByName(const char *alproto_name) { SCEnter(); AppProto a; for (a = 0; a < ALPROTO_MAX; a++) { if (alpd_ctx.alproto_names[a] != NULL && strlen(alpd_ctx.alproto_names[a]) == strlen(alproto_name) && (SCMemcmp(alpd_ctx.alproto_names[a], alproto_name, strlen(alproto_name)) == 0)) { SCReturnCT(a, "AppProto"); } } SCReturnCT(ALPROTO_UNKNOWN, "AppProto"); } const char *AppLayerProtoDetectGetProtoName(AppProto alproto) { return alpd_ctx.alproto_names[alproto]; } void AppLayerProtoDetectSupportedAppProtocols(AppProto *alprotos) { SCEnter(); memset(alprotos, 0, ALPROTO_MAX * sizeof(AppProto)); int alproto; for (alproto = 0; alproto != ALPROTO_MAX; alproto++) { if (alpd_ctx.alproto_names[alproto] != NULL) alprotos[alproto] = 1; } SCReturn; } uint8_t expectation_proto[ALPROTO_MAX]; static void AppLayerProtoDetectPEGetIpprotos(AppProto alproto, uint8_t *ipprotos) { if (expectation_proto[alproto] == IPPROTO_TCP) { ipprotos[IPPROTO_TCP / 8] |= 1 << (IPPROTO_TCP % 8); } if (expectation_proto[alproto] == IPPROTO_UDP) { ipprotos[IPPROTO_UDP / 8] |= 1 << (IPPROTO_UDP % 8); } } void AppLayerRegisterExpectationProto(uint8_t proto, AppProto alproto) { if (expectation_proto[alproto]) { if (proto != expectation_proto[alproto]) { SCLogError(SC_ERR_NOT_SUPPORTED, "Expectation on 2 IP protocols are not supported"); } } expectation_proto[alproto] = proto; } /***** Unittests *****/ #ifdef UNITTESTS #include "app-layer-htp.h" static AppLayerProtoDetectCtx alpd_ctx_ut; void AppLayerProtoDetectUnittestCtxBackup(void) { SCEnter(); alpd_ctx_ut = alpd_ctx; memset(&alpd_ctx, 0, sizeof(alpd_ctx)); SCReturn; } void AppLayerProtoDetectUnittestCtxRestore(void) { SCEnter(); alpd_ctx = alpd_ctx_ut; memset(&alpd_ctx_ut, 0, sizeof(alpd_ctx_ut)); SCReturn; } static int AppLayerProtoDetectTest01(void) { AppLayerProtoDetectUnittestCtxBackup(); AppLayerProtoDetectSetup(); const char *buf; int r = 0; buf = "HTTP"; AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_HTTP, buf, 4, 0, STREAM_TOCLIENT); buf = "GET"; AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_HTTP, buf, 4, 0, STREAM_TOSERVER); AppLayerProtoDetectPrepareState(); if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].max_pat_id != 1) { printf("Failure - " "alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].max_pat_id != 1\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].max_pat_id != 1) { printf("Failure - " "alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].max_pat_id != 1\n"); goto end; } r = 1; end: AppLayerProtoDetectDeSetup(); AppLayerProtoDetectUnittestCtxRestore(); return r; } static int AppLayerProtoDetectTest02(void) { AppLayerProtoDetectUnittestCtxBackup(); AppLayerProtoDetectSetup(); int r = 0; const char *buf = "HTTP"; AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_HTTP, buf, 4, 0, STREAM_TOCLIENT); buf = "ftp"; AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_FTP, buf, 4, 0, STREAM_TOCLIENT); AppLayerProtoDetectPrepareState(); if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].max_pat_id != 0) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].max_pat_id != 0\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].max_pat_id != 2) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].max_pat_id != 2\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].map != NULL) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].map != NULL\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map == NULL) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map != NULL\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map[0]->alproto != ALPROTO_FTP) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map[0].alproto != ALPROTO_FTP\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map[1]->alproto != ALPROTO_HTTP) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map[1].alproto != ALPROTO_HTTP\n"); goto end; } r = 1; end: AppLayerProtoDetectDeSetup(); AppLayerProtoDetectUnittestCtxRestore(); return r; } static int AppLayerProtoDetectTest03(void) { AppLayerProtoDetectUnittestCtxBackup(); AppLayerProtoDetectSetup(); uint8_t l7data[] = "HTTP/1.1 200 OK\r\nServer: Apache/1.0\r\n\r\n"; const char *buf; int r = 0; Flow f; AppProto pm_results[ALPROTO_MAX]; AppLayerProtoDetectThreadCtx *alpd_tctx; memset(&f, 0x00, sizeof(f)); f.protomap = FlowGetProtoMapping(IPPROTO_TCP); memset(pm_results, 0, sizeof(pm_results)); buf = "HTTP"; AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_HTTP, buf, 4, 0, STREAM_TOCLIENT); buf = "220 "; AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_FTP, buf, 4, 0, STREAM_TOCLIENT); AppLayerProtoDetectPrepareState(); /* AppLayerProtoDetectGetCtxThread() should be called post AppLayerProtoDetectPrepareState(), since * it sets internal structures which depends on the above function. */ alpd_tctx = AppLayerProtoDetectGetCtxThread(); if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].max_pat_id != 0) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].max_pat_id != 0\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].max_pat_id != 2) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].max_pat_id != 2\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].map != NULL) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].map != NULL\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map == NULL) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map != NULL\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map[0]->alproto != ALPROTO_FTP) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map[0].alproto != ALPROTO_FTP\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map[1]->alproto != ALPROTO_HTTP) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map[1].alproto != ALPROTO_HTTP\n"); goto end; } uint32_t cnt = AppLayerProtoDetectPMGetProto(alpd_tctx, &f, l7data, sizeof(l7data), STREAM_TOCLIENT, IPPROTO_TCP, pm_results); if (cnt != 1 && pm_results[0] != ALPROTO_HTTP) { printf("cnt != 1 && pm_results[0] != AlPROTO_HTTP\n"); goto end; } r = 1; end: if (alpd_tctx != NULL) AppLayerProtoDetectDestroyCtxThread(alpd_tctx); AppLayerProtoDetectDeSetup(); AppLayerProtoDetectUnittestCtxRestore(); return r; } static int AppLayerProtoDetectTest04(void) { AppLayerProtoDetectUnittestCtxBackup(); AppLayerProtoDetectSetup(); uint8_t l7data[] = "HTTP/1.1 200 OK\r\nServer: Apache/1.0\r\n\r\n"; const char *buf; int r = 0; Flow f; AppProto pm_results[ALPROTO_MAX]; AppLayerProtoDetectThreadCtx *alpd_tctx; memset(&f, 0x00, sizeof(f)); f.protomap = FlowGetProtoMapping(IPPROTO_TCP); memset(pm_results, 0, sizeof(pm_results)); buf = "200 "; AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_HTTP, buf, 13, 0, STREAM_TOCLIENT); AppLayerProtoDetectPrepareState(); /* AppLayerProtoDetectGetCtxThread() should be called post AppLayerProtoDetectPrepareState(), since * it sets internal structures which depends on the above function. */ alpd_tctx = AppLayerProtoDetectGetCtxThread(); if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].max_pat_id != 0) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].max_pat_id != 0\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].max_pat_id != 1) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].max_pat_id != 2\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].map != NULL) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].map != NULL\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map == NULL) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map != NULL\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map[0]->alproto != ALPROTO_HTTP) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map[0].alproto != ALPROTO_HTTP\n"); goto end; } uint32_t cnt = AppLayerProtoDetectPMGetProto(alpd_tctx, &f, l7data, sizeof(l7data), STREAM_TOCLIENT, IPPROTO_TCP, pm_results); if (cnt != 1 && pm_results[0] != ALPROTO_HTTP) { printf("cnt != 1 && pm_results[0] != AlPROTO_HTTP\n"); goto end; } r = 1; end: if (alpd_tctx != NULL) AppLayerProtoDetectDestroyCtxThread(alpd_tctx); AppLayerProtoDetectDeSetup(); AppLayerProtoDetectUnittestCtxRestore(); return r; } static int AppLayerProtoDetectTest05(void) { AppLayerProtoDetectUnittestCtxBackup(); AppLayerProtoDetectSetup(); uint8_t l7data[] = "HTTP/1.1 200 OK\r\nServer: Apache/1.0\r\n\r\n<HTML><BODY>Blahblah</BODY></HTML>"; const char *buf; int r = 0; Flow f; AppProto pm_results[ALPROTO_MAX]; AppLayerProtoDetectThreadCtx *alpd_tctx; memset(&f, 0x00, sizeof(f)); f.protomap = FlowGetProtoMapping(IPPROTO_TCP); memset(pm_results, 0, sizeof(pm_results)); buf = "HTTP"; AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_HTTP, buf, 4, 0, STREAM_TOCLIENT); buf = "220 "; AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_FTP, buf, 4, 0, STREAM_TOCLIENT); AppLayerProtoDetectPrepareState(); /* AppLayerProtoDetectGetCtxThread() should be called post AppLayerProtoDetectPrepareState(), since * it sets internal structures which depends on the above function. */ alpd_tctx = AppLayerProtoDetectGetCtxThread(); if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].max_pat_id != 0) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].max_pat_id != 0\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].max_pat_id != 2) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].max_pat_id != 2\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].map != NULL) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].map != NULL\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map == NULL) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map != NULL\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map[0]->alproto != ALPROTO_FTP) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map[0].alproto != ALPROTO_FTP\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map[1]->alproto != ALPROTO_HTTP) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map[1].alproto != ALPROTO_HTTP\n"); goto end; } uint32_t cnt = AppLayerProtoDetectPMGetProto(alpd_tctx, &f, l7data, sizeof(l7data), STREAM_TOCLIENT, IPPROTO_TCP, pm_results); if (cnt != 1 && pm_results[0] != ALPROTO_HTTP) { printf("cnt != 1 && pm_results[0] != AlPROTO_HTTP\n"); goto end; } r = 1; end: if (alpd_tctx != NULL) AppLayerProtoDetectDestroyCtxThread(alpd_tctx); AppLayerProtoDetectDeSetup(); AppLayerProtoDetectUnittestCtxRestore(); return r; } static int AppLayerProtoDetectTest06(void) { AppLayerProtoDetectUnittestCtxBackup(); AppLayerProtoDetectSetup(); uint8_t l7data[] = "220 Welcome to the OISF FTP server\r\n"; const char *buf; int r = 0; Flow f; AppProto pm_results[ALPROTO_MAX]; AppLayerProtoDetectThreadCtx *alpd_tctx; memset(&f, 0x00, sizeof(f)); f.protomap = FlowGetProtoMapping(IPPROTO_TCP); buf = "HTTP"; AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_HTTP, buf, 4, 0, STREAM_TOCLIENT); buf = "220 "; AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_FTP, buf, 4, 0, STREAM_TOCLIENT); AppLayerProtoDetectPrepareState(); /* AppLayerProtoDetectGetCtxThread() should be called post AppLayerProtoDetectPrepareState(), since * it sets internal structures which depends on the above function. */ alpd_tctx = AppLayerProtoDetectGetCtxThread(); if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].max_pat_id != 0) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].max_pat_id != 0\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].max_pat_id != 2) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].max_pat_id != 2\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].map != NULL) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].map != NULL\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map == NULL) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map != NULL\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map[0]->alproto != ALPROTO_FTP) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map[0].alproto != ALPROTO_FTP\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map[1]->alproto != ALPROTO_HTTP) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map[1].alproto != ALPROTO_HTTP\n"); goto end; } uint32_t cnt = AppLayerProtoDetectPMGetProto(alpd_tctx, &f, l7data, sizeof(l7data), STREAM_TOCLIENT, IPPROTO_TCP, pm_results); if (cnt != 1 && pm_results[0] != ALPROTO_FTP) { printf("cnt != 1 && pm_results[0] != AlPROTO_FTP\n"); goto end; } r = 1; end: if (alpd_tctx != NULL) AppLayerProtoDetectDestroyCtxThread(alpd_tctx); AppLayerProtoDetectDeSetup(); AppLayerProtoDetectUnittestCtxRestore(); return r; } static int AppLayerProtoDetectTest07(void) { AppLayerProtoDetectUnittestCtxBackup(); AppLayerProtoDetectSetup(); uint8_t l7data[] = "220 Welcome to the OISF HTTP/FTP server\r\n"; const char *buf; int r = 0; Flow f; AppProto pm_results[ALPROTO_MAX]; AppLayerProtoDetectThreadCtx *alpd_tctx; memset(&f, 0x00, sizeof(f)); f.protomap = FlowGetProtoMapping(IPPROTO_TCP); memset(pm_results, 0, sizeof(pm_results)); buf = "HTTP"; AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_HTTP, buf, 4, 0, STREAM_TOCLIENT); AppLayerProtoDetectPrepareState(); /* AppLayerProtoDetectGetCtxThread() should be called post AppLayerProtoDetectPrepareState(), since * it sets internal structures which depends on the above function. */ alpd_tctx = AppLayerProtoDetectGetCtxThread(); if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].max_pat_id != 0) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].max_pat_id != 0\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].max_pat_id != 1) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].max_pat_id != 2\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].map != NULL) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].map != NULL\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map == NULL) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map != NULL\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map[0]->alproto != ALPROTO_HTTP) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map[0].alproto != ALPROTO_HTTP\n"); goto end; } uint32_t cnt = AppLayerProtoDetectPMGetProto(alpd_tctx, &f, l7data, sizeof(l7data), STREAM_TOCLIENT, IPPROTO_TCP, pm_results); if (cnt != 0) { printf("cnt != 0\n"); goto end; } r = 1; end: if (alpd_tctx != NULL) AppLayerProtoDetectDestroyCtxThread(alpd_tctx); AppLayerProtoDetectDeSetup(); AppLayerProtoDetectUnittestCtxRestore(); return r; } static int AppLayerProtoDetectTest08(void) { AppLayerProtoDetectUnittestCtxBackup(); AppLayerProtoDetectSetup(); uint8_t l7data[] = { 0x00, 0x00, 0x00, 0x85, 0xff, 0x53, 0x4d, 0x42, 0x72, 0x00, 0x00, 0x00, 0x00, 0x18, 0x53, 0xc8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xfe, 0x00, 0x00, 0x00, 0x00, 0x00, 0x62, 0x00, 0x02, 0x50, 0x43, 0x20, 0x4e, 0x45, 0x54, 0x57, 0x4f, 0x52, 0x4b, 0x20, 0x50, 0x52, 0x4f, 0x47, 0x52, 0x41, 0x4d, 0x20, 0x31, 0x2e, 0x30, 0x00, 0x02, 0x4c, 0x41, 0x4e, 0x4d, 0x41, 0x4e, 0x31, 0x2e, 0x30, 0x00, 0x02, 0x57, 0x69, 0x6e, 0x64, 0x6f, 0x77, 0x73, 0x20, 0x66, 0x6f, 0x72, 0x20, 0x57, 0x6f, 0x72, 0x6b, 0x67, 0x72, 0x6f, 0x75, 0x70, 0x73, 0x20, 0x33, 0x2e, 0x31, 0x61, 0x00, 0x02, 0x4c, 0x4d, 0x31, 0x2e, 0x32, 0x58, 0x30, 0x30, 0x32, 0x00, 0x02, 0x4c, 0x41, 0x4e, 0x4d, 0x41, 0x4e, 0x32, 0x2e, 0x31, 0x00, 0x02, 0x4e, 0x54, 0x20, 0x4c, 0x4d, 0x20, 0x30, 0x2e, 0x31, 0x32, 0x00 }; const char *buf; int r = 0; Flow f; AppProto pm_results[ALPROTO_MAX]; AppLayerProtoDetectThreadCtx *alpd_tctx; memset(&f, 0x00, sizeof(f)); f.protomap = FlowGetProtoMapping(IPPROTO_TCP); memset(pm_results, 0, sizeof(pm_results)); buf = "|ff|SMB"; AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_SMB, buf, 8, 4, STREAM_TOCLIENT); AppLayerProtoDetectPrepareState(); /* AppLayerProtoDetectGetCtxThread() should be called post AppLayerProtoDetectPrepareState(), since * it sets internal structures which depends on the above function. */ alpd_tctx = AppLayerProtoDetectGetCtxThread(); if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].max_pat_id != 0) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].max_pat_id != 0\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].max_pat_id != 1) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].max_pat_id != 2\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].map != NULL) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].map != NULL\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map == NULL) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map != NULL\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map[0]->alproto != ALPROTO_SMB) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map[0].alproto != ALPROTO_SMB\n"); goto end; } uint32_t cnt = AppLayerProtoDetectPMGetProto(alpd_tctx, &f, l7data, sizeof(l7data), STREAM_TOCLIENT, IPPROTO_TCP, pm_results); if (cnt != 1 && pm_results[0] != ALPROTO_SMB) { printf("cnt != 1 && pm_results[0] != AlPROTO_SMB\n"); goto end; } r = 1; end: if (alpd_tctx != NULL) AppLayerProtoDetectDestroyCtxThread(alpd_tctx); AppLayerProtoDetectDeSetup(); AppLayerProtoDetectUnittestCtxRestore(); return r; } static int AppLayerProtoDetectTest09(void) { AppLayerProtoDetectUnittestCtxBackup(); AppLayerProtoDetectSetup(); uint8_t l7data[] = { 0x00, 0x00, 0x00, 0x66, 0xfe, 0x53, 0x4d, 0x42, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x24, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x02 }; const char *buf; int r = 0; Flow f; AppProto pm_results[ALPROTO_MAX]; AppLayerProtoDetectThreadCtx *alpd_tctx; memset(&f, 0x00, sizeof(f)); f.protomap = FlowGetProtoMapping(IPPROTO_TCP); memset(pm_results, 0, sizeof(pm_results)); buf = "|fe|SMB"; AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_SMB2, buf, 8, 4, STREAM_TOCLIENT); AppLayerProtoDetectPrepareState(); /* AppLayerProtoDetectGetCtxThread() should be called post AppLayerProtoDetectPrepareState(), since * it sets internal structures which depends on the above function. */ alpd_tctx = AppLayerProtoDetectGetCtxThread(); if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].max_pat_id != 0) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].max_pat_id != 0\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].max_pat_id != 1) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].max_pat_id != 2\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].map != NULL) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].map != NULL\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map == NULL) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map != NULL\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map[0]->alproto != ALPROTO_SMB2) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map[0].alproto != ALPROTO_SMB2\n"); goto end; } uint32_t cnt = AppLayerProtoDetectPMGetProto(alpd_tctx, &f, l7data, sizeof(l7data), STREAM_TOCLIENT, IPPROTO_TCP, pm_results); if (cnt != 1 && pm_results[0] != ALPROTO_SMB2) { printf("cnt != 1 && pm_results[0] != AlPROTO_SMB2\n"); goto end; } r = 1; end: if (alpd_tctx != NULL) AppLayerProtoDetectDestroyCtxThread(alpd_tctx); AppLayerProtoDetectDeSetup(); AppLayerProtoDetectUnittestCtxRestore(); return r; } static int AppLayerProtoDetectTest10(void) { AppLayerProtoDetectUnittestCtxBackup(); AppLayerProtoDetectSetup(); uint8_t l7data[] = { 0x05, 0x00, 0x0b, 0x03, 0x10, 0x00, 0x00, 0x00, 0x48, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd0, 0x16, 0xd0, 0x16, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0xb8, 0x4a, 0x9f, 0x4d, 0x1c, 0x7d, 0xcf, 0x11, 0x86, 0x1e, 0x00, 0x20, 0xaf, 0x6e, 0x7c, 0x57, 0x00, 0x00, 0x00, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00 }; const char *buf; int r = 0; Flow f; AppProto pm_results[ALPROTO_MAX]; AppLayerProtoDetectThreadCtx *alpd_tctx; memset(&f, 0x00, sizeof(f)); f.protomap = FlowGetProtoMapping(IPPROTO_TCP); memset(pm_results, 0, sizeof(pm_results)); buf = "|05 00|"; AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_DCERPC, buf, 4, 0, STREAM_TOCLIENT); AppLayerProtoDetectPrepareState(); /* AppLayerProtoDetectGetCtxThread() should be called post AppLayerProtoDetectPrepareState(), since * it sets internal structures which depends on the above function. */ alpd_tctx = AppLayerProtoDetectGetCtxThread(); if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].max_pat_id != 0) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].max_pat_id != 0\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].max_pat_id != 1) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].max_pat_id != 2\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].map != NULL) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].map != NULL\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map == NULL) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map != NULL\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map[0]->alproto != ALPROTO_DCERPC) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map[0].alproto != ALPROTO_DCERPC\n"); goto end; } uint32_t cnt = AppLayerProtoDetectPMGetProto(alpd_tctx, &f, l7data, sizeof(l7data), STREAM_TOCLIENT, IPPROTO_TCP, pm_results); if (cnt != 1 && pm_results[0] != ALPROTO_DCERPC) { printf("cnt != 1 && pm_results[0] != AlPROTO_DCERPC\n"); goto end; } r = 1; end: if (alpd_tctx != NULL) AppLayerProtoDetectDestroyCtxThread(alpd_tctx); AppLayerProtoDetectDeSetup(); AppLayerProtoDetectUnittestCtxRestore(); return r; } /** * \test Why we still get http for connect... obviously because * we also match on the reply, duh */ static int AppLayerProtoDetectTest11(void) { AppLayerProtoDetectUnittestCtxBackup(); AppLayerProtoDetectSetup(); uint8_t l7data[] = "CONNECT www.ssllabs.com:443 HTTP/1.0\r\n"; uint8_t l7data_resp[] = "HTTP/1.1 405 Method Not Allowed\r\n"; int r = 0; Flow f; AppProto pm_results[ALPROTO_MAX]; AppLayerProtoDetectThreadCtx *alpd_tctx; memset(&f, 0x00, sizeof(f)); f.protomap = FlowGetProtoMapping(IPPROTO_TCP); memset(pm_results, 0, sizeof(pm_results)); AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_HTTP, "HTTP", 4, 0, STREAM_TOSERVER); AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_HTTP, "GET", 3, 0, STREAM_TOSERVER); AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_HTTP, "PUT", 3, 0, STREAM_TOSERVER); AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_HTTP, "POST", 4, 0, STREAM_TOSERVER); AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_HTTP, "TRACE", 5, 0, STREAM_TOSERVER); AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_HTTP, "OPTIONS", 7, 0, STREAM_TOSERVER); AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_HTTP, "CONNECT", 7, 0, STREAM_TOSERVER); AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_HTTP, "HTTP", 4, 0, STREAM_TOCLIENT); AppLayerProtoDetectPrepareState(); /* AppLayerProtoDetectGetCtxThread() should be called post AppLayerProtoDetectPrepareState(), since * it sets internal structures which depends on the above function. */ alpd_tctx = AppLayerProtoDetectGetCtxThread(); if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].max_pat_id != 7) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].max_pat_id != 7\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].max_pat_id != 1) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].max_pat_id != 1\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].map == NULL) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].map != NULL\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map == NULL) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map != NULL\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].map[0]->alproto != ALPROTO_HTTP || alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].map[1]->alproto != ALPROTO_HTTP || alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].map[2]->alproto != ALPROTO_HTTP || alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].map[3]->alproto != ALPROTO_HTTP || alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].map[4]->alproto != ALPROTO_HTTP || alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].map[5]->alproto != ALPROTO_HTTP || alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].map[6]->alproto != ALPROTO_HTTP || alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map[0]->alproto != ALPROTO_HTTP) { printf("failure 1\n"); goto end; } memset(pm_results, 0, sizeof(pm_results)); uint32_t cnt = AppLayerProtoDetectPMGetProto(alpd_tctx, &f, l7data, sizeof(l7data), STREAM_TOSERVER, IPPROTO_TCP, pm_results); if (cnt != 1 && pm_results[0] != ALPROTO_HTTP) { printf("l7data - cnt != 1 && pm_results[0] != AlPROTO_HTTP\n"); goto end; } memset(pm_results, 0, sizeof(pm_results)); cnt = AppLayerProtoDetectPMGetProto(alpd_tctx, &f, l7data_resp, sizeof(l7data_resp), STREAM_TOCLIENT, IPPROTO_TCP, pm_results); if (cnt != 1 && pm_results[0] != ALPROTO_HTTP) { printf("l7data_resp - cnt != 1 && pm_results[0] != AlPROTO_HTTP\n"); goto end; } r = 1; end: if (alpd_tctx != NULL) AppLayerProtoDetectDestroyCtxThread(alpd_tctx); AppLayerProtoDetectDeSetup(); AppLayerProtoDetectUnittestCtxRestore(); return r; } /** * \test AlpProtoSignature test */ static int AppLayerProtoDetectTest12(void) { AppLayerProtoDetectUnittestCtxBackup(); AppLayerProtoDetectSetup(); int r = 0; AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_HTTP, "HTTP", 4, 0, STREAM_TOSERVER); if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].head == NULL || alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].map != NULL) { printf("failure 1\n"); goto end; } AppLayerProtoDetectPrepareState(); if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].max_pat_id != 1) { printf("failure 2\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].head != NULL || alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].map == NULL) { printf("failure 3\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].map[0]->alproto != ALPROTO_HTTP) { printf("failure 4\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].map[0]->cd->id != 0) { printf("failure 5\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].map[0]->next != NULL) { printf("failure 6\n"); goto end; } r = 1; end: AppLayerProtoDetectDeSetup(); AppLayerProtoDetectUnittestCtxRestore(); return r; } /** * \test What about if we add some sigs only for udp but call for tcp? * It should not detect any proto */ static int AppLayerProtoDetectTest13(void) { AppLayerProtoDetectUnittestCtxBackup(); AppLayerProtoDetectSetup(); uint8_t l7data[] = "CONNECT www.ssllabs.com:443 HTTP/1.0\r\n"; uint8_t l7data_resp[] = "HTTP/1.1 405 Method Not Allowed\r\n"; int r = 0; Flow f; AppProto pm_results[ALPROTO_MAX]; AppLayerProtoDetectThreadCtx *alpd_tctx; uint32_t cnt; memset(&f, 0x00, sizeof(f)); f.protomap = FlowGetProtoMapping(IPPROTO_TCP); AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_UDP, ALPROTO_HTTP, "HTTP", 4, 0, STREAM_TOSERVER); AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_UDP, ALPROTO_HTTP, "GET", 3, 0, STREAM_TOSERVER); AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_UDP, ALPROTO_HTTP, "PUT", 3, 0, STREAM_TOSERVER); AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_UDP, ALPROTO_HTTP, "POST", 4, 0, STREAM_TOSERVER); AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_UDP, ALPROTO_HTTP, "TRACE", 5, 0, STREAM_TOSERVER); AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_UDP, ALPROTO_HTTP, "OPTIONS", 7, 0, STREAM_TOSERVER); AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_UDP, ALPROTO_HTTP, "CONNECT", 7, 0, STREAM_TOSERVER); AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_UDP, ALPROTO_HTTP, "HTTP", 4, 0, STREAM_TOCLIENT); AppLayerProtoDetectPrepareState(); /* AppLayerProtoDetectGetCtxThread() should be called post AppLayerProtoDetectPrepareState(), since * it sets internal structures which depends on the above function. */ alpd_tctx = AppLayerProtoDetectGetCtxThread(); if (alpd_ctx.ctx_ipp[FLOW_PROTO_UDP].ctx_pm[0].max_pat_id != 7) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_UDP].ctx_pm[0].max_pat_id != 7\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_UDP].ctx_pm[1].max_pat_id != 1) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_UDP].ctx_pm[1].max_pat_id != 1\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_UDP].ctx_pm[0].map[0]->alproto != ALPROTO_HTTP || alpd_ctx.ctx_ipp[FLOW_PROTO_UDP].ctx_pm[0].map[1]->alproto != ALPROTO_HTTP || alpd_ctx.ctx_ipp[FLOW_PROTO_UDP].ctx_pm[0].map[2]->alproto != ALPROTO_HTTP || alpd_ctx.ctx_ipp[FLOW_PROTO_UDP].ctx_pm[0].map[3]->alproto != ALPROTO_HTTP || alpd_ctx.ctx_ipp[FLOW_PROTO_UDP].ctx_pm[0].map[4]->alproto != ALPROTO_HTTP || alpd_ctx.ctx_ipp[FLOW_PROTO_UDP].ctx_pm[0].map[5]->alproto != ALPROTO_HTTP || alpd_ctx.ctx_ipp[FLOW_PROTO_UDP].ctx_pm[0].map[6]->alproto != ALPROTO_HTTP || alpd_ctx.ctx_ipp[FLOW_PROTO_UDP].ctx_pm[1].map[0]->alproto != ALPROTO_HTTP) { printf("failure 1\n"); goto end; } memset(pm_results, 0, sizeof(pm_results)); cnt = AppLayerProtoDetectPMGetProto(alpd_tctx, &f, l7data, sizeof(l7data), STREAM_TOSERVER, IPPROTO_TCP, pm_results); if (cnt != 0) { printf("l7data - cnt != 0\n"); goto end; } memset(pm_results, 0, sizeof(pm_results)); cnt = AppLayerProtoDetectPMGetProto(alpd_tctx, &f, l7data_resp, sizeof(l7data_resp), STREAM_TOCLIENT, IPPROTO_TCP, pm_results); if (cnt != 0) { printf("l7data_resp - cnt != 0\n"); goto end; } r = 1; end: if (alpd_tctx != NULL) AppLayerProtoDetectDestroyCtxThread(alpd_tctx); AppLayerProtoDetectDeSetup(); AppLayerProtoDetectUnittestCtxRestore(); return r; } /** * \test What about if we add some sigs only for udp calling it for UDP? * It should detect ALPROTO_HTTP (over udp). This is just a check * to ensure that TCP/UDP differences work correctly. */ static int AppLayerProtoDetectTest14(void) { AppLayerProtoDetectUnittestCtxBackup(); AppLayerProtoDetectSetup(); uint8_t l7data[] = "CONNECT www.ssllabs.com:443 HTTP/1.0\r\n"; uint8_t l7data_resp[] = "HTTP/1.1 405 Method Not Allowed\r\n"; int r = 0; Flow f; AppProto pm_results[ALPROTO_MAX]; AppLayerProtoDetectThreadCtx *alpd_tctx; uint32_t cnt; memset(&f, 0x00, sizeof(f)); f.protomap = FlowGetProtoMapping(IPPROTO_UDP); AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_UDP, ALPROTO_HTTP, "HTTP", 4, 0, STREAM_TOSERVER); AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_UDP, ALPROTO_HTTP, "GET", 3, 0, STREAM_TOSERVER); AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_UDP, ALPROTO_HTTP, "PUT", 3, 0, STREAM_TOSERVER); AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_UDP, ALPROTO_HTTP, "POST", 4, 0, STREAM_TOSERVER); AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_UDP, ALPROTO_HTTP, "TRACE", 5, 0, STREAM_TOSERVER); AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_UDP, ALPROTO_HTTP, "OPTIONS", 7, 0, STREAM_TOSERVER); AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_UDP, ALPROTO_HTTP, "CONNECT", 7, 0, STREAM_TOSERVER); AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_UDP, ALPROTO_HTTP, "HTTP", 4, 0, STREAM_TOCLIENT); AppLayerProtoDetectPrepareState(); /* AppLayerProtoDetectGetCtxThread() should be called post AppLayerProtoDetectPrepareState(), since * it sets internal structures which depends on the above function. */ alpd_tctx = AppLayerProtoDetectGetCtxThread(); if (alpd_ctx.ctx_ipp[FLOW_PROTO_UDP].ctx_pm[0].max_pat_id != 7) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_UDP].ctx_pm[0].max_pat_id != 7\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_UDP].ctx_pm[1].max_pat_id != 1) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_UDP].ctx_pm[1].max_pat_id != 1\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_UDP].ctx_pm[0].map[0]->alproto != ALPROTO_HTTP || alpd_ctx.ctx_ipp[FLOW_PROTO_UDP].ctx_pm[0].map[1]->alproto != ALPROTO_HTTP || alpd_ctx.ctx_ipp[FLOW_PROTO_UDP].ctx_pm[0].map[2]->alproto != ALPROTO_HTTP || alpd_ctx.ctx_ipp[FLOW_PROTO_UDP].ctx_pm[0].map[3]->alproto != ALPROTO_HTTP || alpd_ctx.ctx_ipp[FLOW_PROTO_UDP].ctx_pm[0].map[4]->alproto != ALPROTO_HTTP || alpd_ctx.ctx_ipp[FLOW_PROTO_UDP].ctx_pm[0].map[5]->alproto != ALPROTO_HTTP || alpd_ctx.ctx_ipp[FLOW_PROTO_UDP].ctx_pm[0].map[6]->alproto != ALPROTO_HTTP || alpd_ctx.ctx_ipp[FLOW_PROTO_UDP].ctx_pm[1].map[0]->alproto != ALPROTO_HTTP) { printf("failure 1\n"); goto end; } memset(pm_results, 0, sizeof(pm_results)); cnt = AppLayerProtoDetectPMGetProto(alpd_tctx, &f, l7data, sizeof(l7data), STREAM_TOSERVER, IPPROTO_UDP, pm_results); if (cnt != 1 && pm_results[0] != ALPROTO_HTTP) { printf("l7data - cnt != 0\n"); goto end; } memset(pm_results, 0, sizeof(pm_results)); cnt = AppLayerProtoDetectPMGetProto(alpd_tctx, &f, l7data_resp, sizeof(l7data_resp), STREAM_TOCLIENT, IPPROTO_UDP, pm_results); if (cnt != 1 && pm_results[0] != ALPROTO_HTTP) { printf("l7data_resp - cnt != 0\n"); goto end; } r = 1; end: if (alpd_tctx != NULL) AppLayerProtoDetectDestroyCtxThread(alpd_tctx); AppLayerProtoDetectDeSetup(); AppLayerProtoDetectUnittestCtxRestore(); return r; } typedef struct AppLayerProtoDetectPPTestDataElement_ { const char *alproto_name; AppProto alproto; uint16_t port; uint32_t alproto_mask; uint32_t min_depth; uint32_t max_depth; } AppLayerProtoDetectPPTestDataElement; typedef struct AppLayerProtoDetectPPTestDataPort_ { uint16_t port; uint32_t alproto_mask; uint16_t dp_max_depth; uint16_t sp_max_depth; AppLayerProtoDetectPPTestDataElement *toserver_element; AppLayerProtoDetectPPTestDataElement *toclient_element; int ts_no_of_element; int tc_no_of_element; } AppLayerProtoDetectPPTestDataPort; typedef struct AppLayerProtoDetectPPTestDataIPProto_ { uint8_t ipproto; AppLayerProtoDetectPPTestDataPort *port; int no_of_port; } AppLayerProtoDetectPPTestDataIPProto; static int AppLayerProtoDetectPPTestData(AppLayerProtoDetectProbingParser *pp, AppLayerProtoDetectPPTestDataIPProto *ip_proto, int no_of_ip_proto) { int result = 0; int i = -1, j = -1 , k = -1; #ifdef DEBUG int dir = 0; #endif for (i = 0; i < no_of_ip_proto; i++, pp = pp->next) { if (pp->ipproto != ip_proto[i].ipproto) goto end; AppLayerProtoDetectProbingParserPort *pp_port = pp->port; for (k = 0; k < ip_proto[i].no_of_port; k++, pp_port = pp_port->next) { if (pp_port->port != ip_proto[i].port[k].port) goto end; if (pp_port->alproto_mask != ip_proto[i].port[k].alproto_mask) goto end; if (pp_port->alproto_mask != ip_proto[i].port[k].alproto_mask) goto end; if (pp_port->dp_max_depth != ip_proto[i].port[k].dp_max_depth) goto end; if (pp_port->sp_max_depth != ip_proto[i].port[k].sp_max_depth) goto end; AppLayerProtoDetectProbingParserElement *pp_element = pp_port->dp; #ifdef DEBUG dir = 0; #endif for (j = 0 ; j < ip_proto[i].port[k].ts_no_of_element; j++, pp_element = pp_element->next) { if (pp_element->alproto != ip_proto[i].port[k].toserver_element[j].alproto) { goto end; } if (pp_element->port != ip_proto[i].port[k].toserver_element[j].port) { goto end; } if (pp_element->alproto_mask != ip_proto[i].port[k].toserver_element[j].alproto_mask) { goto end; } if (pp_element->min_depth != ip_proto[i].port[k].toserver_element[j].min_depth) { goto end; } if (pp_element->max_depth != ip_proto[i].port[k].toserver_element[j].max_depth) { goto end; } } /* for */ if (pp_element != NULL) goto end; pp_element = pp_port->sp; #ifdef DEBUG dir = 1; #endif for (j = 0 ; j < ip_proto[i].port[k].tc_no_of_element; j++, pp_element = pp_element->next) { if (pp_element->alproto != ip_proto[i].port[k].toclient_element[j].alproto) { goto end; } if (pp_element->port != ip_proto[i].port[k].toclient_element[j].port) { goto end; } if (pp_element->alproto_mask != ip_proto[i].port[k].toclient_element[j].alproto_mask) { goto end; } if (pp_element->min_depth != ip_proto[i].port[k].toclient_element[j].min_depth) { goto end; } if (pp_element->max_depth != ip_proto[i].port[k].toclient_element[j].max_depth) { goto end; } } /* for */ if (pp_element != NULL) goto end; } if (pp_port != NULL) goto end; } if (pp != NULL) goto end; result = 1; end: #ifdef DEBUG printf("i = %d, k = %d, j = %d(%s)\n", i, k, j, (dir == 0) ? "ts" : "tc"); #endif return result; } static uint16_t ProbingParserDummyForTesting(Flow *f, uint8_t *input, uint32_t input_len) { return 0; } static int AppLayerProtoDetectTest15(void) { AppLayerProtoDetectUnittestCtxBackup(); AppLayerProtoDetectSetup(); int result = 0; AppLayerProtoDetectPPRegister(IPPROTO_TCP, "80", ALPROTO_HTTP, 5, 8, STREAM_TOSERVER, ProbingParserDummyForTesting, NULL); AppLayerProtoDetectPPRegister(IPPROTO_TCP, "80", ALPROTO_SMB, 5, 6, STREAM_TOSERVER, ProbingParserDummyForTesting, NULL); AppLayerProtoDetectPPRegister(IPPROTO_TCP, "80", ALPROTO_FTP, 7, 10, STREAM_TOSERVER, ProbingParserDummyForTesting, NULL); AppLayerProtoDetectPPRegister(IPPROTO_TCP, "81", ALPROTO_DCERPC, 9, 10, STREAM_TOSERVER, ProbingParserDummyForTesting, NULL); AppLayerProtoDetectPPRegister(IPPROTO_TCP, "81", ALPROTO_FTP, 7, 15, STREAM_TOSERVER, ProbingParserDummyForTesting, NULL); AppLayerProtoDetectPPRegister(IPPROTO_TCP, "0", ALPROTO_SMTP, 12, 0, STREAM_TOSERVER, ProbingParserDummyForTesting, NULL); AppLayerProtoDetectPPRegister(IPPROTO_TCP, "0", ALPROTO_TLS, 12, 18, STREAM_TOSERVER, ProbingParserDummyForTesting, NULL); AppLayerProtoDetectPPRegister(IPPROTO_TCP, "85", ALPROTO_DCERPC, 9, 10, STREAM_TOSERVER, ProbingParserDummyForTesting, NULL); AppLayerProtoDetectPPRegister(IPPROTO_TCP, "85", ALPROTO_FTP, 7, 15, STREAM_TOSERVER, ProbingParserDummyForTesting, NULL); result = 1; AppLayerProtoDetectPPRegister(IPPROTO_UDP, "85", ALPROTO_IMAP, 12, 23, STREAM_TOSERVER, ProbingParserDummyForTesting, NULL); /* toclient */ AppLayerProtoDetectPPRegister(IPPROTO_TCP, "0", ALPROTO_JABBER, 12, 23, STREAM_TOCLIENT, ProbingParserDummyForTesting, NULL); AppLayerProtoDetectPPRegister(IPPROTO_TCP, "0", ALPROTO_IRC, 12, 14, STREAM_TOCLIENT, ProbingParserDummyForTesting, NULL); AppLayerProtoDetectPPRegister(IPPROTO_TCP, "85", ALPROTO_DCERPC, 9, 10, STREAM_TOCLIENT, ProbingParserDummyForTesting, NULL); AppLayerProtoDetectPPRegister(IPPROTO_TCP, "81", ALPROTO_FTP, 7, 15, STREAM_TOCLIENT, ProbingParserDummyForTesting, NULL); AppLayerProtoDetectPPRegister(IPPROTO_TCP, "0", ALPROTO_TLS, 12, 18, STREAM_TOCLIENT, ProbingParserDummyForTesting, NULL); AppLayerProtoDetectPPRegister(IPPROTO_TCP, "80", ALPROTO_HTTP, 5, 8, STREAM_TOCLIENT, ProbingParserDummyForTesting, NULL); AppLayerProtoDetectPPRegister(IPPROTO_TCP, "81", ALPROTO_DCERPC, 9, 10, STREAM_TOCLIENT, ProbingParserDummyForTesting, NULL); AppLayerProtoDetectPPRegister(IPPROTO_TCP, "90", ALPROTO_FTP, 7, 15, STREAM_TOCLIENT, ProbingParserDummyForTesting, NULL); AppLayerProtoDetectPPRegister(IPPROTO_TCP, "80", ALPROTO_SMB, 5, 6, STREAM_TOCLIENT, ProbingParserDummyForTesting, NULL); AppLayerProtoDetectPPRegister(IPPROTO_UDP, "85", ALPROTO_IMAP, 12, 23, STREAM_TOCLIENT, ProbingParserDummyForTesting, NULL); AppLayerProtoDetectPPRegister(IPPROTO_TCP, "0", ALPROTO_SMTP, 12, 17, STREAM_TOCLIENT, ProbingParserDummyForTesting, NULL); AppLayerProtoDetectPPRegister(IPPROTO_TCP, "80", ALPROTO_FTP, 7, 10, STREAM_TOCLIENT, ProbingParserDummyForTesting, NULL); AppLayerProtoDetectPPTestDataElement element_ts_80[] = { { "http", ALPROTO_HTTP, 80, 1 << ALPROTO_HTTP, 5, 8 }, { "smb", ALPROTO_SMB, 80, 1 << ALPROTO_SMB, 5, 6 }, { "ftp", ALPROTO_FTP, 80, 1 << ALPROTO_FTP, 7, 10 }, { "smtp", ALPROTO_SMTP, 0, 1 << ALPROTO_SMTP, 12, 0 }, { "tls", ALPROTO_TLS, 0, 1 << ALPROTO_TLS, 12, 18 }, { "irc", ALPROTO_IRC, 0, 1 << ALPROTO_IRC, 12, 25 }, { "jabber", ALPROTO_JABBER, 0, 1 << ALPROTO_JABBER, 12, 23 }, }; AppLayerProtoDetectPPTestDataElement element_tc_80[] = { { "http", ALPROTO_HTTP, 80, 1 << ALPROTO_HTTP, 5, 8 }, { "smb", ALPROTO_SMB, 80, 1 << ALPROTO_SMB, 5, 6 }, { "ftp", ALPROTO_FTP, 80, 1 << ALPROTO_FTP, 7, 10 }, { "jabber", ALPROTO_JABBER, 0, 1 << ALPROTO_JABBER, 12, 23 }, { "irc", ALPROTO_IRC, 0, 1 << ALPROTO_IRC, 12, 14 }, { "tls", ALPROTO_TLS, 0, 1 << ALPROTO_TLS, 12, 18 }, { "smtp", ALPROTO_SMTP, 0, 1 << ALPROTO_SMTP, 12, 17 } }; AppLayerProtoDetectPPTestDataElement element_ts_81[] = { { "dcerpc", ALPROTO_DCERPC, 81, 1 << ALPROTO_DCERPC, 9, 10 }, { "ftp", ALPROTO_FTP, 81, 1 << ALPROTO_FTP, 7, 15 }, { "smtp", ALPROTO_SMTP, 0, 1 << ALPROTO_SMTP, 12, 0 }, { "tls", ALPROTO_TLS, 0, 1 << ALPROTO_TLS, 12, 18 }, { "irc", ALPROTO_IRC, 0, 1 << ALPROTO_IRC, 12, 25 }, { "jabber", ALPROTO_JABBER, 0, 1 << ALPROTO_JABBER, 12, 23 }, }; AppLayerProtoDetectPPTestDataElement element_tc_81[] = { { "ftp", ALPROTO_FTP, 81, 1 << ALPROTO_FTP, 7, 15 }, { "dcerpc", ALPROTO_DCERPC, 81, 1 << ALPROTO_DCERPC, 9, 10 }, { "jabber", ALPROTO_JABBER, 0, 1 << ALPROTO_JABBER, 12, 23 }, { "irc", ALPROTO_IRC, 0, 1 << ALPROTO_IRC, 12, 14 }, { "tls", ALPROTO_TLS, 0, 1 << ALPROTO_TLS, 12, 18 }, { "smtp", ALPROTO_SMTP, 0, 1 << ALPROTO_SMTP, 12, 17 } }; AppLayerProtoDetectPPTestDataElement element_ts_85[] = { { "dcerpc", ALPROTO_DCERPC, 85, 1 << ALPROTO_DCERPC, 9, 10 }, { "ftp", ALPROTO_FTP, 85, 1 << ALPROTO_FTP, 7, 15 }, { "smtp", ALPROTO_SMTP, 0, 1 << ALPROTO_SMTP, 12, 0 }, { "tls", ALPROTO_TLS, 0, 1 << ALPROTO_TLS, 12, 18 }, { "irc", ALPROTO_IRC, 0, 1 << ALPROTO_IRC, 12, 25 }, { "jabber", ALPROTO_JABBER, 0, 1 << ALPROTO_JABBER, 12, 23 }, }; AppLayerProtoDetectPPTestDataElement element_tc_85[] = { { "dcerpc", ALPROTO_DCERPC, 85, 1 << ALPROTO_DCERPC, 9, 10 }, { "jabber", ALPROTO_JABBER, 0, 1 << ALPROTO_JABBER, 12, 23 }, { "irc", ALPROTO_IRC, 0, 1 << ALPROTO_IRC, 12, 14 }, { "tls", ALPROTO_TLS, 0, 1 << ALPROTO_TLS, 12, 18 }, { "smtp", ALPROTO_SMTP, 0, 1 << ALPROTO_SMTP, 12, 17 } }; AppLayerProtoDetectPPTestDataElement element_ts_90[] = { { "smtp", ALPROTO_SMTP, 0, 1 << ALPROTO_SMTP, 12, 0 }, { "tls", ALPROTO_TLS, 0, 1 << ALPROTO_TLS, 12, 18 }, { "irc", ALPROTO_IRC, 0, 1 << ALPROTO_IRC, 12, 25 }, { "jabber", ALPROTO_JABBER, 0, 1 << ALPROTO_JABBER, 12, 23 }, }; AppLayerProtoDetectPPTestDataElement element_tc_90[] = { { "ftp", ALPROTO_FTP, 90, 1 << ALPROTO_FTP, 7, 15 }, { "jabber", ALPROTO_JABBER, 0, 1 << ALPROTO_JABBER, 12, 23 }, { "irc", ALPROTO_IRC, 0, 1 << ALPROTO_IRC, 12, 14 }, { "tls", ALPROTO_TLS, 0, 1 << ALPROTO_TLS, 12, 18 }, { "smtp", ALPROTO_SMTP, 0, 1 << ALPROTO_SMTP, 12, 17 } }; AppLayerProtoDetectPPTestDataElement element_ts_0[] = { { "smtp", ALPROTO_SMTP, 0, 1 << ALPROTO_SMTP, 12, 0 }, { "tls", ALPROTO_TLS, 0, 1 << ALPROTO_TLS, 12, 18 }, { "irc", ALPROTO_IRC, 0, 1 << ALPROTO_IRC, 12, 25 }, { "jabber", ALPROTO_JABBER, 0, 1 << ALPROTO_JABBER, 12, 23 }, }; AppLayerProtoDetectPPTestDataElement element_tc_0[] = { { "jabber", ALPROTO_JABBER, 0, 1 << ALPROTO_JABBER, 12, 23 }, { "irc", ALPROTO_IRC, 0, 1 << ALPROTO_IRC, 12, 14 }, { "tls", ALPROTO_TLS, 0, 1 << ALPROTO_TLS, 12, 18 }, { "smtp", ALPROTO_SMTP, 0, 1 << ALPROTO_SMTP, 12, 17 } }; AppLayerProtoDetectPPTestDataElement element_ts_85_udp[] = { { "imap", ALPROTO_IMAP, 85, 1 << ALPROTO_IMAP, 12, 23 }, }; AppLayerProtoDetectPPTestDataElement element_tc_85_udp[] = { { "imap", ALPROTO_IMAP, 85, 1 << ALPROTO_IMAP, 12, 23 }, }; AppLayerProtoDetectPPTestDataPort ports_tcp[] = { { 80, ((1 << ALPROTO_HTTP) | (1 << ALPROTO_SMB) | (1 << ALPROTO_FTP) | (1 << ALPROTO_SMTP) | (1 << ALPROTO_TLS) | (1 << ALPROTO_IRC) | (1 << ALPROTO_JABBER)), ((1 << ALPROTO_HTTP) | (1 << ALPROTO_SMB) | (1 << ALPROTO_FTP) | (1 << ALPROTO_JABBER) | (1 << ALPROTO_IRC) | (1 << ALPROTO_TLS) | (1 << ALPROTO_SMTP)), 23, element_ts_80, element_tc_80, sizeof(element_ts_80) / sizeof(AppLayerProtoDetectPPTestDataElement), sizeof(element_tc_80) / sizeof(AppLayerProtoDetectPPTestDataElement), }, { 81, ((1 << ALPROTO_DCERPC) | (1 << ALPROTO_FTP) | (1 << ALPROTO_SMTP) | (1 << ALPROTO_TLS) | (1 << ALPROTO_IRC) | (1 << ALPROTO_JABBER)), ((1 << ALPROTO_FTP) | (1 << ALPROTO_DCERPC) | (1 << ALPROTO_JABBER) | (1 << ALPROTO_IRC) | (1 << ALPROTO_TLS) | (1 << ALPROTO_SMTP)), 23, element_ts_81, element_tc_81, sizeof(element_ts_81) / sizeof(AppLayerProtoDetectPPTestDataElement), sizeof(element_tc_81) / sizeof(AppLayerProtoDetectPPTestDataElement), }, { 85, ((1 << ALPROTO_DCERPC) | (1 << ALPROTO_FTP) | (1 << ALPROTO_SMTP) | (1 << ALPROTO_TLS) | (1 << ALPROTO_IRC) | (1 << ALPROTO_JABBER)), ((1 << ALPROTO_DCERPC) | (1 << ALPROTO_JABBER) | (1 << ALPROTO_IRC) | (1 << ALPROTO_TLS) | (1 << ALPROTO_SMTP)), 23, element_ts_85, element_tc_85, sizeof(element_ts_85) / sizeof(AppLayerProtoDetectPPTestDataElement), sizeof(element_tc_85) / sizeof(AppLayerProtoDetectPPTestDataElement) }, { 90, ((1 << ALPROTO_SMTP) | (1 << ALPROTO_TLS) | (1 << ALPROTO_IRC) | (1 << ALPROTO_JABBER)), ((1 << ALPROTO_FTP) | (1 << ALPROTO_JABBER) | (1 << ALPROTO_IRC) | (1 << ALPROTO_TLS) | (1 << ALPROTO_SMTP)), 23, element_ts_90, element_tc_90, sizeof(element_ts_90) / sizeof(AppLayerProtoDetectPPTestDataElement), sizeof(element_tc_90) / sizeof(AppLayerProtoDetectPPTestDataElement) }, { 0, ((1 << ALPROTO_SMTP) | (1 << ALPROTO_TLS) | (1 << ALPROTO_IRC) | (1 << ALPROTO_JABBER)), ((1 << ALPROTO_JABBER) | (1 << ALPROTO_IRC) | (1 << ALPROTO_TLS) | (1 << ALPROTO_SMTP)), 23, element_ts_0, element_tc_0, sizeof(element_ts_0) / sizeof(AppLayerProtoDetectPPTestDataElement), sizeof(element_tc_0) / sizeof(AppLayerProtoDetectPPTestDataElement) } }; AppLayerProtoDetectPPTestDataPort ports_udp[] = { { 85, (1 << ALPROTO_IMAP), (1 << ALPROTO_IMAP), 23, element_ts_85_udp, element_tc_85_udp, sizeof(element_ts_85_udp) / sizeof(AppLayerProtoDetectPPTestDataElement), sizeof(element_tc_85_udp) / sizeof(AppLayerProtoDetectPPTestDataElement), }, }; AppLayerProtoDetectPPTestDataIPProto ip_proto[] = { { IPPROTO_TCP, ports_tcp, sizeof(ports_tcp) / sizeof(AppLayerProtoDetectPPTestDataPort), }, { IPPROTO_UDP, ports_udp, sizeof(ports_udp) / sizeof(AppLayerProtoDetectPPTestDataPort), }, }; if (AppLayerProtoDetectPPTestData(alpd_ctx.ctx_pp, ip_proto, sizeof(ip_proto) / sizeof(AppLayerProtoDetectPPTestDataIPProto)) == 0) { goto end; } result = 1; end: AppLayerProtoDetectDeSetup(); AppLayerProtoDetectUnittestCtxRestore(); return result; } /** \test test if the engine detect the proto and match with it */ static int AppLayerProtoDetectTest16(void) { int result = 0; Flow *f = NULL; HtpState *http_state = NULL; uint8_t http_buf1[] = "POST /one HTTP/1.0\r\n" "User-Agent: Mozilla/1.0\r\n" "Cookie: hellocatch\r\n\r\n"; uint32_t http_buf1_len = sizeof(http_buf1) - 1; TcpSession ssn; Packet *p = NULL; Signature *s = NULL; ThreadVars tv; DetectEngineThreadCtx *det_ctx = NULL; DetectEngineCtx *de_ctx = NULL; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); memset(&tv, 0, sizeof(ThreadVars)); memset(&ssn, 0, sizeof(TcpSession)); p = UTHBuildPacket(NULL, 0, IPPROTO_TCP); if (p == NULL) { printf("packet setup failed: "); goto end; } f = UTHBuildFlow(AF_INET, "1.1.1.1", "2.2.2.2", 1024, 80); if (f == NULL) { printf("flow setup failed: "); goto end; } f->protoctx = &ssn; f->proto = IPPROTO_TCP; p->flow = f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; f->alproto = ALPROTO_HTTP; StreamTcpInitConfig(TRUE); de_ctx = DetectEngineCtxInit(); if (de_ctx == NULL) { goto end; } de_ctx->flags |= DE_QUIET; s = de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " "(msg:\"Test content option\"; " "sid:1;)"); if (s == NULL) { goto end; } SigGroupBuild(de_ctx); DetectEngineThreadCtxInit(&tv, (void *)de_ctx, (void *)&det_ctx); FLOWLOCK_WRLOCK(f); int r = AppLayerParserParse(NULL, alp_tctx, f, ALPROTO_HTTP, STREAM_TOSERVER, http_buf1, http_buf1_len); if (r != 0) { printf("toserver chunk 1 returned %" PRId32 ", expected 0: ", r); FLOWLOCK_UNLOCK(f); goto end; } FLOWLOCK_UNLOCK(f); http_state = f->alstate; if (http_state == NULL) { printf("no http state: "); goto end; } /* do detect */ SigMatchSignatures(&tv, de_ctx, det_ctx, p); if (!PacketAlertCheck(p, 1)) { printf("sig 1 didn't alert, but it should: "); goto end; } result = 1; end: if (alp_tctx != NULL) AppLayerParserThreadCtxFree(alp_tctx); if (det_ctx != NULL) DetectEngineThreadCtxDeinit(&tv, det_ctx); if (de_ctx != NULL) SigGroupCleanup(de_ctx); if (de_ctx != NULL) DetectEngineCtxFree(de_ctx); StreamTcpFreeConfig(TRUE); UTHFreePackets(&p, 1); UTHFreeFlow(f); return result; } /** \test test if the engine detect the proto on a non standar port * and match with it */ static int AppLayerProtoDetectTest17(void) { int result = 0; Flow *f = NULL; HtpState *http_state = NULL; uint8_t http_buf1[] = "POST /one HTTP/1.0\r\n" "User-Agent: Mozilla/1.0\r\n" "Cookie: hellocatch\r\n\r\n"; uint32_t http_buf1_len = sizeof(http_buf1) - 1; TcpSession ssn; Packet *p = NULL; Signature *s = NULL; ThreadVars tv; DetectEngineThreadCtx *det_ctx = NULL; DetectEngineCtx *de_ctx = NULL; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); memset(&tv, 0, sizeof(ThreadVars)); memset(&ssn, 0, sizeof(TcpSession)); p = UTHBuildPacketSrcDstPorts(http_buf1, http_buf1_len, IPPROTO_TCP, 12345, 88); f = UTHBuildFlow(AF_INET, "1.1.1.1", "2.2.2.2", 1024, 80); if (f == NULL) goto end; f->protoctx = &ssn; f->proto = IPPROTO_TCP; p->flow = f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; f->alproto = ALPROTO_HTTP; StreamTcpInitConfig(TRUE); de_ctx = DetectEngineCtxInit(); if (de_ctx == NULL) { goto end; } de_ctx->flags |= DE_QUIET; s = de_ctx->sig_list = SigInit(de_ctx, "alert http any !80 -> any any " "(msg:\"http over non standar port\"; " "sid:1;)"); if (s == NULL) { goto end; } SigGroupBuild(de_ctx); DetectEngineThreadCtxInit(&tv, (void *)de_ctx, (void *)&det_ctx); FLOWLOCK_WRLOCK(f); int r = AppLayerParserParse(NULL, alp_tctx, f, ALPROTO_HTTP, STREAM_TOSERVER, http_buf1, http_buf1_len); if (r != 0) { printf("toserver chunk 1 returned %" PRId32 ", expected 0: ", r); FLOWLOCK_UNLOCK(f); goto end; } FLOWLOCK_UNLOCK(f); http_state = f->alstate; if (http_state == NULL) { printf("no http state: "); goto end; } /* do detect */ SigMatchSignatures(&tv, de_ctx, det_ctx, p); if (!PacketAlertCheck(p, 1)) { printf("sig 1 didn't alert, but it should: "); goto end; } result = 1; end: if (alp_tctx != NULL) AppLayerParserThreadCtxFree(alp_tctx); if (det_ctx != NULL) DetectEngineThreadCtxDeinit(&tv, det_ctx); if (de_ctx != NULL) SigGroupCleanup(de_ctx); if (de_ctx != NULL) DetectEngineCtxFree(de_ctx); StreamTcpFreeConfig(TRUE); UTHFreePackets(&p, 1); UTHFreeFlow(f); return result; } /** \test test if the engine detect the proto and doesn't match * because the sig expects another proto (ex ftp)*/ static int AppLayerProtoDetectTest18(void) { int result = 0; Flow *f = NULL; HtpState *http_state = NULL; uint8_t http_buf1[] = "POST /one HTTP/1.0\r\n" "User-Agent: Mozilla/1.0\r\n" "Cookie: hellocatch\r\n\r\n"; uint32_t http_buf1_len = sizeof(http_buf1) - 1; TcpSession ssn; Packet *p = NULL; Signature *s = NULL; ThreadVars tv; DetectEngineThreadCtx *det_ctx = NULL; DetectEngineCtx *de_ctx = NULL; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); memset(&tv, 0, sizeof(ThreadVars)); memset(&ssn, 0, sizeof(TcpSession)); p = UTHBuildPacket(http_buf1, http_buf1_len, IPPROTO_TCP); f = UTHBuildFlow(AF_INET, "1.1.1.1", "2.2.2.2", 1024, 80); if (f == NULL) goto end; f->protoctx = &ssn; f->proto = IPPROTO_TCP; p->flow = f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; f->alproto = ALPROTO_HTTP; StreamTcpInitConfig(TRUE); de_ctx = DetectEngineCtxInit(); if (de_ctx == NULL) { goto end; } de_ctx->flags |= DE_QUIET; s = de_ctx->sig_list = SigInit(de_ctx, "alert ftp any any -> any any " "(msg:\"Test content option\"; " "sid:1;)"); if (s == NULL) { goto end; } SigGroupBuild(de_ctx); DetectEngineThreadCtxInit(&tv, (void *)de_ctx, (void *)&det_ctx); FLOWLOCK_WRLOCK(f); int r = AppLayerParserParse(NULL, alp_tctx, f, ALPROTO_HTTP, STREAM_TOSERVER, http_buf1, http_buf1_len); if (r != 0) { printf("toserver chunk 1 returned %" PRId32 ", expected 0: ", r); FLOWLOCK_UNLOCK(f); goto end; } FLOWLOCK_UNLOCK(f); http_state = f->alstate; if (http_state == NULL) { printf("no http state: "); goto end; } /* do detect */ SigMatchSignatures(&tv, de_ctx, det_ctx, p); if (PacketAlertCheck(p, 1)) { printf("sig 1 alerted, but it should not (it's not ftp): "); goto end; } result = 1; end: if (alp_tctx != NULL) AppLayerParserThreadCtxFree(alp_tctx); if (det_ctx != NULL) DetectEngineThreadCtxDeinit(&tv, det_ctx); if (de_ctx != NULL) SigGroupCleanup(de_ctx); if (de_ctx != NULL) DetectEngineCtxFree(de_ctx); StreamTcpFreeConfig(TRUE); UTHFreePackets(&p, 1); UTHFreeFlow(f); return result; } /** \test test if the engine detect the proto and doesn't match * because the packet has another proto (ex ftp) */ static int AppLayerProtoDetectTest19(void) { int result = 0; Flow *f = NULL; uint8_t http_buf1[] = "MPUT one\r\n"; uint32_t http_buf1_len = sizeof(http_buf1) - 1; TcpSession ssn; Packet *p = NULL; Signature *s = NULL; ThreadVars tv; DetectEngineThreadCtx *det_ctx = NULL; DetectEngineCtx *de_ctx = NULL; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); memset(&tv, 0, sizeof(ThreadVars)); memset(&ssn, 0, sizeof(TcpSession)); p = UTHBuildPacketSrcDstPorts(http_buf1, http_buf1_len, IPPROTO_TCP, 12345, 88); f = UTHBuildFlow(AF_INET, "1.1.1.1", "2.2.2.2", 1024, 80); if (f == NULL) goto end; f->protoctx = &ssn; f->proto = IPPROTO_TCP; p->flow = f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; f->alproto = ALPROTO_FTP; StreamTcpInitConfig(TRUE); de_ctx = DetectEngineCtxInit(); if (de_ctx == NULL) { goto end; } de_ctx->flags |= DE_QUIET; s = de_ctx->sig_list = SigInit(de_ctx, "alert http any !80 -> any any " "(msg:\"http over non standar port\"; " "sid:1;)"); if (s == NULL) { goto end; } SigGroupBuild(de_ctx); DetectEngineThreadCtxInit(&tv, (void *)de_ctx, (void *)&det_ctx); FLOWLOCK_WRLOCK(f); int r = AppLayerParserParse(NULL, alp_tctx, f, ALPROTO_FTP, STREAM_TOSERVER, http_buf1, http_buf1_len); if (r != 0) { printf("toserver chunk 1 returned %" PRId32 ", expected 0: ", r); FLOWLOCK_UNLOCK(f); goto end; } FLOWLOCK_UNLOCK(f); /* do detect */ SigMatchSignatures(&tv, de_ctx, det_ctx, p); if (PacketAlertCheck(p, 1)) { printf("sig 1 alerted, but it should not (it's ftp): "); goto end; } result = 1; end: if (alp_tctx != NULL) AppLayerParserThreadCtxFree(alp_tctx); if (det_ctx != NULL) DetectEngineThreadCtxDeinit(&tv, det_ctx); if (de_ctx != NULL) SigGroupCleanup(de_ctx); if (de_ctx != NULL) DetectEngineCtxFree(de_ctx); StreamTcpFreeConfig(TRUE); UTHFreePackets(&p, 1); UTHFreeFlow(f); return result; } void AppLayerProtoDetectUnittestsRegister(void) { SCEnter(); UtRegisterTest("AppLayerProtoDetectTest01", AppLayerProtoDetectTest01); UtRegisterTest("AppLayerProtoDetectTest02", AppLayerProtoDetectTest02); UtRegisterTest("AppLayerProtoDetectTest03", AppLayerProtoDetectTest03); UtRegisterTest("AppLayerProtoDetectTest04", AppLayerProtoDetectTest04); UtRegisterTest("AppLayerProtoDetectTest05", AppLayerProtoDetectTest05); UtRegisterTest("AppLayerProtoDetectTest06", AppLayerProtoDetectTest06); UtRegisterTest("AppLayerProtoDetectTest07", AppLayerProtoDetectTest07); UtRegisterTest("AppLayerProtoDetectTest08", AppLayerProtoDetectTest08); UtRegisterTest("AppLayerProtoDetectTest09", AppLayerProtoDetectTest09); UtRegisterTest("AppLayerProtoDetectTest10", AppLayerProtoDetectTest10); UtRegisterTest("AppLayerProtoDetectTest11", AppLayerProtoDetectTest11); UtRegisterTest("AppLayerProtoDetectTest12", AppLayerProtoDetectTest12); UtRegisterTest("AppLayerProtoDetectTest13", AppLayerProtoDetectTest13); UtRegisterTest("AppLayerProtoDetectTest14", AppLayerProtoDetectTest14); UtRegisterTest("AppLayerProtoDetectTest15", AppLayerProtoDetectTest15); UtRegisterTest("AppLayerProtoDetectTest16", AppLayerProtoDetectTest16); UtRegisterTest("AppLayerProtoDetectTest17", AppLayerProtoDetectTest17); UtRegisterTest("AppLayerProtoDetectTest18", AppLayerProtoDetectTest18); UtRegisterTest("AppLayerProtoDetectTest19", AppLayerProtoDetectTest19); SCReturn; } #endif /* UNITTESTS */
./CrossVul/dataset_final_sorted/CWE-20/c/good_722_0
crossvul-cpp_data_good_2115_0
/* * Derived from "arch/i386/kernel/process.c" * Copyright (C) 1995 Linus Torvalds * * Updated and modified by Cort Dougan (cort@cs.nmt.edu) and * Paul Mackerras (paulus@cs.anu.edu.au) * * PowerPC version * Copyright (C) 1995-1996 Gary Thomas (gdt@linuxppc.org) * * 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/errno.h> #include <linux/sched.h> #include <linux/kernel.h> #include <linux/mm.h> #include <linux/smp.h> #include <linux/stddef.h> #include <linux/unistd.h> #include <linux/ptrace.h> #include <linux/slab.h> #include <linux/user.h> #include <linux/elf.h> #include <linux/prctl.h> #include <linux/init_task.h> #include <linux/export.h> #include <linux/kallsyms.h> #include <linux/mqueue.h> #include <linux/hardirq.h> #include <linux/utsname.h> #include <linux/ftrace.h> #include <linux/kernel_stat.h> #include <linux/personality.h> #include <linux/random.h> #include <linux/hw_breakpoint.h> #include <asm/pgtable.h> #include <asm/uaccess.h> #include <asm/io.h> #include <asm/processor.h> #include <asm/mmu.h> #include <asm/prom.h> #include <asm/machdep.h> #include <asm/time.h> #include <asm/runlatch.h> #include <asm/syscalls.h> #include <asm/switch_to.h> #include <asm/tm.h> #include <asm/debug.h> #ifdef CONFIG_PPC64 #include <asm/firmware.h> #endif #include <linux/kprobes.h> #include <linux/kdebug.h> /* Transactional Memory debug */ #ifdef TM_DEBUG_SW #define TM_DEBUG(x...) printk(KERN_INFO x) #else #define TM_DEBUG(x...) do { } while(0) #endif extern unsigned long _get_SP(void); #ifndef CONFIG_SMP struct task_struct *last_task_used_math = NULL; struct task_struct *last_task_used_altivec = NULL; struct task_struct *last_task_used_vsx = NULL; struct task_struct *last_task_used_spe = NULL; #endif #ifdef CONFIG_PPC_TRANSACTIONAL_MEM void giveup_fpu_maybe_transactional(struct task_struct *tsk) { /* * If we are saving the current thread's registers, and the * thread is in a transactional state, set the TIF_RESTORE_TM * bit so that we know to restore the registers before * returning to userspace. */ if (tsk == current && tsk->thread.regs && MSR_TM_ACTIVE(tsk->thread.regs->msr) && !test_thread_flag(TIF_RESTORE_TM)) { tsk->thread.tm_orig_msr = tsk->thread.regs->msr; set_thread_flag(TIF_RESTORE_TM); } giveup_fpu(tsk); } void giveup_altivec_maybe_transactional(struct task_struct *tsk) { /* * If we are saving the current thread's registers, and the * thread is in a transactional state, set the TIF_RESTORE_TM * bit so that we know to restore the registers before * returning to userspace. */ if (tsk == current && tsk->thread.regs && MSR_TM_ACTIVE(tsk->thread.regs->msr) && !test_thread_flag(TIF_RESTORE_TM)) { tsk->thread.tm_orig_msr = tsk->thread.regs->msr; set_thread_flag(TIF_RESTORE_TM); } giveup_altivec(tsk); } #else #define giveup_fpu_maybe_transactional(tsk) giveup_fpu(tsk) #define giveup_altivec_maybe_transactional(tsk) giveup_altivec(tsk) #endif /* CONFIG_PPC_TRANSACTIONAL_MEM */ #ifdef CONFIG_PPC_FPU /* * Make sure the floating-point register state in the * the thread_struct is up to date for task tsk. */ void flush_fp_to_thread(struct task_struct *tsk) { if (tsk->thread.regs) { /* * We need to disable preemption here because if we didn't, * another process could get scheduled after the regs->msr * test but before we have finished saving the FP registers * to the thread_struct. That process could take over the * FPU, and then when we get scheduled again we would store * bogus values for the remaining FP registers. */ preempt_disable(); if (tsk->thread.regs->msr & MSR_FP) { #ifdef CONFIG_SMP /* * This should only ever be called for current or * for a stopped child process. Since we save away * the FP register state on context switch on SMP, * there is something wrong if a stopped child appears * to still have its FP state in the CPU registers. */ BUG_ON(tsk != current); #endif giveup_fpu_maybe_transactional(tsk); } preempt_enable(); } } EXPORT_SYMBOL_GPL(flush_fp_to_thread); #endif /* CONFIG_PPC_FPU */ void enable_kernel_fp(void) { WARN_ON(preemptible()); #ifdef CONFIG_SMP if (current->thread.regs && (current->thread.regs->msr & MSR_FP)) giveup_fpu_maybe_transactional(current); else giveup_fpu(NULL); /* just enables FP for kernel */ #else giveup_fpu_maybe_transactional(last_task_used_math); #endif /* CONFIG_SMP */ } EXPORT_SYMBOL(enable_kernel_fp); #ifdef CONFIG_ALTIVEC void enable_kernel_altivec(void) { WARN_ON(preemptible()); #ifdef CONFIG_SMP if (current->thread.regs && (current->thread.regs->msr & MSR_VEC)) giveup_altivec_maybe_transactional(current); else giveup_altivec_notask(); #else giveup_altivec_maybe_transactional(last_task_used_altivec); #endif /* CONFIG_SMP */ } EXPORT_SYMBOL(enable_kernel_altivec); /* * Make sure the VMX/Altivec register state in the * the thread_struct is up to date for task tsk. */ void flush_altivec_to_thread(struct task_struct *tsk) { if (tsk->thread.regs) { preempt_disable(); if (tsk->thread.regs->msr & MSR_VEC) { #ifdef CONFIG_SMP BUG_ON(tsk != current); #endif giveup_altivec_maybe_transactional(tsk); } preempt_enable(); } } EXPORT_SYMBOL_GPL(flush_altivec_to_thread); #endif /* CONFIG_ALTIVEC */ #ifdef CONFIG_VSX #if 0 /* not currently used, but some crazy RAID module might want to later */ void enable_kernel_vsx(void) { WARN_ON(preemptible()); #ifdef CONFIG_SMP if (current->thread.regs && (current->thread.regs->msr & MSR_VSX)) giveup_vsx(current); else giveup_vsx(NULL); /* just enable vsx for kernel - force */ #else giveup_vsx(last_task_used_vsx); #endif /* CONFIG_SMP */ } EXPORT_SYMBOL(enable_kernel_vsx); #endif void giveup_vsx(struct task_struct *tsk) { giveup_fpu_maybe_transactional(tsk); giveup_altivec_maybe_transactional(tsk); __giveup_vsx(tsk); } void flush_vsx_to_thread(struct task_struct *tsk) { if (tsk->thread.regs) { preempt_disable(); if (tsk->thread.regs->msr & MSR_VSX) { #ifdef CONFIG_SMP BUG_ON(tsk != current); #endif giveup_vsx(tsk); } preempt_enable(); } } EXPORT_SYMBOL_GPL(flush_vsx_to_thread); #endif /* CONFIG_VSX */ #ifdef CONFIG_SPE void enable_kernel_spe(void) { WARN_ON(preemptible()); #ifdef CONFIG_SMP if (current->thread.regs && (current->thread.regs->msr & MSR_SPE)) giveup_spe(current); else giveup_spe(NULL); /* just enable SPE for kernel - force */ #else giveup_spe(last_task_used_spe); #endif /* __SMP __ */ } EXPORT_SYMBOL(enable_kernel_spe); void flush_spe_to_thread(struct task_struct *tsk) { if (tsk->thread.regs) { preempt_disable(); if (tsk->thread.regs->msr & MSR_SPE) { #ifdef CONFIG_SMP BUG_ON(tsk != current); #endif tsk->thread.spefscr = mfspr(SPRN_SPEFSCR); giveup_spe(tsk); } preempt_enable(); } } #endif /* CONFIG_SPE */ #ifndef CONFIG_SMP /* * If we are doing lazy switching of CPU state (FP, altivec or SPE), * and the current task has some state, discard it. */ void discard_lazy_cpu_state(void) { preempt_disable(); if (last_task_used_math == current) last_task_used_math = NULL; #ifdef CONFIG_ALTIVEC if (last_task_used_altivec == current) last_task_used_altivec = NULL; #endif /* CONFIG_ALTIVEC */ #ifdef CONFIG_VSX if (last_task_used_vsx == current) last_task_used_vsx = NULL; #endif /* CONFIG_VSX */ #ifdef CONFIG_SPE if (last_task_used_spe == current) last_task_used_spe = NULL; #endif preempt_enable(); } #endif /* CONFIG_SMP */ #ifdef CONFIG_PPC_ADV_DEBUG_REGS void do_send_trap(struct pt_regs *regs, unsigned long address, unsigned long error_code, int signal_code, int breakpt) { siginfo_t info; current->thread.trap_nr = signal_code; if (notify_die(DIE_DABR_MATCH, "dabr_match", regs, error_code, 11, SIGSEGV) == NOTIFY_STOP) return; /* Deliver the signal to userspace */ info.si_signo = SIGTRAP; info.si_errno = breakpt; /* breakpoint or watchpoint id */ info.si_code = signal_code; info.si_addr = (void __user *)address; force_sig_info(SIGTRAP, &info, current); } #else /* !CONFIG_PPC_ADV_DEBUG_REGS */ void do_break (struct pt_regs *regs, unsigned long address, unsigned long error_code) { siginfo_t info; current->thread.trap_nr = TRAP_HWBKPT; if (notify_die(DIE_DABR_MATCH, "dabr_match", regs, error_code, 11, SIGSEGV) == NOTIFY_STOP) return; if (debugger_break_match(regs)) return; /* Clear the breakpoint */ hw_breakpoint_disable(); /* Deliver the signal to userspace */ info.si_signo = SIGTRAP; info.si_errno = 0; info.si_code = TRAP_HWBKPT; info.si_addr = (void __user *)address; force_sig_info(SIGTRAP, &info, current); } #endif /* CONFIG_PPC_ADV_DEBUG_REGS */ static DEFINE_PER_CPU(struct arch_hw_breakpoint, current_brk); #ifdef CONFIG_PPC_ADV_DEBUG_REGS /* * Set the debug registers back to their default "safe" values. */ static void set_debug_reg_defaults(struct thread_struct *thread) { thread->debug.iac1 = thread->debug.iac2 = 0; #if CONFIG_PPC_ADV_DEBUG_IACS > 2 thread->debug.iac3 = thread->debug.iac4 = 0; #endif thread->debug.dac1 = thread->debug.dac2 = 0; #if CONFIG_PPC_ADV_DEBUG_DVCS > 0 thread->debug.dvc1 = thread->debug.dvc2 = 0; #endif thread->debug.dbcr0 = 0; #ifdef CONFIG_BOOKE /* * Force User/Supervisor bits to b11 (user-only MSR[PR]=1) */ thread->debug.dbcr1 = DBCR1_IAC1US | DBCR1_IAC2US | DBCR1_IAC3US | DBCR1_IAC4US; /* * Force Data Address Compare User/Supervisor bits to be User-only * (0b11 MSR[PR]=1) and set all other bits in DBCR2 register to be 0. */ thread->debug.dbcr2 = DBCR2_DAC1US | DBCR2_DAC2US; #else thread->debug.dbcr1 = 0; #endif } static void prime_debug_regs(struct debug_reg *debug) { /* * We could have inherited MSR_DE from userspace, since * it doesn't get cleared on exception entry. Make sure * MSR_DE is clear before we enable any debug events. */ mtmsr(mfmsr() & ~MSR_DE); mtspr(SPRN_IAC1, debug->iac1); mtspr(SPRN_IAC2, debug->iac2); #if CONFIG_PPC_ADV_DEBUG_IACS > 2 mtspr(SPRN_IAC3, debug->iac3); mtspr(SPRN_IAC4, debug->iac4); #endif mtspr(SPRN_DAC1, debug->dac1); mtspr(SPRN_DAC2, debug->dac2); #if CONFIG_PPC_ADV_DEBUG_DVCS > 0 mtspr(SPRN_DVC1, debug->dvc1); mtspr(SPRN_DVC2, debug->dvc2); #endif mtspr(SPRN_DBCR0, debug->dbcr0); mtspr(SPRN_DBCR1, debug->dbcr1); #ifdef CONFIG_BOOKE mtspr(SPRN_DBCR2, debug->dbcr2); #endif } /* * Unless neither the old or new thread are making use of the * debug registers, set the debug registers from the values * stored in the new thread. */ void switch_booke_debug_regs(struct debug_reg *new_debug) { if ((current->thread.debug.dbcr0 & DBCR0_IDM) || (new_debug->dbcr0 & DBCR0_IDM)) prime_debug_regs(new_debug); } EXPORT_SYMBOL_GPL(switch_booke_debug_regs); #else /* !CONFIG_PPC_ADV_DEBUG_REGS */ #ifndef CONFIG_HAVE_HW_BREAKPOINT static void set_debug_reg_defaults(struct thread_struct *thread) { thread->hw_brk.address = 0; thread->hw_brk.type = 0; set_breakpoint(&thread->hw_brk); } #endif /* !CONFIG_HAVE_HW_BREAKPOINT */ #endif /* CONFIG_PPC_ADV_DEBUG_REGS */ #ifdef CONFIG_PPC_ADV_DEBUG_REGS static inline int __set_dabr(unsigned long dabr, unsigned long dabrx) { mtspr(SPRN_DAC1, dabr); #ifdef CONFIG_PPC_47x isync(); #endif return 0; } #elif defined(CONFIG_PPC_BOOK3S) static inline int __set_dabr(unsigned long dabr, unsigned long dabrx) { mtspr(SPRN_DABR, dabr); if (cpu_has_feature(CPU_FTR_DABRX)) mtspr(SPRN_DABRX, dabrx); return 0; } #else static inline int __set_dabr(unsigned long dabr, unsigned long dabrx) { return -EINVAL; } #endif static inline int set_dabr(struct arch_hw_breakpoint *brk) { unsigned long dabr, dabrx; dabr = brk->address | (brk->type & HW_BRK_TYPE_DABR); dabrx = ((brk->type >> 3) & 0x7); if (ppc_md.set_dabr) return ppc_md.set_dabr(dabr, dabrx); return __set_dabr(dabr, dabrx); } static inline int set_dawr(struct arch_hw_breakpoint *brk) { unsigned long dawr, dawrx, mrd; dawr = brk->address; dawrx = (brk->type & (HW_BRK_TYPE_READ | HW_BRK_TYPE_WRITE)) \ << (63 - 58); //* read/write bits */ dawrx |= ((brk->type & (HW_BRK_TYPE_TRANSLATE)) >> 2) \ << (63 - 59); //* translate */ dawrx |= (brk->type & (HW_BRK_TYPE_PRIV_ALL)) \ >> 3; //* PRIM bits */ /* dawr length is stored in field MDR bits 48:53. Matches range in doublewords (64 bits) baised by -1 eg. 0b000000=1DW and 0b111111=64DW. brk->len is in bytes. This aligns up to double word size, shifts and does the bias. */ mrd = ((brk->len + 7) >> 3) - 1; dawrx |= (mrd & 0x3f) << (63 - 53); if (ppc_md.set_dawr) return ppc_md.set_dawr(dawr, dawrx); mtspr(SPRN_DAWR, dawr); mtspr(SPRN_DAWRX, dawrx); return 0; } int set_breakpoint(struct arch_hw_breakpoint *brk) { __get_cpu_var(current_brk) = *brk; if (cpu_has_feature(CPU_FTR_DAWR)) return set_dawr(brk); return set_dabr(brk); } #ifdef CONFIG_PPC64 DEFINE_PER_CPU(struct cpu_usage, cpu_usage_array); #endif static inline bool hw_brk_match(struct arch_hw_breakpoint *a, struct arch_hw_breakpoint *b) { if (a->address != b->address) return false; if (a->type != b->type) return false; if (a->len != b->len) return false; return true; } #ifdef CONFIG_PPC_TRANSACTIONAL_MEM static void tm_reclaim_thread(struct thread_struct *thr, struct thread_info *ti, uint8_t cause) { unsigned long msr_diff = 0; /* * If FP/VSX registers have been already saved to the * thread_struct, move them to the transact_fp array. * We clear the TIF_RESTORE_TM bit since after the reclaim * the thread will no longer be transactional. */ if (test_ti_thread_flag(ti, TIF_RESTORE_TM)) { msr_diff = thr->tm_orig_msr & ~thr->regs->msr; if (msr_diff & MSR_FP) memcpy(&thr->transact_fp, &thr->fp_state, sizeof(struct thread_fp_state)); if (msr_diff & MSR_VEC) memcpy(&thr->transact_vr, &thr->vr_state, sizeof(struct thread_vr_state)); clear_ti_thread_flag(ti, TIF_RESTORE_TM); msr_diff &= MSR_FP | MSR_VEC | MSR_VSX | MSR_FE0 | MSR_FE1; } tm_reclaim(thr, thr->regs->msr, cause); /* Having done the reclaim, we now have the checkpointed * FP/VSX values in the registers. These might be valid * even if we have previously called enable_kernel_fp() or * flush_fp_to_thread(), so update thr->regs->msr to * indicate their current validity. */ thr->regs->msr |= msr_diff; } void tm_reclaim_current(uint8_t cause) { tm_enable(); tm_reclaim_thread(&current->thread, current_thread_info(), cause); } static inline void tm_reclaim_task(struct task_struct *tsk) { /* We have to work out if we're switching from/to a task that's in the * middle of a transaction. * * In switching we need to maintain a 2nd register state as * oldtask->thread.ckpt_regs. We tm_reclaim(oldproc); this saves the * checkpointed (tbegin) state in ckpt_regs and saves the transactional * (current) FPRs into oldtask->thread.transact_fpr[]. * * We also context switch (save) TFHAR/TEXASR/TFIAR in here. */ struct thread_struct *thr = &tsk->thread; if (!thr->regs) return; if (!MSR_TM_ACTIVE(thr->regs->msr)) goto out_and_saveregs; /* Stash the original thread MSR, as giveup_fpu et al will * modify it. We hold onto it to see whether the task used * FP & vector regs. If the TIF_RESTORE_TM flag is set, * tm_orig_msr is already set. */ if (!test_ti_thread_flag(task_thread_info(tsk), TIF_RESTORE_TM)) thr->tm_orig_msr = thr->regs->msr; TM_DEBUG("--- tm_reclaim on pid %d (NIP=%lx, " "ccr=%lx, msr=%lx, trap=%lx)\n", tsk->pid, thr->regs->nip, thr->regs->ccr, thr->regs->msr, thr->regs->trap); tm_reclaim_thread(thr, task_thread_info(tsk), TM_CAUSE_RESCHED); TM_DEBUG("--- tm_reclaim on pid %d complete\n", tsk->pid); out_and_saveregs: /* Always save the regs here, even if a transaction's not active. * This context-switches a thread's TM info SPRs. We do it here to * be consistent with the restore path (in recheckpoint) which * cannot happen later in _switch(). */ tm_save_sprs(thr); } static inline void tm_recheckpoint_new_task(struct task_struct *new) { unsigned long msr; if (!cpu_has_feature(CPU_FTR_TM)) return; /* Recheckpoint the registers of the thread we're about to switch to. * * If the task was using FP, we non-lazily reload both the original and * the speculative FP register states. This is because the kernel * doesn't see if/when a TM rollback occurs, so if we take an FP * unavoidable later, we are unable to determine which set of FP regs * need to be restored. */ if (!new->thread.regs) return; /* The TM SPRs are restored here, so that TEXASR.FS can be set * before the trecheckpoint and no explosion occurs. */ tm_restore_sprs(&new->thread); if (!MSR_TM_ACTIVE(new->thread.regs->msr)) return; msr = new->thread.tm_orig_msr; /* Recheckpoint to restore original checkpointed register state. */ TM_DEBUG("*** tm_recheckpoint of pid %d " "(new->msr 0x%lx, new->origmsr 0x%lx)\n", new->pid, new->thread.regs->msr, msr); /* This loads the checkpointed FP/VEC state, if used */ tm_recheckpoint(&new->thread, msr); /* This loads the speculative FP/VEC state, if used */ if (msr & MSR_FP) { do_load_up_transact_fpu(&new->thread); new->thread.regs->msr |= (MSR_FP | new->thread.fpexc_mode); } #ifdef CONFIG_ALTIVEC if (msr & MSR_VEC) { do_load_up_transact_altivec(&new->thread); new->thread.regs->msr |= MSR_VEC; } #endif /* We may as well turn on VSX too since all the state is restored now */ if (msr & MSR_VSX) new->thread.regs->msr |= MSR_VSX; TM_DEBUG("*** tm_recheckpoint of pid %d complete " "(kernel msr 0x%lx)\n", new->pid, mfmsr()); } static inline void __switch_to_tm(struct task_struct *prev) { if (cpu_has_feature(CPU_FTR_TM)) { tm_enable(); tm_reclaim_task(prev); } } /* * This is called if we are on the way out to userspace and the * TIF_RESTORE_TM flag is set. It checks if we need to reload * FP and/or vector state and does so if necessary. * If userspace is inside a transaction (whether active or * suspended) and FP/VMX/VSX instructions have ever been enabled * inside that transaction, then we have to keep them enabled * and keep the FP/VMX/VSX state loaded while ever the transaction * continues. The reason is that if we didn't, and subsequently * got a FP/VMX/VSX unavailable interrupt inside a transaction, * we don't know whether it's the same transaction, and thus we * don't know which of the checkpointed state and the transactional * state to use. */ void restore_tm_state(struct pt_regs *regs) { unsigned long msr_diff; clear_thread_flag(TIF_RESTORE_TM); if (!MSR_TM_ACTIVE(regs->msr)) return; msr_diff = current->thread.tm_orig_msr & ~regs->msr; msr_diff &= MSR_FP | MSR_VEC | MSR_VSX; if (msr_diff & MSR_FP) { fp_enable(); load_fp_state(&current->thread.fp_state); regs->msr |= current->thread.fpexc_mode; } if (msr_diff & MSR_VEC) { vec_enable(); load_vr_state(&current->thread.vr_state); } regs->msr |= msr_diff; } #else #define tm_recheckpoint_new_task(new) #define __switch_to_tm(prev) #endif /* CONFIG_PPC_TRANSACTIONAL_MEM */ struct task_struct *__switch_to(struct task_struct *prev, struct task_struct *new) { struct thread_struct *new_thread, *old_thread; struct task_struct *last; #ifdef CONFIG_PPC_BOOK3S_64 struct ppc64_tlb_batch *batch; #endif WARN_ON(!irqs_disabled()); /* Back up the TAR across context switches. * Note that the TAR is not available for use in the kernel. (To * provide this, the TAR should be backed up/restored on exception * entry/exit instead, and be in pt_regs. FIXME, this should be in * pt_regs anyway (for debug).) * Save the TAR here before we do treclaim/trecheckpoint as these * will change the TAR. */ save_tar(&prev->thread); __switch_to_tm(prev); #ifdef CONFIG_SMP /* avoid complexity of lazy save/restore of fpu * by just saving it every time we switch out if * this task used the fpu during the last quantum. * * If it tries to use the fpu again, it'll trap and * reload its fp regs. So we don't have to do a restore * every switch, just a save. * -- Cort */ if (prev->thread.regs && (prev->thread.regs->msr & MSR_FP)) giveup_fpu(prev); #ifdef CONFIG_ALTIVEC /* * If the previous thread used altivec in the last quantum * (thus changing altivec regs) then save them. * We used to check the VRSAVE register but not all apps * set it, so we don't rely on it now (and in fact we need * to save & restore VSCR even if VRSAVE == 0). -- paulus * * On SMP we always save/restore altivec regs just to avoid the * complexity of changing processors. * -- Cort */ if (prev->thread.regs && (prev->thread.regs->msr & MSR_VEC)) giveup_altivec(prev); #endif /* CONFIG_ALTIVEC */ #ifdef CONFIG_VSX if (prev->thread.regs && (prev->thread.regs->msr & MSR_VSX)) /* VMX and FPU registers are already save here */ __giveup_vsx(prev); #endif /* CONFIG_VSX */ #ifdef CONFIG_SPE /* * If the previous thread used spe in the last quantum * (thus changing spe regs) then save them. * * On SMP we always save/restore spe regs just to avoid the * complexity of changing processors. */ if ((prev->thread.regs && (prev->thread.regs->msr & MSR_SPE))) giveup_spe(prev); #endif /* CONFIG_SPE */ #else /* CONFIG_SMP */ #ifdef CONFIG_ALTIVEC /* Avoid the trap. On smp this this never happens since * we don't set last_task_used_altivec -- Cort */ if (new->thread.regs && last_task_used_altivec == new) new->thread.regs->msr |= MSR_VEC; #endif /* CONFIG_ALTIVEC */ #ifdef CONFIG_VSX if (new->thread.regs && last_task_used_vsx == new) new->thread.regs->msr |= MSR_VSX; #endif /* CONFIG_VSX */ #ifdef CONFIG_SPE /* Avoid the trap. On smp this this never happens since * we don't set last_task_used_spe */ if (new->thread.regs && last_task_used_spe == new) new->thread.regs->msr |= MSR_SPE; #endif /* CONFIG_SPE */ #endif /* CONFIG_SMP */ #ifdef CONFIG_PPC_ADV_DEBUG_REGS switch_booke_debug_regs(&new->thread.debug); #else /* * For PPC_BOOK3S_64, we use the hw-breakpoint interfaces that would * schedule DABR */ #ifndef CONFIG_HAVE_HW_BREAKPOINT if (unlikely(!hw_brk_match(&__get_cpu_var(current_brk), &new->thread.hw_brk))) set_breakpoint(&new->thread.hw_brk); #endif /* CONFIG_HAVE_HW_BREAKPOINT */ #endif new_thread = &new->thread; old_thread = &current->thread; #ifdef CONFIG_PPC64 /* * Collect processor utilization data per process */ if (firmware_has_feature(FW_FEATURE_SPLPAR)) { struct cpu_usage *cu = &__get_cpu_var(cpu_usage_array); long unsigned start_tb, current_tb; start_tb = old_thread->start_tb; cu->current_tb = current_tb = mfspr(SPRN_PURR); old_thread->accum_tb += (current_tb - start_tb); new_thread->start_tb = current_tb; } #endif /* CONFIG_PPC64 */ #ifdef CONFIG_PPC_BOOK3S_64 batch = &__get_cpu_var(ppc64_tlb_batch); if (batch->active) { current_thread_info()->local_flags |= _TLF_LAZY_MMU; if (batch->index) __flush_tlb_pending(batch); batch->active = 0; } #endif /* CONFIG_PPC_BOOK3S_64 */ /* * We can't take a PMU exception inside _switch() since there is a * window where the kernel stack SLB and the kernel stack are out * of sync. Hard disable here. */ hard_irq_disable(); tm_recheckpoint_new_task(new); last = _switch(old_thread, new_thread); #ifdef CONFIG_PPC_BOOK3S_64 if (current_thread_info()->local_flags & _TLF_LAZY_MMU) { current_thread_info()->local_flags &= ~_TLF_LAZY_MMU; batch = &__get_cpu_var(ppc64_tlb_batch); batch->active = 1; } #endif /* CONFIG_PPC_BOOK3S_64 */ return last; } static int instructions_to_print = 16; static void show_instructions(struct pt_regs *regs) { int i; unsigned long pc = regs->nip - (instructions_to_print * 3 / 4 * sizeof(int)); printk("Instruction dump:"); for (i = 0; i < instructions_to_print; i++) { int instr; if (!(i % 8)) printk("\n"); #if !defined(CONFIG_BOOKE) /* If executing with the IMMU off, adjust pc rather * than print XXXXXXXX. */ if (!(regs->msr & MSR_IR)) pc = (unsigned long)phys_to_virt(pc); #endif /* We use __get_user here *only* to avoid an OOPS on a * bad address because the pc *should* only be a * kernel address. */ if (!__kernel_text_address(pc) || __get_user(instr, (unsigned int __user *)pc)) { printk(KERN_CONT "XXXXXXXX "); } else { if (regs->nip == pc) printk(KERN_CONT "<%08x> ", instr); else printk(KERN_CONT "%08x ", instr); } pc += sizeof(int); } printk("\n"); } static struct regbit { unsigned long bit; const char *name; } msr_bits[] = { #if defined(CONFIG_PPC64) && !defined(CONFIG_BOOKE) {MSR_SF, "SF"}, {MSR_HV, "HV"}, #endif {MSR_VEC, "VEC"}, {MSR_VSX, "VSX"}, #ifdef CONFIG_BOOKE {MSR_CE, "CE"}, #endif {MSR_EE, "EE"}, {MSR_PR, "PR"}, {MSR_FP, "FP"}, {MSR_ME, "ME"}, #ifdef CONFIG_BOOKE {MSR_DE, "DE"}, #else {MSR_SE, "SE"}, {MSR_BE, "BE"}, #endif {MSR_IR, "IR"}, {MSR_DR, "DR"}, {MSR_PMM, "PMM"}, #ifndef CONFIG_BOOKE {MSR_RI, "RI"}, {MSR_LE, "LE"}, #endif {0, NULL} }; static void printbits(unsigned long val, struct regbit *bits) { const char *sep = ""; printk("<"); for (; bits->bit; ++bits) if (val & bits->bit) { printk("%s%s", sep, bits->name); sep = ","; } printk(">"); } #ifdef CONFIG_PPC64 #define REG "%016lx" #define REGS_PER_LINE 4 #define LAST_VOLATILE 13 #else #define REG "%08lx" #define REGS_PER_LINE 8 #define LAST_VOLATILE 12 #endif void show_regs(struct pt_regs * regs) { int i, trap; show_regs_print_info(KERN_DEFAULT); printk("NIP: "REG" LR: "REG" CTR: "REG"\n", regs->nip, regs->link, regs->ctr); printk("REGS: %p TRAP: %04lx %s (%s)\n", regs, regs->trap, print_tainted(), init_utsname()->release); printk("MSR: "REG" ", regs->msr); printbits(regs->msr, msr_bits); printk(" CR: %08lx XER: %08lx\n", regs->ccr, regs->xer); trap = TRAP(regs); if ((regs->trap != 0xc00) && cpu_has_feature(CPU_FTR_CFAR)) printk("CFAR: "REG" ", regs->orig_gpr3); if (trap == 0x200 || trap == 0x300 || trap == 0x600) #if defined(CONFIG_4xx) || defined(CONFIG_BOOKE) printk("DEAR: "REG" ESR: "REG" ", regs->dar, regs->dsisr); #else printk("DAR: "REG" DSISR: %08lx ", regs->dar, regs->dsisr); #endif #ifdef CONFIG_PPC64 printk("SOFTE: %ld ", regs->softe); #endif #ifdef CONFIG_PPC_TRANSACTIONAL_MEM if (MSR_TM_ACTIVE(regs->msr)) printk("\nPACATMSCRATCH: %016llx ", get_paca()->tm_scratch); #endif for (i = 0; i < 32; i++) { if ((i % REGS_PER_LINE) == 0) printk("\nGPR%02d: ", i); printk(REG " ", regs->gpr[i]); if (i == LAST_VOLATILE && !FULL_REGS(regs)) break; } printk("\n"); #ifdef CONFIG_KALLSYMS /* * Lookup NIP late so we have the best change of getting the * above info out without failing */ printk("NIP ["REG"] %pS\n", regs->nip, (void *)regs->nip); printk("LR ["REG"] %pS\n", regs->link, (void *)regs->link); #endif show_stack(current, (unsigned long *) regs->gpr[1]); if (!user_mode(regs)) show_instructions(regs); } void exit_thread(void) { discard_lazy_cpu_state(); } void flush_thread(void) { discard_lazy_cpu_state(); #ifdef CONFIG_HAVE_HW_BREAKPOINT flush_ptrace_hw_breakpoint(current); #else /* CONFIG_HAVE_HW_BREAKPOINT */ set_debug_reg_defaults(&current->thread); #endif /* CONFIG_HAVE_HW_BREAKPOINT */ } void release_thread(struct task_struct *t) { } /* * this gets called so that we can store coprocessor state into memory and * copy the current task into the new thread. */ int arch_dup_task_struct(struct task_struct *dst, struct task_struct *src) { flush_fp_to_thread(src); flush_altivec_to_thread(src); flush_vsx_to_thread(src); flush_spe_to_thread(src); /* * Flush TM state out so we can copy it. __switch_to_tm() does this * flush but it removes the checkpointed state from the current CPU and * transitions the CPU out of TM mode. Hence we need to call * tm_recheckpoint_new_task() (on the same task) to restore the * checkpointed state back and the TM mode. */ __switch_to_tm(src); tm_recheckpoint_new_task(src); *dst = *src; clear_task_ebb(dst); return 0; } /* * Copy a thread.. */ extern unsigned long dscr_default; /* defined in arch/powerpc/kernel/sysfs.c */ int copy_thread(unsigned long clone_flags, unsigned long usp, unsigned long arg, struct task_struct *p) { struct pt_regs *childregs, *kregs; extern void ret_from_fork(void); extern void ret_from_kernel_thread(void); void (*f)(void); unsigned long sp = (unsigned long)task_stack_page(p) + THREAD_SIZE; /* Copy registers */ sp -= sizeof(struct pt_regs); childregs = (struct pt_regs *) sp; if (unlikely(p->flags & PF_KTHREAD)) { struct thread_info *ti = (void *)task_stack_page(p); memset(childregs, 0, sizeof(struct pt_regs)); childregs->gpr[1] = sp + sizeof(struct pt_regs); childregs->gpr[14] = usp; /* function */ #ifdef CONFIG_PPC64 clear_tsk_thread_flag(p, TIF_32BIT); childregs->softe = 1; #endif childregs->gpr[15] = arg; p->thread.regs = NULL; /* no user register state */ ti->flags |= _TIF_RESTOREALL; f = ret_from_kernel_thread; } else { struct pt_regs *regs = current_pt_regs(); CHECK_FULL_REGS(regs); *childregs = *regs; if (usp) childregs->gpr[1] = usp; p->thread.regs = childregs; childregs->gpr[3] = 0; /* Result from fork() */ if (clone_flags & CLONE_SETTLS) { #ifdef CONFIG_PPC64 if (!is_32bit_task()) childregs->gpr[13] = childregs->gpr[6]; else #endif childregs->gpr[2] = childregs->gpr[6]; } f = ret_from_fork; } sp -= STACK_FRAME_OVERHEAD; /* * The way this works is that at some point in the future * some task will call _switch to switch to the new task. * That will pop off the stack frame created below and start * the new task running at ret_from_fork. The new task will * do some house keeping and then return from the fork or clone * system call, using the stack frame created above. */ ((unsigned long *)sp)[0] = 0; sp -= sizeof(struct pt_regs); kregs = (struct pt_regs *) sp; sp -= STACK_FRAME_OVERHEAD; p->thread.ksp = sp; #ifdef CONFIG_PPC32 p->thread.ksp_limit = (unsigned long)task_stack_page(p) + _ALIGN_UP(sizeof(struct thread_info), 16); #endif #ifdef CONFIG_HAVE_HW_BREAKPOINT p->thread.ptrace_bps[0] = NULL; #endif p->thread.fp_save_area = NULL; #ifdef CONFIG_ALTIVEC p->thread.vr_save_area = NULL; #endif #ifdef CONFIG_PPC_STD_MMU_64 if (mmu_has_feature(MMU_FTR_SLB)) { unsigned long sp_vsid; unsigned long llp = mmu_psize_defs[mmu_linear_psize].sllp; if (mmu_has_feature(MMU_FTR_1T_SEGMENT)) sp_vsid = get_kernel_vsid(sp, MMU_SEGSIZE_1T) << SLB_VSID_SHIFT_1T; else sp_vsid = get_kernel_vsid(sp, MMU_SEGSIZE_256M) << SLB_VSID_SHIFT; sp_vsid |= SLB_VSID_KERNEL | llp; p->thread.ksp_vsid = sp_vsid; } #endif /* CONFIG_PPC_STD_MMU_64 */ #ifdef CONFIG_PPC64 if (cpu_has_feature(CPU_FTR_DSCR)) { p->thread.dscr_inherit = current->thread.dscr_inherit; p->thread.dscr = current->thread.dscr; } if (cpu_has_feature(CPU_FTR_HAS_PPR)) p->thread.ppr = INIT_PPR; #endif /* * The PPC64 ABI makes use of a TOC to contain function * pointers. The function (ret_from_except) is actually a pointer * to the TOC entry. The first entry is a pointer to the actual * function. */ #ifdef CONFIG_PPC64 kregs->nip = *((unsigned long *)f); #else kregs->nip = (unsigned long)f; #endif return 0; } /* * Set up a thread for executing a new program */ void start_thread(struct pt_regs *regs, unsigned long start, unsigned long sp) { #ifdef CONFIG_PPC64 unsigned long load_addr = regs->gpr[2]; /* saved by ELF_PLAT_INIT */ #endif /* * If we exec out of a kernel thread then thread.regs will not be * set. Do it now. */ if (!current->thread.regs) { struct pt_regs *regs = task_stack_page(current) + THREAD_SIZE; current->thread.regs = regs - 1; } memset(regs->gpr, 0, sizeof(regs->gpr)); regs->ctr = 0; regs->link = 0; regs->xer = 0; regs->ccr = 0; regs->gpr[1] = sp; /* * We have just cleared all the nonvolatile GPRs, so make * FULL_REGS(regs) return true. This is necessary to allow * ptrace to examine the thread immediately after exec. */ regs->trap &= ~1UL; #ifdef CONFIG_PPC32 regs->mq = 0; regs->nip = start; regs->msr = MSR_USER; #else if (!is_32bit_task()) { unsigned long entry; if (is_elf2_task()) { /* Look ma, no function descriptors! */ entry = start; /* * Ulrich says: * The latest iteration of the ABI requires that when * calling a function (at its global entry point), * the caller must ensure r12 holds the entry point * address (so that the function can quickly * establish addressability). */ regs->gpr[12] = start; /* Make sure that's restored on entry to userspace. */ set_thread_flag(TIF_RESTOREALL); } else { unsigned long toc; /* start is a relocated pointer to the function * descriptor for the elf _start routine. The first * entry in the function descriptor is the entry * address of _start and the second entry is the TOC * value we need to use. */ __get_user(entry, (unsigned long __user *)start); __get_user(toc, (unsigned long __user *)start+1); /* Check whether the e_entry function descriptor entries * need to be relocated before we can use them. */ if (load_addr != 0) { entry += load_addr; toc += load_addr; } regs->gpr[2] = toc; } regs->nip = entry; regs->msr = MSR_USER64; } else { regs->nip = start; regs->gpr[2] = 0; regs->msr = MSR_USER32; } #endif discard_lazy_cpu_state(); #ifdef CONFIG_VSX current->thread.used_vsr = 0; #endif memset(&current->thread.fp_state, 0, sizeof(current->thread.fp_state)); current->thread.fp_save_area = NULL; #ifdef CONFIG_ALTIVEC memset(&current->thread.vr_state, 0, sizeof(current->thread.vr_state)); current->thread.vr_state.vscr.u[3] = 0x00010000; /* Java mode disabled */ current->thread.vr_save_area = NULL; current->thread.vrsave = 0; current->thread.used_vr = 0; #endif /* CONFIG_ALTIVEC */ #ifdef CONFIG_SPE memset(current->thread.evr, 0, sizeof(current->thread.evr)); current->thread.acc = 0; current->thread.spefscr = 0; current->thread.used_spe = 0; #endif /* CONFIG_SPE */ #ifdef CONFIG_PPC_TRANSACTIONAL_MEM if (cpu_has_feature(CPU_FTR_TM)) regs->msr |= MSR_TM; current->thread.tm_tfhar = 0; current->thread.tm_texasr = 0; current->thread.tm_tfiar = 0; #endif /* CONFIG_PPC_TRANSACTIONAL_MEM */ } #define PR_FP_ALL_EXCEPT (PR_FP_EXC_DIV | PR_FP_EXC_OVF | PR_FP_EXC_UND \ | PR_FP_EXC_RES | PR_FP_EXC_INV) int set_fpexc_mode(struct task_struct *tsk, unsigned int val) { struct pt_regs *regs = tsk->thread.regs; /* This is a bit hairy. If we are an SPE enabled processor * (have embedded fp) we store the IEEE exception enable flags in * fpexc_mode. fpexc_mode is also used for setting FP exception * mode (asyn, precise, disabled) for 'Classic' FP. */ if (val & PR_FP_EXC_SW_ENABLE) { #ifdef CONFIG_SPE if (cpu_has_feature(CPU_FTR_SPE)) { /* * When the sticky exception bits are set * directly by userspace, it must call prctl * with PR_GET_FPEXC (with PR_FP_EXC_SW_ENABLE * in the existing prctl settings) or * PR_SET_FPEXC (with PR_FP_EXC_SW_ENABLE in * the bits being set). <fenv.h> functions * saving and restoring the whole * floating-point environment need to do so * anyway to restore the prctl settings from * the saved environment. */ tsk->thread.spefscr_last = mfspr(SPRN_SPEFSCR); tsk->thread.fpexc_mode = val & (PR_FP_EXC_SW_ENABLE | PR_FP_ALL_EXCEPT); return 0; } else { return -EINVAL; } #else return -EINVAL; #endif } /* on a CONFIG_SPE this does not hurt us. The bits that * __pack_fe01 use do not overlap with bits used for * PR_FP_EXC_SW_ENABLE. Additionally, the MSR[FE0,FE1] bits * on CONFIG_SPE implementations are reserved so writing to * them does not change anything */ if (val > PR_FP_EXC_PRECISE) return -EINVAL; tsk->thread.fpexc_mode = __pack_fe01(val); if (regs != NULL && (regs->msr & MSR_FP) != 0) regs->msr = (regs->msr & ~(MSR_FE0|MSR_FE1)) | tsk->thread.fpexc_mode; return 0; } int get_fpexc_mode(struct task_struct *tsk, unsigned long adr) { unsigned int val; if (tsk->thread.fpexc_mode & PR_FP_EXC_SW_ENABLE) #ifdef CONFIG_SPE if (cpu_has_feature(CPU_FTR_SPE)) { /* * When the sticky exception bits are set * directly by userspace, it must call prctl * with PR_GET_FPEXC (with PR_FP_EXC_SW_ENABLE * in the existing prctl settings) or * PR_SET_FPEXC (with PR_FP_EXC_SW_ENABLE in * the bits being set). <fenv.h> functions * saving and restoring the whole * floating-point environment need to do so * anyway to restore the prctl settings from * the saved environment. */ tsk->thread.spefscr_last = mfspr(SPRN_SPEFSCR); val = tsk->thread.fpexc_mode; } else return -EINVAL; #else return -EINVAL; #endif else val = __unpack_fe01(tsk->thread.fpexc_mode); return put_user(val, (unsigned int __user *) adr); } int set_endian(struct task_struct *tsk, unsigned int val) { struct pt_regs *regs = tsk->thread.regs; if ((val == PR_ENDIAN_LITTLE && !cpu_has_feature(CPU_FTR_REAL_LE)) || (val == PR_ENDIAN_PPC_LITTLE && !cpu_has_feature(CPU_FTR_PPC_LE))) return -EINVAL; if (regs == NULL) return -EINVAL; if (val == PR_ENDIAN_BIG) regs->msr &= ~MSR_LE; else if (val == PR_ENDIAN_LITTLE || val == PR_ENDIAN_PPC_LITTLE) regs->msr |= MSR_LE; else return -EINVAL; return 0; } int get_endian(struct task_struct *tsk, unsigned long adr) { struct pt_regs *regs = tsk->thread.regs; unsigned int val; if (!cpu_has_feature(CPU_FTR_PPC_LE) && !cpu_has_feature(CPU_FTR_REAL_LE)) return -EINVAL; if (regs == NULL) return -EINVAL; if (regs->msr & MSR_LE) { if (cpu_has_feature(CPU_FTR_REAL_LE)) val = PR_ENDIAN_LITTLE; else val = PR_ENDIAN_PPC_LITTLE; } else val = PR_ENDIAN_BIG; return put_user(val, (unsigned int __user *)adr); } int set_unalign_ctl(struct task_struct *tsk, unsigned int val) { tsk->thread.align_ctl = val; return 0; } int get_unalign_ctl(struct task_struct *tsk, unsigned long adr) { return put_user(tsk->thread.align_ctl, (unsigned int __user *)adr); } static inline int valid_irq_stack(unsigned long sp, struct task_struct *p, unsigned long nbytes) { unsigned long stack_page; unsigned long cpu = task_cpu(p); /* * Avoid crashing if the stack has overflowed and corrupted * task_cpu(p), which is in the thread_info struct. */ if (cpu < NR_CPUS && cpu_possible(cpu)) { stack_page = (unsigned long) hardirq_ctx[cpu]; if (sp >= stack_page + sizeof(struct thread_struct) && sp <= stack_page + THREAD_SIZE - nbytes) return 1; stack_page = (unsigned long) softirq_ctx[cpu]; if (sp >= stack_page + sizeof(struct thread_struct) && sp <= stack_page + THREAD_SIZE - nbytes) return 1; } return 0; } int validate_sp(unsigned long sp, struct task_struct *p, unsigned long nbytes) { unsigned long stack_page = (unsigned long)task_stack_page(p); if (sp >= stack_page + sizeof(struct thread_struct) && sp <= stack_page + THREAD_SIZE - nbytes) return 1; return valid_irq_stack(sp, p, nbytes); } EXPORT_SYMBOL(validate_sp); unsigned long get_wchan(struct task_struct *p) { unsigned long ip, sp; int count = 0; if (!p || p == current || p->state == TASK_RUNNING) return 0; sp = p->thread.ksp; if (!validate_sp(sp, p, STACK_FRAME_OVERHEAD)) return 0; do { sp = *(unsigned long *)sp; if (!validate_sp(sp, p, STACK_FRAME_OVERHEAD)) return 0; if (count > 0) { ip = ((unsigned long *)sp)[STACK_FRAME_LR_SAVE]; if (!in_sched_functions(ip)) return ip; } } while (count++ < 16); return 0; } static int kstack_depth_to_print = CONFIG_PRINT_STACK_DEPTH; void show_stack(struct task_struct *tsk, unsigned long *stack) { unsigned long sp, ip, lr, newsp; int count = 0; int firstframe = 1; #ifdef CONFIG_FUNCTION_GRAPH_TRACER int curr_frame = current->curr_ret_stack; extern void return_to_handler(void); unsigned long rth = (unsigned long)return_to_handler; unsigned long mrth = -1; #ifdef CONFIG_PPC64 extern void mod_return_to_handler(void); rth = *(unsigned long *)rth; mrth = (unsigned long)mod_return_to_handler; mrth = *(unsigned long *)mrth; #endif #endif sp = (unsigned long) stack; if (tsk == NULL) tsk = current; if (sp == 0) { if (tsk == current) asm("mr %0,1" : "=r" (sp)); else sp = tsk->thread.ksp; } lr = 0; printk("Call Trace:\n"); do { if (!validate_sp(sp, tsk, STACK_FRAME_OVERHEAD)) return; stack = (unsigned long *) sp; newsp = stack[0]; ip = stack[STACK_FRAME_LR_SAVE]; if (!firstframe || ip != lr) { printk("["REG"] ["REG"] %pS", sp, ip, (void *)ip); #ifdef CONFIG_FUNCTION_GRAPH_TRACER if ((ip == rth || ip == mrth) && curr_frame >= 0) { printk(" (%pS)", (void *)current->ret_stack[curr_frame].ret); curr_frame--; } #endif if (firstframe) printk(" (unreliable)"); printk("\n"); } firstframe = 0; /* * See if this is an exception frame. * We look for the "regshere" marker in the current frame. */ if (validate_sp(sp, tsk, STACK_INT_FRAME_SIZE) && stack[STACK_FRAME_MARKER] == STACK_FRAME_REGS_MARKER) { struct pt_regs *regs = (struct pt_regs *) (sp + STACK_FRAME_OVERHEAD); lr = regs->link; printk("--- Exception: %lx at %pS\n LR = %pS\n", regs->trap, (void *)regs->nip, (void *)lr); firstframe = 1; } sp = newsp; } while (count++ < kstack_depth_to_print); } #ifdef CONFIG_PPC64 /* Called with hard IRQs off */ void notrace __ppc64_runlatch_on(void) { struct thread_info *ti = current_thread_info(); unsigned long ctrl; ctrl = mfspr(SPRN_CTRLF); ctrl |= CTRL_RUNLATCH; mtspr(SPRN_CTRLT, ctrl); ti->local_flags |= _TLF_RUNLATCH; } /* Called with hard IRQs off */ void notrace __ppc64_runlatch_off(void) { struct thread_info *ti = current_thread_info(); unsigned long ctrl; ti->local_flags &= ~_TLF_RUNLATCH; ctrl = mfspr(SPRN_CTRLF); ctrl &= ~CTRL_RUNLATCH; mtspr(SPRN_CTRLT, ctrl); } #endif /* CONFIG_PPC64 */ unsigned long arch_align_stack(unsigned long sp) { if (!(current->personality & ADDR_NO_RANDOMIZE) && randomize_va_space) sp -= get_random_int() & ~PAGE_MASK; return sp & ~0xf; } static inline unsigned long brk_rnd(void) { unsigned long rnd = 0; /* 8MB for 32bit, 1GB for 64bit */ if (is_32bit_task()) rnd = (long)(get_random_int() % (1<<(23-PAGE_SHIFT))); else rnd = (long)(get_random_int() % (1<<(30-PAGE_SHIFT))); return rnd << PAGE_SHIFT; } unsigned long arch_randomize_brk(struct mm_struct *mm) { unsigned long base = mm->brk; unsigned long ret; #ifdef CONFIG_PPC_STD_MMU_64 /* * If we are using 1TB segments and we are allowed to randomise * the heap, we can put it above 1TB so it is backed by a 1TB * segment. Otherwise the heap will be in the bottom 1TB * which always uses 256MB segments and this may result in a * performance penalty. */ if (!is_32bit_task() && (mmu_highuser_ssize == MMU_SEGSIZE_1T)) base = max_t(unsigned long, mm->brk, 1UL << SID_SHIFT_1T); #endif ret = PAGE_ALIGN(base + brk_rnd()); if (ret < mm->brk) return mm->brk; return ret; } unsigned long randomize_et_dyn(unsigned long base) { unsigned long ret = PAGE_ALIGN(base + brk_rnd()); if (ret < base) return base; return ret; }
./CrossVul/dataset_final_sorted/CWE-20/c/good_2115_0
crossvul-cpp_data_bad_435_0
/* * 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, version 2 of the * License. */ #include <linux/export.h> #include <linux/nsproxy.h> #include <linux/slab.h> #include <linux/sched/signal.h> #include <linux/user_namespace.h> #include <linux/proc_ns.h> #include <linux/highuid.h> #include <linux/cred.h> #include <linux/securebits.h> #include <linux/keyctl.h> #include <linux/key-type.h> #include <keys/user-type.h> #include <linux/seq_file.h> #include <linux/fs.h> #include <linux/uaccess.h> #include <linux/ctype.h> #include <linux/projid.h> #include <linux/fs_struct.h> #include <linux/bsearch.h> #include <linux/sort.h> static struct kmem_cache *user_ns_cachep __read_mostly; static DEFINE_MUTEX(userns_state_mutex); static bool new_idmap_permitted(const struct file *file, struct user_namespace *ns, int cap_setid, struct uid_gid_map *map); static void free_user_ns(struct work_struct *work); static struct ucounts *inc_user_namespaces(struct user_namespace *ns, kuid_t uid) { return inc_ucount(ns, uid, UCOUNT_USER_NAMESPACES); } static void dec_user_namespaces(struct ucounts *ucounts) { return dec_ucount(ucounts, UCOUNT_USER_NAMESPACES); } static void set_cred_user_ns(struct cred *cred, struct user_namespace *user_ns) { /* Start with the same capabilities as init but useless for doing * anything as the capabilities are bound to the new user namespace. */ cred->securebits = SECUREBITS_DEFAULT; cred->cap_inheritable = CAP_EMPTY_SET; cred->cap_permitted = CAP_FULL_SET; cred->cap_effective = CAP_FULL_SET; cred->cap_ambient = CAP_EMPTY_SET; cred->cap_bset = CAP_FULL_SET; #ifdef CONFIG_KEYS key_put(cred->request_key_auth); cred->request_key_auth = NULL; #endif /* tgcred will be cleared in our caller bc CLONE_THREAD won't be set */ cred->user_ns = user_ns; } /* * Create a new user namespace, deriving the creator from the user in the * passed credentials, and replacing that user with the new root user for the * new namespace. * * This is called by copy_creds(), which will finish setting the target task's * credentials. */ int create_user_ns(struct cred *new) { struct user_namespace *ns, *parent_ns = new->user_ns; kuid_t owner = new->euid; kgid_t group = new->egid; struct ucounts *ucounts; int ret, i; ret = -ENOSPC; if (parent_ns->level > 32) goto fail; ucounts = inc_user_namespaces(parent_ns, owner); if (!ucounts) goto fail; /* * Verify that we can not violate the policy of which files * may be accessed that is specified by the root directory, * by verifing that the root directory is at the root of the * mount namespace which allows all files to be accessed. */ ret = -EPERM; if (current_chrooted()) goto fail_dec; /* The creator needs a mapping in the parent user namespace * or else we won't be able to reasonably tell userspace who * created a user_namespace. */ ret = -EPERM; if (!kuid_has_mapping(parent_ns, owner) || !kgid_has_mapping(parent_ns, group)) goto fail_dec; ret = -ENOMEM; ns = kmem_cache_zalloc(user_ns_cachep, GFP_KERNEL); if (!ns) goto fail_dec; ret = ns_alloc_inum(&ns->ns); if (ret) goto fail_free; ns->ns.ops = &userns_operations; atomic_set(&ns->count, 1); /* Leave the new->user_ns reference with the new user namespace. */ ns->parent = parent_ns; ns->level = parent_ns->level + 1; ns->owner = owner; ns->group = group; INIT_WORK(&ns->work, free_user_ns); for (i = 0; i < UCOUNT_COUNTS; i++) { ns->ucount_max[i] = INT_MAX; } ns->ucounts = ucounts; /* Inherit USERNS_SETGROUPS_ALLOWED from our parent */ mutex_lock(&userns_state_mutex); ns->flags = parent_ns->flags; mutex_unlock(&userns_state_mutex); #ifdef CONFIG_PERSISTENT_KEYRINGS init_rwsem(&ns->persistent_keyring_register_sem); #endif ret = -ENOMEM; if (!setup_userns_sysctls(ns)) goto fail_keyring; set_cred_user_ns(new, ns); return 0; fail_keyring: #ifdef CONFIG_PERSISTENT_KEYRINGS key_put(ns->persistent_keyring_register); #endif ns_free_inum(&ns->ns); fail_free: kmem_cache_free(user_ns_cachep, ns); fail_dec: dec_user_namespaces(ucounts); fail: return ret; } int unshare_userns(unsigned long unshare_flags, struct cred **new_cred) { struct cred *cred; int err = -ENOMEM; if (!(unshare_flags & CLONE_NEWUSER)) return 0; cred = prepare_creds(); if (cred) { err = create_user_ns(cred); if (err) put_cred(cred); else *new_cred = cred; } return err; } static void free_user_ns(struct work_struct *work) { struct user_namespace *parent, *ns = container_of(work, struct user_namespace, work); do { struct ucounts *ucounts = ns->ucounts; parent = ns->parent; if (ns->gid_map.nr_extents > UID_GID_MAP_MAX_BASE_EXTENTS) { kfree(ns->gid_map.forward); kfree(ns->gid_map.reverse); } if (ns->uid_map.nr_extents > UID_GID_MAP_MAX_BASE_EXTENTS) { kfree(ns->uid_map.forward); kfree(ns->uid_map.reverse); } if (ns->projid_map.nr_extents > UID_GID_MAP_MAX_BASE_EXTENTS) { kfree(ns->projid_map.forward); kfree(ns->projid_map.reverse); } retire_userns_sysctls(ns); #ifdef CONFIG_PERSISTENT_KEYRINGS key_put(ns->persistent_keyring_register); #endif ns_free_inum(&ns->ns); kmem_cache_free(user_ns_cachep, ns); dec_user_namespaces(ucounts); ns = parent; } while (atomic_dec_and_test(&parent->count)); } void __put_user_ns(struct user_namespace *ns) { schedule_work(&ns->work); } EXPORT_SYMBOL(__put_user_ns); /** * idmap_key struct holds the information necessary to find an idmapping in a * sorted idmap array. It is passed to cmp_map_id() as first argument. */ struct idmap_key { bool map_up; /* true -> id from kid; false -> kid from id */ u32 id; /* id to find */ u32 count; /* == 0 unless used with map_id_range_down() */ }; /** * cmp_map_id - Function to be passed to bsearch() to find the requested * idmapping. Expects struct idmap_key to be passed via @k. */ static int cmp_map_id(const void *k, const void *e) { u32 first, last, id2; const struct idmap_key *key = k; const struct uid_gid_extent *el = e; id2 = key->id + key->count - 1; /* handle map_id_{down,up}() */ if (key->map_up) first = el->lower_first; else first = el->first; last = first + el->count - 1; if (key->id >= first && key->id <= last && (id2 >= first && id2 <= last)) return 0; if (key->id < first || id2 < first) return -1; return 1; } /** * map_id_range_down_max - Find idmap via binary search in ordered idmap array. * Can only be called if number of mappings exceeds UID_GID_MAP_MAX_BASE_EXTENTS. */ static struct uid_gid_extent * map_id_range_down_max(unsigned extents, struct uid_gid_map *map, u32 id, u32 count) { struct idmap_key key; key.map_up = false; key.count = count; key.id = id; return bsearch(&key, map->forward, extents, sizeof(struct uid_gid_extent), cmp_map_id); } /** * map_id_range_down_base - Find idmap via binary search in static extent array. * Can only be called if number of mappings is equal or less than * UID_GID_MAP_MAX_BASE_EXTENTS. */ static struct uid_gid_extent * map_id_range_down_base(unsigned extents, struct uid_gid_map *map, u32 id, u32 count) { unsigned idx; u32 first, last, id2; id2 = id + count - 1; /* Find the matching extent */ for (idx = 0; idx < extents; idx++) { first = map->extent[idx].first; last = first + map->extent[idx].count - 1; if (id >= first && id <= last && (id2 >= first && id2 <= last)) return &map->extent[idx]; } return NULL; } static u32 map_id_range_down(struct uid_gid_map *map, u32 id, u32 count) { struct uid_gid_extent *extent; unsigned extents = map->nr_extents; smp_rmb(); if (extents <= UID_GID_MAP_MAX_BASE_EXTENTS) extent = map_id_range_down_base(extents, map, id, count); else extent = map_id_range_down_max(extents, map, id, count); /* Map the id or note failure */ if (extent) id = (id - extent->first) + extent->lower_first; else id = (u32) -1; return id; } static u32 map_id_down(struct uid_gid_map *map, u32 id) { return map_id_range_down(map, id, 1); } /** * map_id_up_base - Find idmap via binary search in static extent array. * Can only be called if number of mappings is equal or less than * UID_GID_MAP_MAX_BASE_EXTENTS. */ static struct uid_gid_extent * map_id_up_base(unsigned extents, struct uid_gid_map *map, u32 id) { unsigned idx; u32 first, last; /* Find the matching extent */ for (idx = 0; idx < extents; idx++) { first = map->extent[idx].lower_first; last = first + map->extent[idx].count - 1; if (id >= first && id <= last) return &map->extent[idx]; } return NULL; } /** * map_id_up_max - Find idmap via binary search in ordered idmap array. * Can only be called if number of mappings exceeds UID_GID_MAP_MAX_BASE_EXTENTS. */ static struct uid_gid_extent * map_id_up_max(unsigned extents, struct uid_gid_map *map, u32 id) { struct idmap_key key; key.map_up = true; key.count = 1; key.id = id; return bsearch(&key, map->reverse, extents, sizeof(struct uid_gid_extent), cmp_map_id); } static u32 map_id_up(struct uid_gid_map *map, u32 id) { struct uid_gid_extent *extent; unsigned extents = map->nr_extents; smp_rmb(); if (extents <= UID_GID_MAP_MAX_BASE_EXTENTS) extent = map_id_up_base(extents, map, id); else extent = map_id_up_max(extents, map, id); /* Map the id or note failure */ if (extent) id = (id - extent->lower_first) + extent->first; else id = (u32) -1; return id; } /** * make_kuid - Map a user-namespace uid pair into a kuid. * @ns: User namespace that the uid is in * @uid: User identifier * * Maps a user-namespace uid pair into a kernel internal kuid, * and returns that kuid. * * When there is no mapping defined for the user-namespace uid * pair INVALID_UID is returned. Callers are expected to test * for and handle INVALID_UID being returned. INVALID_UID * may be tested for using uid_valid(). */ kuid_t make_kuid(struct user_namespace *ns, uid_t uid) { /* Map the uid to a global kernel uid */ return KUIDT_INIT(map_id_down(&ns->uid_map, uid)); } EXPORT_SYMBOL(make_kuid); /** * from_kuid - Create a uid from a kuid user-namespace pair. * @targ: The user namespace we want a uid in. * @kuid: The kernel internal uid to start with. * * Map @kuid into the user-namespace specified by @targ and * return the resulting uid. * * There is always a mapping into the initial user_namespace. * * If @kuid has no mapping in @targ (uid_t)-1 is returned. */ uid_t from_kuid(struct user_namespace *targ, kuid_t kuid) { /* Map the uid from a global kernel uid */ return map_id_up(&targ->uid_map, __kuid_val(kuid)); } EXPORT_SYMBOL(from_kuid); /** * from_kuid_munged - Create a uid from a kuid user-namespace pair. * @targ: The user namespace we want a uid in. * @kuid: The kernel internal uid to start with. * * Map @kuid into the user-namespace specified by @targ and * return the resulting uid. * * There is always a mapping into the initial user_namespace. * * Unlike from_kuid from_kuid_munged never fails and always * returns a valid uid. This makes from_kuid_munged appropriate * for use in syscalls like stat and getuid where failing the * system call and failing to provide a valid uid are not an * options. * * If @kuid has no mapping in @targ overflowuid is returned. */ uid_t from_kuid_munged(struct user_namespace *targ, kuid_t kuid) { uid_t uid; uid = from_kuid(targ, kuid); if (uid == (uid_t) -1) uid = overflowuid; return uid; } EXPORT_SYMBOL(from_kuid_munged); /** * make_kgid - Map a user-namespace gid pair into a kgid. * @ns: User namespace that the gid is in * @gid: group identifier * * Maps a user-namespace gid pair into a kernel internal kgid, * and returns that kgid. * * When there is no mapping defined for the user-namespace gid * pair INVALID_GID is returned. Callers are expected to test * for and handle INVALID_GID being returned. INVALID_GID may be * tested for using gid_valid(). */ kgid_t make_kgid(struct user_namespace *ns, gid_t gid) { /* Map the gid to a global kernel gid */ return KGIDT_INIT(map_id_down(&ns->gid_map, gid)); } EXPORT_SYMBOL(make_kgid); /** * from_kgid - Create a gid from a kgid user-namespace pair. * @targ: The user namespace we want a gid in. * @kgid: The kernel internal gid to start with. * * Map @kgid into the user-namespace specified by @targ and * return the resulting gid. * * There is always a mapping into the initial user_namespace. * * If @kgid has no mapping in @targ (gid_t)-1 is returned. */ gid_t from_kgid(struct user_namespace *targ, kgid_t kgid) { /* Map the gid from a global kernel gid */ return map_id_up(&targ->gid_map, __kgid_val(kgid)); } EXPORT_SYMBOL(from_kgid); /** * from_kgid_munged - Create a gid from a kgid user-namespace pair. * @targ: The user namespace we want a gid in. * @kgid: The kernel internal gid to start with. * * Map @kgid into the user-namespace specified by @targ and * return the resulting gid. * * There is always a mapping into the initial user_namespace. * * Unlike from_kgid from_kgid_munged never fails and always * returns a valid gid. This makes from_kgid_munged appropriate * for use in syscalls like stat and getgid where failing the * system call and failing to provide a valid gid are not options. * * If @kgid has no mapping in @targ overflowgid is returned. */ gid_t from_kgid_munged(struct user_namespace *targ, kgid_t kgid) { gid_t gid; gid = from_kgid(targ, kgid); if (gid == (gid_t) -1) gid = overflowgid; return gid; } EXPORT_SYMBOL(from_kgid_munged); /** * make_kprojid - Map a user-namespace projid pair into a kprojid. * @ns: User namespace that the projid is in * @projid: Project identifier * * Maps a user-namespace uid pair into a kernel internal kuid, * and returns that kuid. * * When there is no mapping defined for the user-namespace projid * pair INVALID_PROJID is returned. Callers are expected to test * for and handle handle INVALID_PROJID being returned. INVALID_PROJID * may be tested for using projid_valid(). */ kprojid_t make_kprojid(struct user_namespace *ns, projid_t projid) { /* Map the uid to a global kernel uid */ return KPROJIDT_INIT(map_id_down(&ns->projid_map, projid)); } EXPORT_SYMBOL(make_kprojid); /** * from_kprojid - Create a projid from a kprojid user-namespace pair. * @targ: The user namespace we want a projid in. * @kprojid: The kernel internal project identifier to start with. * * Map @kprojid into the user-namespace specified by @targ and * return the resulting projid. * * There is always a mapping into the initial user_namespace. * * If @kprojid has no mapping in @targ (projid_t)-1 is returned. */ projid_t from_kprojid(struct user_namespace *targ, kprojid_t kprojid) { /* Map the uid from a global kernel uid */ return map_id_up(&targ->projid_map, __kprojid_val(kprojid)); } EXPORT_SYMBOL(from_kprojid); /** * from_kprojid_munged - Create a projiid from a kprojid user-namespace pair. * @targ: The user namespace we want a projid in. * @kprojid: The kernel internal projid to start with. * * Map @kprojid into the user-namespace specified by @targ and * return the resulting projid. * * There is always a mapping into the initial user_namespace. * * Unlike from_kprojid from_kprojid_munged never fails and always * returns a valid projid. This makes from_kprojid_munged * appropriate for use in syscalls like stat and where * failing the system call and failing to provide a valid projid are * not an options. * * If @kprojid has no mapping in @targ OVERFLOW_PROJID is returned. */ projid_t from_kprojid_munged(struct user_namespace *targ, kprojid_t kprojid) { projid_t projid; projid = from_kprojid(targ, kprojid); if (projid == (projid_t) -1) projid = OVERFLOW_PROJID; return projid; } EXPORT_SYMBOL(from_kprojid_munged); static int uid_m_show(struct seq_file *seq, void *v) { struct user_namespace *ns = seq->private; struct uid_gid_extent *extent = v; struct user_namespace *lower_ns; uid_t lower; lower_ns = seq_user_ns(seq); if ((lower_ns == ns) && lower_ns->parent) lower_ns = lower_ns->parent; lower = from_kuid(lower_ns, KUIDT_INIT(extent->lower_first)); seq_printf(seq, "%10u %10u %10u\n", extent->first, lower, extent->count); return 0; } static int gid_m_show(struct seq_file *seq, void *v) { struct user_namespace *ns = seq->private; struct uid_gid_extent *extent = v; struct user_namespace *lower_ns; gid_t lower; lower_ns = seq_user_ns(seq); if ((lower_ns == ns) && lower_ns->parent) lower_ns = lower_ns->parent; lower = from_kgid(lower_ns, KGIDT_INIT(extent->lower_first)); seq_printf(seq, "%10u %10u %10u\n", extent->first, lower, extent->count); return 0; } static int projid_m_show(struct seq_file *seq, void *v) { struct user_namespace *ns = seq->private; struct uid_gid_extent *extent = v; struct user_namespace *lower_ns; projid_t lower; lower_ns = seq_user_ns(seq); if ((lower_ns == ns) && lower_ns->parent) lower_ns = lower_ns->parent; lower = from_kprojid(lower_ns, KPROJIDT_INIT(extent->lower_first)); seq_printf(seq, "%10u %10u %10u\n", extent->first, lower, extent->count); return 0; } static void *m_start(struct seq_file *seq, loff_t *ppos, struct uid_gid_map *map) { loff_t pos = *ppos; unsigned extents = map->nr_extents; smp_rmb(); if (pos >= extents) return NULL; if (extents <= UID_GID_MAP_MAX_BASE_EXTENTS) return &map->extent[pos]; return &map->forward[pos]; } static void *uid_m_start(struct seq_file *seq, loff_t *ppos) { struct user_namespace *ns = seq->private; return m_start(seq, ppos, &ns->uid_map); } static void *gid_m_start(struct seq_file *seq, loff_t *ppos) { struct user_namespace *ns = seq->private; return m_start(seq, ppos, &ns->gid_map); } static void *projid_m_start(struct seq_file *seq, loff_t *ppos) { struct user_namespace *ns = seq->private; return m_start(seq, ppos, &ns->projid_map); } static void *m_next(struct seq_file *seq, void *v, loff_t *pos) { (*pos)++; return seq->op->start(seq, pos); } static void m_stop(struct seq_file *seq, void *v) { return; } const struct seq_operations proc_uid_seq_operations = { .start = uid_m_start, .stop = m_stop, .next = m_next, .show = uid_m_show, }; const struct seq_operations proc_gid_seq_operations = { .start = gid_m_start, .stop = m_stop, .next = m_next, .show = gid_m_show, }; const struct seq_operations proc_projid_seq_operations = { .start = projid_m_start, .stop = m_stop, .next = m_next, .show = projid_m_show, }; static bool mappings_overlap(struct uid_gid_map *new_map, struct uid_gid_extent *extent) { u32 upper_first, lower_first, upper_last, lower_last; unsigned idx; upper_first = extent->first; lower_first = extent->lower_first; upper_last = upper_first + extent->count - 1; lower_last = lower_first + extent->count - 1; for (idx = 0; idx < new_map->nr_extents; idx++) { u32 prev_upper_first, prev_lower_first; u32 prev_upper_last, prev_lower_last; struct uid_gid_extent *prev; if (new_map->nr_extents <= UID_GID_MAP_MAX_BASE_EXTENTS) prev = &new_map->extent[idx]; else prev = &new_map->forward[idx]; prev_upper_first = prev->first; prev_lower_first = prev->lower_first; prev_upper_last = prev_upper_first + prev->count - 1; prev_lower_last = prev_lower_first + prev->count - 1; /* Does the upper range intersect a previous extent? */ if ((prev_upper_first <= upper_last) && (prev_upper_last >= upper_first)) return true; /* Does the lower range intersect a previous extent? */ if ((prev_lower_first <= lower_last) && (prev_lower_last >= lower_first)) return true; } return false; } /** * insert_extent - Safely insert a new idmap extent into struct uid_gid_map. * Takes care to allocate a 4K block of memory if the number of mappings exceeds * UID_GID_MAP_MAX_BASE_EXTENTS. */ static int insert_extent(struct uid_gid_map *map, struct uid_gid_extent *extent) { struct uid_gid_extent *dest; if (map->nr_extents == UID_GID_MAP_MAX_BASE_EXTENTS) { struct uid_gid_extent *forward; /* Allocate memory for 340 mappings. */ forward = kmalloc_array(UID_GID_MAP_MAX_EXTENTS, sizeof(struct uid_gid_extent), GFP_KERNEL); if (!forward) return -ENOMEM; /* Copy over memory. Only set up memory for the forward pointer. * Defer the memory setup for the reverse pointer. */ memcpy(forward, map->extent, map->nr_extents * sizeof(map->extent[0])); map->forward = forward; map->reverse = NULL; } if (map->nr_extents < UID_GID_MAP_MAX_BASE_EXTENTS) dest = &map->extent[map->nr_extents]; else dest = &map->forward[map->nr_extents]; *dest = *extent; map->nr_extents++; return 0; } /* cmp function to sort() forward mappings */ static int cmp_extents_forward(const void *a, const void *b) { const struct uid_gid_extent *e1 = a; const struct uid_gid_extent *e2 = b; if (e1->first < e2->first) return -1; if (e1->first > e2->first) return 1; return 0; } /* cmp function to sort() reverse mappings */ static int cmp_extents_reverse(const void *a, const void *b) { const struct uid_gid_extent *e1 = a; const struct uid_gid_extent *e2 = b; if (e1->lower_first < e2->lower_first) return -1; if (e1->lower_first > e2->lower_first) return 1; return 0; } /** * sort_idmaps - Sorts an array of idmap entries. * Can only be called if number of mappings exceeds UID_GID_MAP_MAX_BASE_EXTENTS. */ static int sort_idmaps(struct uid_gid_map *map) { if (map->nr_extents <= UID_GID_MAP_MAX_BASE_EXTENTS) return 0; /* Sort forward array. */ sort(map->forward, map->nr_extents, sizeof(struct uid_gid_extent), cmp_extents_forward, NULL); /* Only copy the memory from forward we actually need. */ map->reverse = kmemdup(map->forward, map->nr_extents * sizeof(struct uid_gid_extent), GFP_KERNEL); if (!map->reverse) return -ENOMEM; /* Sort reverse array. */ sort(map->reverse, map->nr_extents, sizeof(struct uid_gid_extent), cmp_extents_reverse, NULL); return 0; } static ssize_t map_write(struct file *file, const char __user *buf, size_t count, loff_t *ppos, int cap_setid, struct uid_gid_map *map, struct uid_gid_map *parent_map) { struct seq_file *seq = file->private_data; struct user_namespace *ns = seq->private; struct uid_gid_map new_map; unsigned idx; struct uid_gid_extent extent; char *kbuf = NULL, *pos, *next_line; ssize_t ret; /* Only allow < page size writes at the beginning of the file */ if ((*ppos != 0) || (count >= PAGE_SIZE)) return -EINVAL; /* Slurp in the user data */ kbuf = memdup_user_nul(buf, count); if (IS_ERR(kbuf)) return PTR_ERR(kbuf); /* * The userns_state_mutex serializes all writes to any given map. * * Any map is only ever written once. * * An id map fits within 1 cache line on most architectures. * * On read nothing needs to be done unless you are on an * architecture with a crazy cache coherency model like alpha. * * There is a one time data dependency between reading the * count of the extents and the values of the extents. The * desired behavior is to see the values of the extents that * were written before the count of the extents. * * To achieve this smp_wmb() is used on guarantee the write * order and smp_rmb() is guaranteed that we don't have crazy * architectures returning stale data. */ mutex_lock(&userns_state_mutex); memset(&new_map, 0, sizeof(struct uid_gid_map)); ret = -EPERM; /* Only allow one successful write to the map */ if (map->nr_extents != 0) goto out; /* * Adjusting namespace settings requires capabilities on the target. */ if (cap_valid(cap_setid) && !file_ns_capable(file, ns, CAP_SYS_ADMIN)) goto out; /* Parse the user data */ ret = -EINVAL; pos = kbuf; for (; pos; pos = next_line) { /* Find the end of line and ensure I don't look past it */ next_line = strchr(pos, '\n'); if (next_line) { *next_line = '\0'; next_line++; if (*next_line == '\0') next_line = NULL; } pos = skip_spaces(pos); extent.first = simple_strtoul(pos, &pos, 10); if (!isspace(*pos)) goto out; pos = skip_spaces(pos); extent.lower_first = simple_strtoul(pos, &pos, 10); if (!isspace(*pos)) goto out; pos = skip_spaces(pos); extent.count = simple_strtoul(pos, &pos, 10); if (*pos && !isspace(*pos)) goto out; /* Verify there is not trailing junk on the line */ pos = skip_spaces(pos); if (*pos != '\0') goto out; /* Verify we have been given valid starting values */ if ((extent.first == (u32) -1) || (extent.lower_first == (u32) -1)) goto out; /* Verify count is not zero and does not cause the * extent to wrap */ if ((extent.first + extent.count) <= extent.first) goto out; if ((extent.lower_first + extent.count) <= extent.lower_first) goto out; /* Do the ranges in extent overlap any previous extents? */ if (mappings_overlap(&new_map, &extent)) goto out; if ((new_map.nr_extents + 1) == UID_GID_MAP_MAX_EXTENTS && (next_line != NULL)) goto out; ret = insert_extent(&new_map, &extent); if (ret < 0) goto out; ret = -EINVAL; } /* Be very certaint the new map actually exists */ if (new_map.nr_extents == 0) goto out; ret = -EPERM; /* Validate the user is allowed to use user id's mapped to. */ if (!new_idmap_permitted(file, ns, cap_setid, &new_map)) goto out; ret = sort_idmaps(&new_map); if (ret < 0) goto out; ret = -EPERM; /* Map the lower ids from the parent user namespace to the * kernel global id space. */ for (idx = 0; idx < new_map.nr_extents; idx++) { struct uid_gid_extent *e; u32 lower_first; if (new_map.nr_extents <= UID_GID_MAP_MAX_BASE_EXTENTS) e = &new_map.extent[idx]; else e = &new_map.forward[idx]; lower_first = map_id_range_down(parent_map, e->lower_first, e->count); /* Fail if we can not map the specified extent to * the kernel global id space. */ if (lower_first == (u32) -1) goto out; e->lower_first = lower_first; } /* Install the map */ if (new_map.nr_extents <= UID_GID_MAP_MAX_BASE_EXTENTS) { memcpy(map->extent, new_map.extent, new_map.nr_extents * sizeof(new_map.extent[0])); } else { map->forward = new_map.forward; map->reverse = new_map.reverse; } smp_wmb(); map->nr_extents = new_map.nr_extents; *ppos = count; ret = count; out: if (ret < 0 && new_map.nr_extents > UID_GID_MAP_MAX_BASE_EXTENTS) { kfree(new_map.forward); kfree(new_map.reverse); map->forward = NULL; map->reverse = NULL; map->nr_extents = 0; } mutex_unlock(&userns_state_mutex); kfree(kbuf); return ret; } ssize_t proc_uid_map_write(struct file *file, const char __user *buf, size_t size, loff_t *ppos) { struct seq_file *seq = file->private_data; struct user_namespace *ns = seq->private; struct user_namespace *seq_ns = seq_user_ns(seq); if (!ns->parent) return -EPERM; if ((seq_ns != ns) && (seq_ns != ns->parent)) return -EPERM; return map_write(file, buf, size, ppos, CAP_SETUID, &ns->uid_map, &ns->parent->uid_map); } ssize_t proc_gid_map_write(struct file *file, const char __user *buf, size_t size, loff_t *ppos) { struct seq_file *seq = file->private_data; struct user_namespace *ns = seq->private; struct user_namespace *seq_ns = seq_user_ns(seq); if (!ns->parent) return -EPERM; if ((seq_ns != ns) && (seq_ns != ns->parent)) return -EPERM; return map_write(file, buf, size, ppos, CAP_SETGID, &ns->gid_map, &ns->parent->gid_map); } ssize_t proc_projid_map_write(struct file *file, const char __user *buf, size_t size, loff_t *ppos) { struct seq_file *seq = file->private_data; struct user_namespace *ns = seq->private; struct user_namespace *seq_ns = seq_user_ns(seq); if (!ns->parent) return -EPERM; if ((seq_ns != ns) && (seq_ns != ns->parent)) return -EPERM; /* Anyone can set any valid project id no capability needed */ return map_write(file, buf, size, ppos, -1, &ns->projid_map, &ns->parent->projid_map); } static bool new_idmap_permitted(const struct file *file, struct user_namespace *ns, int cap_setid, struct uid_gid_map *new_map) { const struct cred *cred = file->f_cred; /* Don't allow mappings that would allow anything that wouldn't * be allowed without the establishment of unprivileged mappings. */ if ((new_map->nr_extents == 1) && (new_map->extent[0].count == 1) && uid_eq(ns->owner, cred->euid)) { u32 id = new_map->extent[0].lower_first; if (cap_setid == CAP_SETUID) { kuid_t uid = make_kuid(ns->parent, id); if (uid_eq(uid, cred->euid)) return true; } else if (cap_setid == CAP_SETGID) { kgid_t gid = make_kgid(ns->parent, id); if (!(ns->flags & USERNS_SETGROUPS_ALLOWED) && gid_eq(gid, cred->egid)) return true; } } /* Allow anyone to set a mapping that doesn't require privilege */ if (!cap_valid(cap_setid)) return true; /* Allow the specified ids if we have the appropriate capability * (CAP_SETUID or CAP_SETGID) over the parent user namespace. * And the opener of the id file also had the approprpiate capability. */ if (ns_capable(ns->parent, cap_setid) && file_ns_capable(file, ns->parent, cap_setid)) return true; return false; } int proc_setgroups_show(struct seq_file *seq, void *v) { struct user_namespace *ns = seq->private; unsigned long userns_flags = READ_ONCE(ns->flags); seq_printf(seq, "%s\n", (userns_flags & USERNS_SETGROUPS_ALLOWED) ? "allow" : "deny"); return 0; } ssize_t proc_setgroups_write(struct file *file, const char __user *buf, size_t count, loff_t *ppos) { struct seq_file *seq = file->private_data; struct user_namespace *ns = seq->private; char kbuf[8], *pos; bool setgroups_allowed; ssize_t ret; /* Only allow a very narrow range of strings to be written */ ret = -EINVAL; if ((*ppos != 0) || (count >= sizeof(kbuf))) goto out; /* What was written? */ ret = -EFAULT; if (copy_from_user(kbuf, buf, count)) goto out; kbuf[count] = '\0'; pos = kbuf; /* What is being requested? */ ret = -EINVAL; if (strncmp(pos, "allow", 5) == 0) { pos += 5; setgroups_allowed = true; } else if (strncmp(pos, "deny", 4) == 0) { pos += 4; setgroups_allowed = false; } else goto out; /* Verify there is not trailing junk on the line */ pos = skip_spaces(pos); if (*pos != '\0') goto out; ret = -EPERM; mutex_lock(&userns_state_mutex); if (setgroups_allowed) { /* Enabling setgroups after setgroups has been disabled * is not allowed. */ if (!(ns->flags & USERNS_SETGROUPS_ALLOWED)) goto out_unlock; } else { /* Permanently disabling setgroups after setgroups has * been enabled by writing the gid_map is not allowed. */ if (ns->gid_map.nr_extents != 0) goto out_unlock; ns->flags &= ~USERNS_SETGROUPS_ALLOWED; } mutex_unlock(&userns_state_mutex); /* Report a successful write */ *ppos = count; ret = count; out: return ret; out_unlock: mutex_unlock(&userns_state_mutex); goto out; } bool userns_may_setgroups(const struct user_namespace *ns) { bool allowed; mutex_lock(&userns_state_mutex); /* It is not safe to use setgroups until a gid mapping in * the user namespace has been established. */ allowed = ns->gid_map.nr_extents != 0; /* Is setgroups allowed? */ allowed = allowed && (ns->flags & USERNS_SETGROUPS_ALLOWED); mutex_unlock(&userns_state_mutex); return allowed; } /* * Returns true if @child is the same namespace or a descendant of * @ancestor. */ bool in_userns(const struct user_namespace *ancestor, const struct user_namespace *child) { const struct user_namespace *ns; for (ns = child; ns->level > ancestor->level; ns = ns->parent) ; return (ns == ancestor); } bool current_in_userns(const struct user_namespace *target_ns) { return in_userns(target_ns, current_user_ns()); } EXPORT_SYMBOL(current_in_userns); static inline struct user_namespace *to_user_ns(struct ns_common *ns) { return container_of(ns, struct user_namespace, ns); } static struct ns_common *userns_get(struct task_struct *task) { struct user_namespace *user_ns; rcu_read_lock(); user_ns = get_user_ns(__task_cred(task)->user_ns); rcu_read_unlock(); return user_ns ? &user_ns->ns : NULL; } static void userns_put(struct ns_common *ns) { put_user_ns(to_user_ns(ns)); } static int userns_install(struct nsproxy *nsproxy, struct ns_common *ns) { struct user_namespace *user_ns = to_user_ns(ns); struct cred *cred; /* Don't allow gaining capabilities by reentering * the same user namespace. */ if (user_ns == current_user_ns()) return -EINVAL; /* Tasks that share a thread group must share a user namespace */ if (!thread_group_empty(current)) return -EINVAL; if (current->fs->users != 1) return -EINVAL; if (!ns_capable(user_ns, CAP_SYS_ADMIN)) return -EPERM; cred = prepare_creds(); if (!cred) return -ENOMEM; put_user_ns(cred->user_ns); set_cred_user_ns(cred, get_user_ns(user_ns)); return commit_creds(cred); } struct ns_common *ns_get_owner(struct ns_common *ns) { struct user_namespace *my_user_ns = current_user_ns(); struct user_namespace *owner, *p; /* See if the owner is in the current user namespace */ owner = p = ns->ops->owner(ns); for (;;) { if (!p) return ERR_PTR(-EPERM); if (p == my_user_ns) break; p = p->parent; } return &get_user_ns(owner)->ns; } static struct user_namespace *userns_owner(struct ns_common *ns) { return to_user_ns(ns)->parent; } const struct proc_ns_operations userns_operations = { .name = "user", .type = CLONE_NEWUSER, .get = userns_get, .put = userns_put, .install = userns_install, .owner = userns_owner, .get_parent = ns_get_owner, }; static __init int user_namespaces_init(void) { user_ns_cachep = KMEM_CACHE(user_namespace, SLAB_PANIC); return 0; } subsys_initcall(user_namespaces_init);
./CrossVul/dataset_final_sorted/CWE-20/c/bad_435_0
crossvul-cpp_data_bad_5845_26
/* * Copyright (c) 2006 Oracle. All rights reserved. * * This software is available to you under a choice of one of two * licenses. You may choose to be licensed under the terms of the GNU * General Public License (GPL) Version 2, available from the file * COPYING in the main directory of this source tree, or the * OpenIB.org BSD license below: * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * - Redistributions of source code must retain the above * copyright notice, this list of conditions and the following * disclaimer. * * - Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ #include <linux/kernel.h> #include <linux/slab.h> #include <net/sock.h> #include <linux/in.h> #include <linux/export.h> #include "rds.h" void rds_inc_init(struct rds_incoming *inc, struct rds_connection *conn, __be32 saddr) { atomic_set(&inc->i_refcount, 1); INIT_LIST_HEAD(&inc->i_item); inc->i_conn = conn; inc->i_saddr = saddr; inc->i_rdma_cookie = 0; } EXPORT_SYMBOL_GPL(rds_inc_init); static void rds_inc_addref(struct rds_incoming *inc) { rdsdebug("addref inc %p ref %d\n", inc, atomic_read(&inc->i_refcount)); atomic_inc(&inc->i_refcount); } void rds_inc_put(struct rds_incoming *inc) { rdsdebug("put inc %p ref %d\n", inc, atomic_read(&inc->i_refcount)); if (atomic_dec_and_test(&inc->i_refcount)) { BUG_ON(!list_empty(&inc->i_item)); inc->i_conn->c_trans->inc_free(inc); } } EXPORT_SYMBOL_GPL(rds_inc_put); static void rds_recv_rcvbuf_delta(struct rds_sock *rs, struct sock *sk, struct rds_cong_map *map, int delta, __be16 port) { int now_congested; if (delta == 0) return; rs->rs_rcv_bytes += delta; now_congested = rs->rs_rcv_bytes > rds_sk_rcvbuf(rs); rdsdebug("rs %p (%pI4:%u) recv bytes %d buf %d " "now_cong %d delta %d\n", rs, &rs->rs_bound_addr, ntohs(rs->rs_bound_port), rs->rs_rcv_bytes, rds_sk_rcvbuf(rs), now_congested, delta); /* wasn't -> am congested */ if (!rs->rs_congested && now_congested) { rs->rs_congested = 1; rds_cong_set_bit(map, port); rds_cong_queue_updates(map); } /* was -> aren't congested */ /* Require more free space before reporting uncongested to prevent bouncing cong/uncong state too often */ else if (rs->rs_congested && (rs->rs_rcv_bytes < (rds_sk_rcvbuf(rs)/2))) { rs->rs_congested = 0; rds_cong_clear_bit(map, port); rds_cong_queue_updates(map); } /* do nothing if no change in cong state */ } /* * Process all extension headers that come with this message. */ static void rds_recv_incoming_exthdrs(struct rds_incoming *inc, struct rds_sock *rs) { struct rds_header *hdr = &inc->i_hdr; unsigned int pos = 0, type, len; union { struct rds_ext_header_version version; struct rds_ext_header_rdma rdma; struct rds_ext_header_rdma_dest rdma_dest; } buffer; while (1) { len = sizeof(buffer); type = rds_message_next_extension(hdr, &pos, &buffer, &len); if (type == RDS_EXTHDR_NONE) break; /* Process extension header here */ switch (type) { case RDS_EXTHDR_RDMA: rds_rdma_unuse(rs, be32_to_cpu(buffer.rdma.h_rdma_rkey), 0); break; case RDS_EXTHDR_RDMA_DEST: /* We ignore the size for now. We could stash it * somewhere and use it for error checking. */ inc->i_rdma_cookie = rds_rdma_make_cookie( be32_to_cpu(buffer.rdma_dest.h_rdma_rkey), be32_to_cpu(buffer.rdma_dest.h_rdma_offset)); break; } } } /* * The transport must make sure that this is serialized against other * rx and conn reset on this specific conn. * * We currently assert that only one fragmented message will be sent * down a connection at a time. This lets us reassemble in the conn * instead of per-flow which means that we don't have to go digging through * flows to tear down partial reassembly progress on conn failure and * we save flow lookup and locking for each frag arrival. It does mean * that small messages will wait behind large ones. Fragmenting at all * is only to reduce the memory consumption of pre-posted buffers. * * The caller passes in saddr and daddr instead of us getting it from the * conn. This lets loopback, who only has one conn for both directions, * tell us which roles the addrs in the conn are playing for this message. */ void rds_recv_incoming(struct rds_connection *conn, __be32 saddr, __be32 daddr, struct rds_incoming *inc, gfp_t gfp) { struct rds_sock *rs = NULL; struct sock *sk; unsigned long flags; inc->i_conn = conn; inc->i_rx_jiffies = jiffies; rdsdebug("conn %p next %llu inc %p seq %llu len %u sport %u dport %u " "flags 0x%x rx_jiffies %lu\n", conn, (unsigned long long)conn->c_next_rx_seq, inc, (unsigned long long)be64_to_cpu(inc->i_hdr.h_sequence), be32_to_cpu(inc->i_hdr.h_len), be16_to_cpu(inc->i_hdr.h_sport), be16_to_cpu(inc->i_hdr.h_dport), inc->i_hdr.h_flags, inc->i_rx_jiffies); /* * Sequence numbers should only increase. Messages get their * sequence number as they're queued in a sending conn. They * can be dropped, though, if the sending socket is closed before * they hit the wire. So sequence numbers can skip forward * under normal operation. They can also drop back in the conn * failover case as previously sent messages are resent down the * new instance of a conn. We drop those, otherwise we have * to assume that the next valid seq does not come after a * hole in the fragment stream. * * The headers don't give us a way to realize if fragments of * a message have been dropped. We assume that frags that arrive * to a flow are part of the current message on the flow that is * being reassembled. This means that senders can't drop messages * from the sending conn until all their frags are sent. * * XXX we could spend more on the wire to get more robust failure * detection, arguably worth it to avoid data corruption. */ if (be64_to_cpu(inc->i_hdr.h_sequence) < conn->c_next_rx_seq && (inc->i_hdr.h_flags & RDS_FLAG_RETRANSMITTED)) { rds_stats_inc(s_recv_drop_old_seq); goto out; } conn->c_next_rx_seq = be64_to_cpu(inc->i_hdr.h_sequence) + 1; if (rds_sysctl_ping_enable && inc->i_hdr.h_dport == 0) { rds_stats_inc(s_recv_ping); rds_send_pong(conn, inc->i_hdr.h_sport); goto out; } rs = rds_find_bound(daddr, inc->i_hdr.h_dport); if (!rs) { rds_stats_inc(s_recv_drop_no_sock); goto out; } /* Process extension headers */ rds_recv_incoming_exthdrs(inc, rs); /* We can be racing with rds_release() which marks the socket dead. */ sk = rds_rs_to_sk(rs); /* serialize with rds_release -> sock_orphan */ write_lock_irqsave(&rs->rs_recv_lock, flags); if (!sock_flag(sk, SOCK_DEAD)) { rdsdebug("adding inc %p to rs %p's recv queue\n", inc, rs); rds_stats_inc(s_recv_queued); rds_recv_rcvbuf_delta(rs, sk, inc->i_conn->c_lcong, be32_to_cpu(inc->i_hdr.h_len), inc->i_hdr.h_dport); rds_inc_addref(inc); list_add_tail(&inc->i_item, &rs->rs_recv_queue); __rds_wake_sk_sleep(sk); } else { rds_stats_inc(s_recv_drop_dead_sock); } write_unlock_irqrestore(&rs->rs_recv_lock, flags); out: if (rs) rds_sock_put(rs); } EXPORT_SYMBOL_GPL(rds_recv_incoming); /* * be very careful here. This is being called as the condition in * wait_event_*() needs to cope with being called many times. */ static int rds_next_incoming(struct rds_sock *rs, struct rds_incoming **inc) { unsigned long flags; if (!*inc) { read_lock_irqsave(&rs->rs_recv_lock, flags); if (!list_empty(&rs->rs_recv_queue)) { *inc = list_entry(rs->rs_recv_queue.next, struct rds_incoming, i_item); rds_inc_addref(*inc); } read_unlock_irqrestore(&rs->rs_recv_lock, flags); } return *inc != NULL; } static int rds_still_queued(struct rds_sock *rs, struct rds_incoming *inc, int drop) { struct sock *sk = rds_rs_to_sk(rs); int ret = 0; unsigned long flags; write_lock_irqsave(&rs->rs_recv_lock, flags); if (!list_empty(&inc->i_item)) { ret = 1; if (drop) { /* XXX make sure this i_conn is reliable */ rds_recv_rcvbuf_delta(rs, sk, inc->i_conn->c_lcong, -be32_to_cpu(inc->i_hdr.h_len), inc->i_hdr.h_dport); list_del_init(&inc->i_item); rds_inc_put(inc); } } write_unlock_irqrestore(&rs->rs_recv_lock, flags); rdsdebug("inc %p rs %p still %d dropped %d\n", inc, rs, ret, drop); return ret; } /* * Pull errors off the error queue. * If msghdr is NULL, we will just purge the error queue. */ int rds_notify_queue_get(struct rds_sock *rs, struct msghdr *msghdr) { struct rds_notifier *notifier; struct rds_rdma_notify cmsg = { 0 }; /* fill holes with zero */ unsigned int count = 0, max_messages = ~0U; unsigned long flags; LIST_HEAD(copy); int err = 0; /* put_cmsg copies to user space and thus may sleep. We can't do this * with rs_lock held, so first grab as many notifications as we can stuff * in the user provided cmsg buffer. We don't try to copy more, to avoid * losing notifications - except when the buffer is so small that it wouldn't * even hold a single notification. Then we give him as much of this single * msg as we can squeeze in, and set MSG_CTRUNC. */ if (msghdr) { max_messages = msghdr->msg_controllen / CMSG_SPACE(sizeof(cmsg)); if (!max_messages) max_messages = 1; } spin_lock_irqsave(&rs->rs_lock, flags); while (!list_empty(&rs->rs_notify_queue) && count < max_messages) { notifier = list_entry(rs->rs_notify_queue.next, struct rds_notifier, n_list); list_move(&notifier->n_list, &copy); count++; } spin_unlock_irqrestore(&rs->rs_lock, flags); if (!count) return 0; while (!list_empty(&copy)) { notifier = list_entry(copy.next, struct rds_notifier, n_list); if (msghdr) { cmsg.user_token = notifier->n_user_token; cmsg.status = notifier->n_status; err = put_cmsg(msghdr, SOL_RDS, RDS_CMSG_RDMA_STATUS, sizeof(cmsg), &cmsg); if (err) break; } list_del_init(&notifier->n_list); kfree(notifier); } /* If we bailed out because of an error in put_cmsg, * we may be left with one or more notifications that we * didn't process. Return them to the head of the list. */ if (!list_empty(&copy)) { spin_lock_irqsave(&rs->rs_lock, flags); list_splice(&copy, &rs->rs_notify_queue); spin_unlock_irqrestore(&rs->rs_lock, flags); } return err; } /* * Queue a congestion notification */ static int rds_notify_cong(struct rds_sock *rs, struct msghdr *msghdr) { uint64_t notify = rs->rs_cong_notify; unsigned long flags; int err; err = put_cmsg(msghdr, SOL_RDS, RDS_CMSG_CONG_UPDATE, sizeof(notify), &notify); if (err) return err; spin_lock_irqsave(&rs->rs_lock, flags); rs->rs_cong_notify &= ~notify; spin_unlock_irqrestore(&rs->rs_lock, flags); return 0; } /* * Receive any control messages. */ static int rds_cmsg_recv(struct rds_incoming *inc, struct msghdr *msg) { int ret = 0; if (inc->i_rdma_cookie) { ret = put_cmsg(msg, SOL_RDS, RDS_CMSG_RDMA_DEST, sizeof(inc->i_rdma_cookie), &inc->i_rdma_cookie); if (ret) return ret; } return 0; } int rds_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t size, int msg_flags) { struct sock *sk = sock->sk; struct rds_sock *rs = rds_sk_to_rs(sk); long timeo; int ret = 0, nonblock = msg_flags & MSG_DONTWAIT; struct sockaddr_in *sin; struct rds_incoming *inc = NULL; /* udp_recvmsg()->sock_recvtimeo() gets away without locking too.. */ timeo = sock_rcvtimeo(sk, nonblock); rdsdebug("size %zu flags 0x%x timeo %ld\n", size, msg_flags, timeo); msg->msg_namelen = 0; if (msg_flags & MSG_OOB) goto out; while (1) { /* If there are pending notifications, do those - and nothing else */ if (!list_empty(&rs->rs_notify_queue)) { ret = rds_notify_queue_get(rs, msg); break; } if (rs->rs_cong_notify) { ret = rds_notify_cong(rs, msg); break; } if (!rds_next_incoming(rs, &inc)) { if (nonblock) { ret = -EAGAIN; break; } timeo = wait_event_interruptible_timeout(*sk_sleep(sk), (!list_empty(&rs->rs_notify_queue) || rs->rs_cong_notify || rds_next_incoming(rs, &inc)), timeo); rdsdebug("recvmsg woke inc %p timeo %ld\n", inc, timeo); if (timeo > 0 || timeo == MAX_SCHEDULE_TIMEOUT) continue; ret = timeo; if (ret == 0) ret = -ETIMEDOUT; break; } rdsdebug("copying inc %p from %pI4:%u to user\n", inc, &inc->i_conn->c_faddr, ntohs(inc->i_hdr.h_sport)); ret = inc->i_conn->c_trans->inc_copy_to_user(inc, msg->msg_iov, size); if (ret < 0) break; /* * if the message we just copied isn't at the head of the * recv queue then someone else raced us to return it, try * to get the next message. */ if (!rds_still_queued(rs, inc, !(msg_flags & MSG_PEEK))) { rds_inc_put(inc); inc = NULL; rds_stats_inc(s_recv_deliver_raced); continue; } if (ret < be32_to_cpu(inc->i_hdr.h_len)) { if (msg_flags & MSG_TRUNC) ret = be32_to_cpu(inc->i_hdr.h_len); msg->msg_flags |= MSG_TRUNC; } if (rds_cmsg_recv(inc, msg)) { ret = -EFAULT; goto out; } rds_stats_inc(s_recv_delivered); sin = (struct sockaddr_in *)msg->msg_name; if (sin) { sin->sin_family = AF_INET; sin->sin_port = inc->i_hdr.h_sport; sin->sin_addr.s_addr = inc->i_saddr; memset(sin->sin_zero, 0, sizeof(sin->sin_zero)); msg->msg_namelen = sizeof(*sin); } break; } if (inc) rds_inc_put(inc); out: return ret; } /* * The socket is being shut down and we're asked to drop messages that were * queued for recvmsg. The caller has unbound the socket so the receive path * won't queue any more incoming fragments or messages on the socket. */ void rds_clear_recv_queue(struct rds_sock *rs) { struct sock *sk = rds_rs_to_sk(rs); struct rds_incoming *inc, *tmp; unsigned long flags; write_lock_irqsave(&rs->rs_recv_lock, flags); list_for_each_entry_safe(inc, tmp, &rs->rs_recv_queue, i_item) { rds_recv_rcvbuf_delta(rs, sk, inc->i_conn->c_lcong, -be32_to_cpu(inc->i_hdr.h_len), inc->i_hdr.h_dport); list_del_init(&inc->i_item); rds_inc_put(inc); } write_unlock_irqrestore(&rs->rs_recv_lock, flags); } /* * inc->i_saddr isn't used here because it is only set in the receive * path. */ void rds_inc_info_copy(struct rds_incoming *inc, struct rds_info_iterator *iter, __be32 saddr, __be32 daddr, int flip) { struct rds_info_message minfo; minfo.seq = be64_to_cpu(inc->i_hdr.h_sequence); minfo.len = be32_to_cpu(inc->i_hdr.h_len); if (flip) { minfo.laddr = daddr; minfo.faddr = saddr; minfo.lport = inc->i_hdr.h_dport; minfo.fport = inc->i_hdr.h_sport; } else { minfo.laddr = saddr; minfo.faddr = daddr; minfo.lport = inc->i_hdr.h_sport; minfo.fport = inc->i_hdr.h_dport; } rds_info_copy(iter, &minfo, sizeof(minfo)); }
./CrossVul/dataset_final_sorted/CWE-20/c/bad_5845_26
crossvul-cpp_data_good_3088_0
/* bubblewrap * Copyright (C) 2016 Alexander Larsson * * This program 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, see <http://www.gnu.org/licenses/>. * */ #include "config.h" #include <poll.h> #include <sched.h> #include <pwd.h> #include <grp.h> #include <sys/mount.h> #include <sys/socket.h> #include <sys/wait.h> #include <sys/eventfd.h> #include <sys/fsuid.h> #include <sys/signalfd.h> #include <sys/capability.h> #include <sys/prctl.h> #include <linux/sched.h> #include <linux/seccomp.h> #include <linux/filter.h> #include "utils.h" #include "network.h" #include "bind-mount.h" #ifndef CLONE_NEWCGROUP #define CLONE_NEWCGROUP 0x02000000 /* New cgroup namespace */ #endif /* Globals to avoid having to use getuid(), since the uid/gid changes during runtime */ static uid_t real_uid; static gid_t real_gid; static uid_t overflow_uid; static gid_t overflow_gid; static bool is_privileged; static const char *argv0; static const char *host_tty_dev; static int proc_fd = -1; static char *opt_exec_label = NULL; static char *opt_file_label = NULL; char *opt_chdir_path = NULL; bool opt_unshare_user = FALSE; bool opt_unshare_user_try = FALSE; bool opt_unshare_pid = FALSE; bool opt_unshare_ipc = FALSE; bool opt_unshare_net = FALSE; bool opt_unshare_uts = FALSE; bool opt_unshare_cgroup = FALSE; bool opt_unshare_cgroup_try = FALSE; bool opt_needs_devpts = FALSE; uid_t opt_sandbox_uid = -1; gid_t opt_sandbox_gid = -1; int opt_sync_fd = -1; int opt_block_fd = -1; int opt_info_fd = -1; int opt_seccomp_fd = -1; char *opt_sandbox_hostname = NULL; typedef enum { SETUP_BIND_MOUNT, SETUP_RO_BIND_MOUNT, SETUP_DEV_BIND_MOUNT, SETUP_MOUNT_PROC, SETUP_MOUNT_DEV, SETUP_MOUNT_TMPFS, SETUP_MOUNT_MQUEUE, SETUP_MAKE_DIR, SETUP_MAKE_FILE, SETUP_MAKE_BIND_FILE, SETUP_MAKE_RO_BIND_FILE, SETUP_MAKE_SYMLINK, SETUP_REMOUNT_RO_NO_RECURSIVE, SETUP_SET_HOSTNAME, } SetupOpType; typedef enum { NO_CREATE_DEST = (1 << 0), } SetupOpFlag; typedef struct _SetupOp SetupOp; struct _SetupOp { SetupOpType type; const char *source; const char *dest; int fd; SetupOpFlag flags; SetupOp *next; }; typedef struct _LockFile LockFile; struct _LockFile { const char *path; LockFile *next; }; static SetupOp *ops = NULL; static SetupOp *last_op = NULL; static LockFile *lock_files = NULL; static LockFile *last_lock_file = NULL; enum { PRIV_SEP_OP_DONE, PRIV_SEP_OP_BIND_MOUNT, PRIV_SEP_OP_PROC_MOUNT, PRIV_SEP_OP_TMPFS_MOUNT, PRIV_SEP_OP_DEVPTS_MOUNT, PRIV_SEP_OP_MQUEUE_MOUNT, PRIV_SEP_OP_REMOUNT_RO_NO_RECURSIVE, PRIV_SEP_OP_SET_HOSTNAME, }; typedef struct { uint32_t op; uint32_t flags; uint32_t arg1_offset; uint32_t arg2_offset; } PrivSepOp; static SetupOp * setup_op_new (SetupOpType type) { SetupOp *op = xcalloc (sizeof (SetupOp)); op->type = type; op->fd = -1; op->flags = 0; if (last_op != NULL) last_op->next = op; else ops = op; last_op = op; return op; } static LockFile * lock_file_new (const char *path) { LockFile *lock = xcalloc (sizeof (LockFile)); lock->path = path; if (last_lock_file != NULL) last_lock_file->next = lock; else lock_files = lock; last_lock_file = lock; return lock; } static void usage (int ecode, FILE *out) { fprintf (out, "usage: %s [OPTIONS...] COMMAND [ARGS...]\n\n", argv0); fprintf (out, " --help Print this help\n" " --version Print version\n" " --args FD Parse nul-separated args from FD\n" " --unshare-user Create new user namespace (may be automatically implied if not setuid)\n" " --unshare-user-try Create new user namespace if possible else continue by skipping it\n" " --unshare-ipc Create new ipc namespace\n" " --unshare-pid Create new pid namespace\n" " --unshare-net Create new network namespace\n" " --unshare-uts Create new uts namespace\n" " --unshare-cgroup Create new cgroup namespace\n" " --unshare-cgroup-try Create new cgroup namespace if possible else continue by skipping it\n" " --uid UID Custom uid in the sandbox (requires --unshare-user)\n" " --gid GID Custon gid in the sandbox (requires --unshare-user)\n" " --hostname NAME Custom hostname in the sandbox (requires --unshare-uts)\n" " --chdir DIR Change directory to DIR\n" " --setenv VAR VALUE Set an environment variable\n" " --unsetenv VAR Unset an environment variable\n" " --lock-file DEST Take a lock on DEST while sandbox is running\n" " --sync-fd FD Keep this fd open while sandbox is running\n" " --bind SRC DEST Bind mount the host path SRC on DEST\n" " --dev-bind SRC DEST Bind mount the host path SRC on DEST, allowing device access\n" " --ro-bind SRC DEST Bind mount the host path SRC readonly on DEST\n" " --remount-ro DEST Remount DEST as readonly, it doesn't recursively remount\n" " --exec-label LABEL Exec Label for the sandbox\n" " --file-label LABEL File label for temporary sandbox content\n" " --proc DEST Mount procfs on DEST\n" " --dev DEST Mount new dev on DEST\n" " --tmpfs DEST Mount new tmpfs on DEST\n" " --mqueue DEST Mount new mqueue on DEST\n" " --dir DEST Create dir at DEST\n" " --file FD DEST Copy from FD to dest DEST\n" " --bind-data FD DEST Copy from FD to file which is bind-mounted on DEST\n" " --ro-bind-data FD DEST Copy from FD to file which is readonly bind-mounted on DEST\n" " --symlink SRC DEST Create symlink at DEST with target SRC\n" " --seccomp FD Load and use seccomp rules from FD\n" " --block-fd FD Block on FD until some data to read is available\n" " --info-fd FD Write information about the running container to FD\n" ); exit (ecode); } static void block_sigchild (void) { sigset_t mask; sigemptyset (&mask); sigaddset (&mask, SIGCHLD); if (sigprocmask (SIG_BLOCK, &mask, NULL) == -1) die_with_error ("sigprocmask"); } static void unblock_sigchild (void) { sigset_t mask; sigemptyset (&mask); sigaddset (&mask, SIGCHLD); if (sigprocmask (SIG_UNBLOCK, &mask, NULL) == -1) die_with_error ("sigprocmask"); } /* Closes all fd:s except 0,1,2 and the passed in array of extra fds */ static int close_extra_fds (void *data, int fd) { int *extra_fds = (int *) data; int i; for (i = 0; extra_fds[i] != -1; i++) if (fd == extra_fds[i]) return 0; if (fd <= 2) return 0; close (fd); return 0; } /* This stays around for as long as the initial process in the app does * and when that exits it exits, propagating the exit status. We do this * by having pid 1 in the sandbox detect this exit and tell the monitor * the exit status via a eventfd. We also track the exit of the sandbox * pid 1 via a signalfd for SIGCHLD, and exit with an error in this case. * This is to catch e.g. problems during setup. */ static void monitor_child (int event_fd) { int res; uint64_t val; ssize_t s; int signal_fd; sigset_t mask; struct pollfd fds[2]; int num_fds; struct signalfd_siginfo fdsi; int dont_close[] = { event_fd, -1 }; /* Close all extra fds in the monitoring process. Any passed in fds have been passed on to the child anyway. */ fdwalk (proc_fd, close_extra_fds, dont_close); sigemptyset (&mask); sigaddset (&mask, SIGCHLD); signal_fd = signalfd (-1, &mask, SFD_CLOEXEC | SFD_NONBLOCK); if (signal_fd == -1) die_with_error ("Can't create signalfd"); num_fds = 1; fds[0].fd = signal_fd; fds[0].events = POLLIN; if (event_fd != -1) { fds[1].fd = event_fd; fds[1].events = POLLIN; num_fds++; } while (1) { fds[0].revents = fds[1].revents = 0; res = poll (fds, num_fds, -1); if (res == -1 && errno != EINTR) die_with_error ("poll"); /* Always read from the eventfd first, if pid 2 died then pid 1 often * dies too, and we could race, reporting that first and we'd lose * the real exit status. */ if (event_fd != -1) { s = read (event_fd, &val, 8); if (s == -1 && errno != EINTR && errno != EAGAIN) die_with_error ("read eventfd"); else if (s == 8) exit ((int) val - 1); } s = read (signal_fd, &fdsi, sizeof (struct signalfd_siginfo)); if (s == -1 && errno != EINTR && errno != EAGAIN) { die_with_error ("read signalfd"); } else if (s == sizeof (struct signalfd_siginfo)) { if (fdsi.ssi_signo != SIGCHLD) die ("Read unexpected signal\n"); exit (fdsi.ssi_status); } } } /* This is pid 1 in the app sandbox. It is needed because we're using * pid namespaces, and someone has to reap zombies in it. We also detect * when the initial process (pid 2) dies and report its exit status to * the monitor so that it can return it to the original spawner. * * When there are no other processes in the sandbox the wait will return * ECHILD, and we then exit pid 1 to clean up the sandbox. */ static int do_init (int event_fd, pid_t initial_pid) { int initial_exit_status = 1; LockFile *lock; for (lock = lock_files; lock != NULL; lock = lock->next) { int fd = open (lock->path, O_RDONLY | O_CLOEXEC); if (fd == -1) die_with_error ("Unable to open lock file %s", lock->path); struct flock l = { .l_type = F_RDLCK, .l_whence = SEEK_SET, .l_start = 0, .l_len = 0 }; if (fcntl (fd, F_SETLK, &l) < 0) die_with_error ("Unable to lock file %s", lock->path); /* Keep fd open to hang on to lock */ } while (TRUE) { pid_t child; int status; child = wait (&status); if (child == initial_pid && event_fd != -1) { uint64_t val; int res UNUSED; if (WIFEXITED (status)) initial_exit_status = WEXITSTATUS (status); val = initial_exit_status + 1; res = write (event_fd, &val, 8); /* Ignore res, if e.g. the parent died and closed event_fd we don't want to error out here */ } if (child == -1 && errno != EINTR) { if (errno != ECHILD) die_with_error ("init wait()"); break; } } return initial_exit_status; } /* low 32bit caps needed */ #define REQUIRED_CAPS_0 (CAP_TO_MASK (CAP_SYS_ADMIN) | CAP_TO_MASK (CAP_SYS_CHROOT) | CAP_TO_MASK (CAP_NET_ADMIN) | CAP_TO_MASK (CAP_SETUID) | CAP_TO_MASK (CAP_SETGID)) /* high 32bit caps needed */ #define REQUIRED_CAPS_1 0 static void set_required_caps (void) { struct __user_cap_header_struct hdr = { _LINUX_CAPABILITY_VERSION_3, 0 }; struct __user_cap_data_struct data[2] = { { 0 } }; /* Drop all non-require capabilities */ data[0].effective = REQUIRED_CAPS_0; data[0].permitted = REQUIRED_CAPS_0; data[0].inheritable = 0; data[1].effective = REQUIRED_CAPS_1; data[1].permitted = REQUIRED_CAPS_1; data[1].inheritable = 0; if (capset (&hdr, data) < 0) die_with_error ("capset failed"); } static void drop_all_caps (void) { struct __user_cap_header_struct hdr = { _LINUX_CAPABILITY_VERSION_3, 0 }; struct __user_cap_data_struct data[2] = { { 0 } }; if (capset (&hdr, data) < 0) die_with_error ("capset failed"); } static bool has_caps (void) { struct __user_cap_header_struct hdr = { _LINUX_CAPABILITY_VERSION_3, 0 }; struct __user_cap_data_struct data[2] = { { 0 } }; if (capget (&hdr, data) < 0) die_with_error ("capget failed"); return data[0].permitted != 0 || data[1].permitted != 0; } /* This acquires the privileges that the bwrap will need it to work. * If bwrap is not setuid, then this does nothing, and it relies on * unprivileged user namespaces to be used. This case is * "is_privileged = FALSE". * * If bwrap is setuid, then we do things in phases. * The first part is run as euid 0, but with with fsuid as the real user. * The second part, inside the child, is run as the real user but with * capabilities. * And finally we drop all capabilities. * The reason for the above dance is to avoid having the setup phase * being able to read files the user can't, while at the same time * working around various kernel issues. See below for details. */ static void acquire_privs (void) { uid_t euid, new_fsuid; euid = geteuid (); /* Are we setuid ? */ if (real_uid != euid) { if (euid == 0) is_privileged = TRUE; else die ("Unexpected setuid user %d, should be 0", euid); /* We want to keep running as euid=0 until at the clone() * operation because doing so will make the user namespace be * owned by root, which makes it not ptrace:able by the user as * it otherwise would be. After that we will run fully as the * user, which is necessary e.g. to be able to read from a fuse * mount from the user. * * However, we don't want to accidentally mis-use euid=0 for * escalated filesystem access before the clone(), so we set * fsuid to the uid. */ if (setfsuid (real_uid) < 0) die_with_error ("Unable to set fsuid"); /* setfsuid can't properly report errors, check that it worked (as per manpage) */ new_fsuid = setfsuid (-1); if (new_fsuid != real_uid) die ("Unable to set fsuid (was %d)", (int)new_fsuid); /* Keep only the required capabilities for setup */ set_required_caps (); } else if (real_uid != 0 && has_caps ()) { /* We have some capabilities in the non-setuid case, which should not happen. Probably caused by the binary being setcap instead of setuid which we don't support anymore */ die ("Unexpected capabilities but not setuid, old file caps config?"); } /* Else, we try unprivileged user namespaces */ } /* This is called once we're inside the namespace */ static void switch_to_user_with_privs (void) { if (!is_privileged) return; /* Tell kernel not clear capabilities when later dropping root uid */ if (prctl (PR_SET_KEEPCAPS, 1, 0, 0, 0) < 0) die_with_error ("prctl(PR_SET_KEEPCAPS) failed"); if (setuid (opt_sandbox_uid) < 0) die_with_error ("unable to drop root uid"); /* Regain effective required capabilities from permitted */ set_required_caps (); } static void drop_privs (void) { if (!is_privileged) return; /* Drop root uid */ if (setuid (opt_sandbox_uid) < 0) die_with_error ("unable to drop root uid"); drop_all_caps (); } static char * get_newroot_path (const char *path) { while (*path == '/') path++; return strconcat ("/newroot/", path); } static char * get_oldroot_path (const char *path) { while (*path == '/') path++; return strconcat ("/oldroot/", path); } static void write_uid_gid_map (uid_t sandbox_uid, uid_t parent_uid, uid_t sandbox_gid, uid_t parent_gid, pid_t pid, bool deny_groups, bool map_root) { cleanup_free char *uid_map = NULL; cleanup_free char *gid_map = NULL; cleanup_free char *dir = NULL; cleanup_fd int dir_fd = -1; uid_t old_fsuid = -1; if (pid == -1) dir = xstrdup ("self"); else dir = xasprintf ("%d", pid); dir_fd = openat (proc_fd, dir, O_RDONLY | O_PATH); if (dir_fd < 0) die_with_error ("open /proc/%s failed", dir); if (map_root && parent_uid != 0 && sandbox_uid != 0) uid_map = xasprintf ("0 %d 1\n" "%d %d 1\n", overflow_uid, sandbox_uid, parent_uid); else uid_map = xasprintf ("%d %d 1\n", sandbox_uid, parent_uid); if (map_root && parent_gid != 0 && sandbox_gid != 0) gid_map = xasprintf ("0 %d 1\n" "%d %d 1\n", overflow_gid, sandbox_gid, parent_gid); else gid_map = xasprintf ("%d %d 1\n", sandbox_gid, parent_gid); /* We have to be root to be allowed to write to the uid map * for setuid apps, so temporary set fsuid to 0 */ if (is_privileged) old_fsuid = setfsuid (0); if (write_file_at (dir_fd, "uid_map", uid_map) != 0) die_with_error ("setting up uid map"); if (deny_groups && write_file_at (dir_fd, "setgroups", "deny\n") != 0) { /* If /proc/[pid]/setgroups does not exist, assume we are * running a linux kernel < 3.19, i.e. we live with the * vulnerability known as CVE-2014-8989 in older kernels * where setgroups does not exist. */ if (errno != ENOENT) die_with_error ("error writing to setgroups"); } if (write_file_at (dir_fd, "gid_map", gid_map) != 0) die_with_error ("setting up gid map"); if (is_privileged) { setfsuid (old_fsuid); if (setfsuid (-1) != real_uid) die ("Unable to re-set fsuid"); } } static void privileged_op (int privileged_op_socket, uint32_t op, uint32_t flags, const char *arg1, const char *arg2) { if (privileged_op_socket != -1) { uint32_t buffer[2048]; /* 8k, but is int32 to guarantee nice alignment */ PrivSepOp *op_buffer = (PrivSepOp *) buffer; size_t buffer_size = sizeof (PrivSepOp); uint32_t arg1_offset = 0, arg2_offset = 0; /* We're unprivileged, send this request to the privileged part */ if (arg1 != NULL) { arg1_offset = buffer_size; buffer_size += strlen (arg1) + 1; } if (arg2 != NULL) { arg2_offset = buffer_size; buffer_size += strlen (arg2) + 1; } if (buffer_size >= sizeof (buffer)) die ("privilege separation operation to large"); op_buffer->op = op; op_buffer->flags = flags; op_buffer->arg1_offset = arg1_offset; op_buffer->arg2_offset = arg2_offset; if (arg1 != NULL) strcpy ((char *) buffer + arg1_offset, arg1); if (arg2 != NULL) strcpy ((char *) buffer + arg2_offset, arg2); if (write (privileged_op_socket, buffer, buffer_size) != buffer_size) die ("Can't write to privileged_op_socket"); if (read (privileged_op_socket, buffer, 1) != 1) die ("Can't read from privileged_op_socket"); return; } /* * This runs a privileged request for the unprivileged setup * code. Note that since the setup code is unprivileged it is not as * trusted, so we need to verify that all requests only affect the * child namespace as set up by the privileged parts of the setup, * and that all the code is very careful about handling input. * * This means: * * Bind mounts are safe, since we always use filesystem namespace. They * must be recursive though, as otherwise you can use a non-recursive bind * mount to access an otherwise over-mounted mountpoint. * * Mounting proc, tmpfs, mqueue, devpts in the child namespace is assumed to * be safe. * * Remounting RO (even non-recursive) is safe because it decreases privileges. * * sethostname() is safe only if we set up a UTS namespace */ switch (op) { case PRIV_SEP_OP_DONE: break; case PRIV_SEP_OP_REMOUNT_RO_NO_RECURSIVE: if (bind_mount (proc_fd, NULL, arg2, BIND_READONLY) != 0) die_with_error ("Can't remount readonly on %s", arg2); break; case PRIV_SEP_OP_BIND_MOUNT: /* We always bind directories recursively, otherwise this would let us access files that are otherwise covered on the host */ if (bind_mount (proc_fd, arg1, arg2, BIND_RECURSIVE | flags) != 0) die_with_error ("Can't bind mount %s on %s", arg1, arg2); break; case PRIV_SEP_OP_PROC_MOUNT: if (mount ("proc", arg1, "proc", MS_MGC_VAL | MS_NOSUID | MS_NOEXEC | MS_NODEV, NULL) != 0) die_with_error ("Can't mount proc on %s", arg1); break; case PRIV_SEP_OP_TMPFS_MOUNT: { cleanup_free char *opt = label_mount ("mode=0755", opt_file_label); if (mount ("tmpfs", arg1, "tmpfs", MS_MGC_VAL | MS_NOSUID | MS_NODEV, opt) != 0) die_with_error ("Can't mount tmpfs on %s", arg1); break; } case PRIV_SEP_OP_DEVPTS_MOUNT: if (mount ("devpts", arg1, "devpts", MS_MGC_VAL | MS_NOSUID | MS_NOEXEC, "newinstance,ptmxmode=0666,mode=620") != 0) die_with_error ("Can't mount devpts on %s", arg1); break; case PRIV_SEP_OP_MQUEUE_MOUNT: if (mount ("mqueue", arg1, "mqueue", 0, NULL) != 0) die_with_error ("Can't mount mqueue on %s", arg1); break; case PRIV_SEP_OP_SET_HOSTNAME: /* This is checked at the start, but lets verify it here in case something manages to send hacked priv-sep operation requests. */ if (!opt_unshare_uts) die ("Refusing to set hostname in original namespace"); if (sethostname (arg1, strlen(arg1)) != 0) die_with_error ("Can't set hostname to %s", arg1); break; default: die ("Unexpected privileged op %d", op); } } /* This is run unprivileged in the child namespace but can request * some privileged operations (also in the child namespace) via the * privileged_op_socket. */ static void setup_newroot (bool unshare_pid, int privileged_op_socket) { SetupOp *op; for (op = ops; op != NULL; op = op->next) { cleanup_free char *source = NULL; cleanup_free char *dest = NULL; int source_mode = 0; int i; if (op->source && op->type != SETUP_MAKE_SYMLINK) { source = get_oldroot_path (op->source); source_mode = get_file_mode (source); if (source_mode < 0) die_with_error ("Can't get type of source %s", op->source); } if (op->dest && (op->flags & NO_CREATE_DEST) == 0) { dest = get_newroot_path (op->dest); if (mkdir_with_parents (dest, 0755, FALSE) != 0) die_with_error ("Can't mkdir parents for %s", op->dest); } switch (op->type) { case SETUP_RO_BIND_MOUNT: case SETUP_DEV_BIND_MOUNT: case SETUP_BIND_MOUNT: if (source_mode == S_IFDIR) { if (mkdir (dest, 0755) != 0 && errno != EEXIST) die_with_error ("Can't mkdir %s", op->dest); } else if (ensure_file (dest, 0666) != 0) die_with_error ("Can't create file at %s", op->dest); privileged_op (privileged_op_socket, PRIV_SEP_OP_BIND_MOUNT, (op->type == SETUP_RO_BIND_MOUNT ? BIND_READONLY : 0) | (op->type == SETUP_DEV_BIND_MOUNT ? BIND_DEVICES : 0), source, dest); break; case SETUP_REMOUNT_RO_NO_RECURSIVE: privileged_op (privileged_op_socket, PRIV_SEP_OP_REMOUNT_RO_NO_RECURSIVE, BIND_READONLY, NULL, dest); break; case SETUP_MOUNT_PROC: if (mkdir (dest, 0755) != 0 && errno != EEXIST) die_with_error ("Can't mkdir %s", op->dest); if (unshare_pid) { /* Our own procfs */ privileged_op (privileged_op_socket, PRIV_SEP_OP_PROC_MOUNT, 0, dest, NULL); } else { /* Use system procfs, as we share pid namespace anyway */ privileged_op (privileged_op_socket, PRIV_SEP_OP_BIND_MOUNT, 0, "oldroot/proc", dest); } /* There are a bunch of weird old subdirs of /proc that could potentially be problematic (for instance /proc/sysrq-trigger lets you shut down the machine if you have write access). We should not have access to these as a non-privileged user, but lets cover them anyway just to make sure */ const char *cover_proc_dirs[] = { "sys", "sysrq-trigger", "irq", "bus" }; for (i = 0; i < N_ELEMENTS (cover_proc_dirs); i++) { cleanup_free char *subdir = strconcat3 (dest, "/", cover_proc_dirs[i]); privileged_op (privileged_op_socket, PRIV_SEP_OP_BIND_MOUNT, BIND_READONLY, subdir, subdir); } break; case SETUP_MOUNT_DEV: if (mkdir (dest, 0755) != 0 && errno != EEXIST) die_with_error ("Can't mkdir %s", op->dest); privileged_op (privileged_op_socket, PRIV_SEP_OP_TMPFS_MOUNT, 0, dest, NULL); static const char *const devnodes[] = { "null", "zero", "full", "random", "urandom", "tty" }; for (i = 0; i < N_ELEMENTS (devnodes); i++) { cleanup_free char *node_dest = strconcat3 (dest, "/", devnodes[i]); cleanup_free char *node_src = strconcat ("/oldroot/dev/", devnodes[i]); if (create_file (node_dest, 0666, NULL) != 0) die_with_error ("Can't create file %s/%s", op->dest, devnodes[i]); privileged_op (privileged_op_socket, PRIV_SEP_OP_BIND_MOUNT, BIND_DEVICES, node_src, node_dest); } static const char *const stdionodes[] = { "stdin", "stdout", "stderr" }; for (i = 0; i < N_ELEMENTS (stdionodes); i++) { cleanup_free char *target = xasprintf ("/proc/self/fd/%d", i); cleanup_free char *node_dest = strconcat3 (dest, "/", stdionodes[i]); if (symlink (target, node_dest) < 0) die_with_error ("Can't create symlink %s/%s", op->dest, stdionodes[i]); } { cleanup_free char *pts = strconcat (dest, "/pts"); cleanup_free char *ptmx = strconcat (dest, "/ptmx"); cleanup_free char *shm = strconcat (dest, "/shm"); if (mkdir (shm, 0755) == -1) die_with_error ("Can't create %s/shm", op->dest); if (mkdir (pts, 0755) == -1) die_with_error ("Can't create %s/devpts", op->dest); privileged_op (privileged_op_socket, PRIV_SEP_OP_DEVPTS_MOUNT, BIND_DEVICES, pts, NULL); if (symlink ("pts/ptmx", ptmx) != 0) die_with_error ("Can't make symlink at %s/ptmx", op->dest); } /* If stdout is a tty, that means the sandbox can write to the outside-sandbox tty. In that case we also create a /dev/console that points to this tty device. This should not cause any more access than we already have, and it makes ttyname() work in the sandbox. */ if (host_tty_dev != NULL && *host_tty_dev != 0) { cleanup_free char *src_tty_dev = strconcat ("/oldroot", host_tty_dev); cleanup_free char *dest_console = strconcat (dest, "/console"); if (create_file (dest_console, 0666, NULL) != 0) die_with_error ("creating %s/console", op->dest); privileged_op (privileged_op_socket, PRIV_SEP_OP_BIND_MOUNT, BIND_DEVICES, src_tty_dev, dest_console); } break; case SETUP_MOUNT_TMPFS: if (mkdir (dest, 0755) != 0 && errno != EEXIST) die_with_error ("Can't mkdir %s", op->dest); privileged_op (privileged_op_socket, PRIV_SEP_OP_TMPFS_MOUNT, 0, dest, NULL); break; case SETUP_MOUNT_MQUEUE: if (mkdir (dest, 0755) != 0 && errno != EEXIST) die_with_error ("Can't mkdir %s", op->dest); privileged_op (privileged_op_socket, PRIV_SEP_OP_MQUEUE_MOUNT, 0, dest, NULL); break; case SETUP_MAKE_DIR: if (mkdir (dest, 0755) != 0 && errno != EEXIST) die_with_error ("Can't mkdir %s", op->dest); break; case SETUP_MAKE_FILE: { cleanup_fd int dest_fd = -1; dest_fd = creat (dest, 0666); if (dest_fd == -1) die_with_error ("Can't create file %s", op->dest); if (copy_file_data (op->fd, dest_fd) != 0) die_with_error ("Can't write data to file %s", op->dest); close (op->fd); } break; case SETUP_MAKE_BIND_FILE: case SETUP_MAKE_RO_BIND_FILE: { cleanup_fd int dest_fd = -1; char tempfile[] = "/bindfileXXXXXX"; dest_fd = mkstemp (tempfile); if (dest_fd == -1) die_with_error ("Can't create tmpfile for %s", op->dest); if (copy_file_data (op->fd, dest_fd) != 0) die_with_error ("Can't write data to file %s", op->dest); close (op->fd); if (ensure_file (dest, 0666) != 0) die_with_error ("Can't create file at %s", op->dest); privileged_op (privileged_op_socket, PRIV_SEP_OP_BIND_MOUNT, (op->type == SETUP_MAKE_RO_BIND_FILE ? BIND_READONLY : 0), tempfile, dest); /* Remove the file so we're sure the app can't get to it in any other way. Its outside the container chroot, so it shouldn't be possible, but lets make it really sure. */ unlink (tempfile); } break; case SETUP_MAKE_SYMLINK: if (symlink (op->source, dest) != 0) die_with_error ("Can't make symlink at %s", op->dest); break; case SETUP_SET_HOSTNAME: privileged_op (privileged_op_socket, PRIV_SEP_OP_SET_HOSTNAME, 0, op->dest, NULL); break; default: die ("Unexpected type %d", op->type); } } privileged_op (privileged_op_socket, PRIV_SEP_OP_DONE, 0, NULL, NULL); } /* We need to resolve relative symlinks in the sandbox before we chroot so that absolute symlinks are handled correctly. We also need to do this after we've switched to the real uid so that e.g. paths on fuse mounts work */ static void resolve_symlinks_in_ops (void) { SetupOp *op; for (op = ops; op != NULL; op = op->next) { const char *old_source; switch (op->type) { case SETUP_RO_BIND_MOUNT: case SETUP_DEV_BIND_MOUNT: case SETUP_BIND_MOUNT: old_source = op->source; op->source = realpath (old_source, NULL); if (op->source == NULL) die_with_error ("Can't find source path %s", old_source); break; default: break; } } } static const char * resolve_string_offset (void *buffer, size_t buffer_size, uint32_t offset) { if (offset == 0) return NULL; if (offset > buffer_size) die ("Invalid string offset %d (buffer size %zd)", offset, buffer_size); return (const char *) buffer + offset; } static uint32_t read_priv_sec_op (int read_socket, void *buffer, size_t buffer_size, uint32_t *flags, const char **arg1, const char **arg2) { const PrivSepOp *op = (const PrivSepOp *) buffer; ssize_t rec_len; do rec_len = read (read_socket, buffer, buffer_size - 1); while (rec_len == -1 && errno == EINTR); if (rec_len < 0) die_with_error ("Can't read from unprivileged helper"); if (rec_len == 0) exit (1); /* Privileged helper died and printed error, so exit silently */ if (rec_len < sizeof (PrivSepOp)) die ("Invalid size %zd from unprivileged helper", rec_len); /* Guarantee zero termination of any strings */ ((char *) buffer)[rec_len] = 0; *flags = op->flags; *arg1 = resolve_string_offset (buffer, rec_len, op->arg1_offset); *arg2 = resolve_string_offset (buffer, rec_len, op->arg2_offset); return op->op; } static void parse_args_recurse (int *argcp, char ***argvp, bool in_file, int *total_parsed_argc_p) { SetupOp *op; int argc = *argcp; char **argv = *argvp; /* I can't imagine a case where someone wants more than this. * If you do...you should be able to pass multiple files * via a single tmpfs and linking them there, etc. * * We're adding this hardening due to precedent from * http://googleprojectzero.blogspot.com/2014/08/the-poisoned-nul-byte-2014-edition.html * * I picked 9000 because the Internet told me to and it was hard to * resist. */ static const uint32_t MAX_ARGS = 9000; if (*total_parsed_argc_p > MAX_ARGS) die ("Exceeded maximum number of arguments %u", MAX_ARGS); while (argc > 0) { const char *arg = argv[0]; if (strcmp (arg, "--help") == 0) { usage (EXIT_SUCCESS, stdout); } else if (strcmp (arg, "--version") == 0) { printf ("%s\n", PACKAGE_STRING); exit (0); } else if (strcmp (arg, "--args") == 0) { int the_fd; char *endptr; char *data, *p; char *data_end; size_t data_len; cleanup_free char **data_argv = NULL; char **data_argv_copy; int data_argc; int i; if (in_file) die ("--args not supported in arguments file"); if (argc < 2) die ("--args takes an argument"); the_fd = strtol (argv[1], &endptr, 10); if (argv[1][0] == 0 || endptr[0] != 0 || the_fd < 0) die ("Invalid fd: %s", argv[1]); data = load_file_data (the_fd, &data_len); if (data == NULL) die_with_error ("Can't read --args data"); data_end = data + data_len; data_argc = 0; p = data; while (p != NULL && p < data_end) { data_argc++; (*total_parsed_argc_p)++; if (*total_parsed_argc_p > MAX_ARGS) die ("Exceeded maximum number of arguments %u", MAX_ARGS); p = memchr (p, 0, data_end - p); if (p != NULL) p++; } data_argv = xcalloc (sizeof (char *) * (data_argc + 1)); i = 0; p = data; while (p != NULL && p < data_end) { /* Note: load_file_data always adds a nul terminator, so this is safe * even for the last string. */ data_argv[i++] = p; p = memchr (p, 0, data_end - p); if (p != NULL) p++; } data_argv_copy = data_argv; /* Don't change data_argv, we need to free it */ parse_args_recurse (&data_argc, &data_argv_copy, TRUE, total_parsed_argc_p); argv += 1; argc -= 1; } else if (strcmp (arg, "--unshare-user") == 0) { opt_unshare_user = TRUE; } else if (strcmp (arg, "--unshare-user-try") == 0) { opt_unshare_user_try = TRUE; } else if (strcmp (arg, "--unshare-ipc") == 0) { opt_unshare_ipc = TRUE; } else if (strcmp (arg, "--unshare-pid") == 0) { opt_unshare_pid = TRUE; } else if (strcmp (arg, "--unshare-net") == 0) { opt_unshare_net = TRUE; } else if (strcmp (arg, "--unshare-uts") == 0) { opt_unshare_uts = TRUE; } else if (strcmp (arg, "--unshare-cgroup") == 0) { opt_unshare_cgroup = TRUE; } else if (strcmp (arg, "--unshare-cgroup-try") == 0) { opt_unshare_cgroup_try = TRUE; } else if (strcmp (arg, "--chdir") == 0) { if (argc < 2) die ("--chdir takes one argument"); opt_chdir_path = argv[1]; argv++; argc--; } else if (strcmp (arg, "--remount-ro") == 0) { SetupOp *op = setup_op_new (SETUP_REMOUNT_RO_NO_RECURSIVE); op->dest = argv[1]; argv++; argc--; } else if (strcmp (arg, "--bind") == 0) { if (argc < 3) die ("--bind takes two arguments"); op = setup_op_new (SETUP_BIND_MOUNT); op->source = argv[1]; op->dest = argv[2]; argv += 2; argc -= 2; } else if (strcmp (arg, "--ro-bind") == 0) { if (argc < 3) die ("--ro-bind takes two arguments"); op = setup_op_new (SETUP_RO_BIND_MOUNT); op->source = argv[1]; op->dest = argv[2]; argv += 2; argc -= 2; } else if (strcmp (arg, "--dev-bind") == 0) { if (argc < 3) die ("--dev-bind takes two arguments"); op = setup_op_new (SETUP_DEV_BIND_MOUNT); op->source = argv[1]; op->dest = argv[2]; argv += 2; argc -= 2; } else if (strcmp (arg, "--proc") == 0) { if (argc < 2) die ("--proc takes an argument"); op = setup_op_new (SETUP_MOUNT_PROC); op->dest = argv[1]; argv += 1; argc -= 1; } else if (strcmp (arg, "--exec-label") == 0) { if (argc < 2) die ("--exec-label takes an argument"); opt_exec_label = argv[1]; die_unless_label_valid (opt_exec_label); argv += 1; argc -= 1; } else if (strcmp (arg, "--file-label") == 0) { if (argc < 2) die ("--file-label takes an argument"); opt_file_label = argv[1]; die_unless_label_valid (opt_file_label); if (label_create_file (opt_file_label)) die_with_error ("--file-label setup failed"); argv += 1; argc -= 1; } else if (strcmp (arg, "--dev") == 0) { if (argc < 2) die ("--dev takes an argument"); op = setup_op_new (SETUP_MOUNT_DEV); op->dest = argv[1]; opt_needs_devpts = TRUE; argv += 1; argc -= 1; } else if (strcmp (arg, "--tmpfs") == 0) { if (argc < 2) die ("--tmpfs takes an argument"); op = setup_op_new (SETUP_MOUNT_TMPFS); op->dest = argv[1]; argv += 1; argc -= 1; } else if (strcmp (arg, "--mqueue") == 0) { if (argc < 2) die ("--mqueue takes an argument"); op = setup_op_new (SETUP_MOUNT_MQUEUE); op->dest = argv[1]; argv += 1; argc -= 1; } else if (strcmp (arg, "--dir") == 0) { if (argc < 2) die ("--dir takes an argument"); op = setup_op_new (SETUP_MAKE_DIR); op->dest = argv[1]; argv += 1; argc -= 1; } else if (strcmp (arg, "--file") == 0) { int file_fd; char *endptr; if (argc < 3) die ("--file takes two arguments"); file_fd = strtol (argv[1], &endptr, 10); if (argv[1][0] == 0 || endptr[0] != 0 || file_fd < 0) die ("Invalid fd: %s", argv[1]); op = setup_op_new (SETUP_MAKE_FILE); op->fd = file_fd; op->dest = argv[2]; argv += 2; argc -= 2; } else if (strcmp (arg, "--bind-data") == 0) { int file_fd; char *endptr; if (argc < 3) die ("--bind-data takes two arguments"); file_fd = strtol (argv[1], &endptr, 10); if (argv[1][0] == 0 || endptr[0] != 0 || file_fd < 0) die ("Invalid fd: %s", argv[1]); op = setup_op_new (SETUP_MAKE_BIND_FILE); op->fd = file_fd; op->dest = argv[2]; argv += 2; argc -= 2; } else if (strcmp (arg, "--ro-bind-data") == 0) { int file_fd; char *endptr; if (argc < 3) die ("--ro-bind-data takes two arguments"); file_fd = strtol (argv[1], &endptr, 10); if (argv[1][0] == 0 || endptr[0] != 0 || file_fd < 0) die ("Invalid fd: %s", argv[1]); op = setup_op_new (SETUP_MAKE_RO_BIND_FILE); op->fd = file_fd; op->dest = argv[2]; argv += 2; argc -= 2; } else if (strcmp (arg, "--symlink") == 0) { if (argc < 3) die ("--symlink takes two arguments"); op = setup_op_new (SETUP_MAKE_SYMLINK); op->source = argv[1]; op->dest = argv[2]; argv += 2; argc -= 2; } else if (strcmp (arg, "--lock-file") == 0) { if (argc < 2) die ("--lock-file takes an argument"); (void) lock_file_new (argv[1]); argv += 1; argc -= 1; } else if (strcmp (arg, "--sync-fd") == 0) { int the_fd; char *endptr; if (argc < 2) die ("--sync-fd takes an argument"); the_fd = strtol (argv[1], &endptr, 10); if (argv[1][0] == 0 || endptr[0] != 0 || the_fd < 0) die ("Invalid fd: %s", argv[1]); opt_sync_fd = the_fd; argv += 1; argc -= 1; } else if (strcmp (arg, "--block-fd") == 0) { int the_fd; char *endptr; if (argc < 2) die ("--block-fd takes an argument"); the_fd = strtol (argv[1], &endptr, 10); if (argv[1][0] == 0 || endptr[0] != 0 || the_fd < 0) die ("Invalid fd: %s", argv[1]); opt_block_fd = the_fd; argv += 1; argc -= 1; } else if (strcmp (arg, "--info-fd") == 0) { int the_fd; char *endptr; if (argc < 2) die ("--info-fd takes an argument"); the_fd = strtol (argv[1], &endptr, 10); if (argv[1][0] == 0 || endptr[0] != 0 || the_fd < 0) die ("Invalid fd: %s", argv[1]); opt_info_fd = the_fd; argv += 1; argc -= 1; } else if (strcmp (arg, "--seccomp") == 0) { int the_fd; char *endptr; if (argc < 2) die ("--seccomp takes an argument"); the_fd = strtol (argv[1], &endptr, 10); if (argv[1][0] == 0 || endptr[0] != 0 || the_fd < 0) die ("Invalid fd: %s", argv[1]); opt_seccomp_fd = the_fd; argv += 1; argc -= 1; } else if (strcmp (arg, "--setenv") == 0) { if (argc < 3) die ("--setenv takes two arguments"); xsetenv (argv[1], argv[2], 1); argv += 2; argc -= 2; } else if (strcmp (arg, "--unsetenv") == 0) { if (argc < 2) die ("--unsetenv takes an argument"); xunsetenv (argv[1]); argv += 1; argc -= 1; } else if (strcmp (arg, "--uid") == 0) { int the_uid; char *endptr; if (argc < 2) die ("--uid takes an argument"); the_uid = strtol (argv[1], &endptr, 10); if (argv[1][0] == 0 || endptr[0] != 0 || the_uid < 0) die ("Invalid uid: %s", argv[1]); opt_sandbox_uid = the_uid; argv += 1; argc -= 1; } else if (strcmp (arg, "--gid") == 0) { int the_gid; char *endptr; if (argc < 2) die ("--gid takes an argument"); the_gid = strtol (argv[1], &endptr, 10); if (argv[1][0] == 0 || endptr[0] != 0 || the_gid < 0) die ("Invalid gid: %s", argv[1]); opt_sandbox_gid = the_gid; argv += 1; argc -= 1; } else if (strcmp (arg, "--hostname") == 0) { if (argc < 2) die ("--hostname takes an argument"); op = setup_op_new (SETUP_SET_HOSTNAME); op->dest = argv[1]; op->flags = NO_CREATE_DEST; opt_sandbox_hostname = argv[1]; argv += 1; argc -= 1; } else if (*arg == '-') { die ("Unknown option %s", arg); } else { break; } argv++; argc--; } *argcp = argc; *argvp = argv; } static void parse_args (int *argcp, char ***argvp) { int total_parsed_argc = *argcp; parse_args_recurse (argcp, argvp, FALSE, &total_parsed_argc); } static void read_overflowids (void) { cleanup_free char *uid_data = NULL; cleanup_free char *gid_data = NULL; uid_data = load_file_at (AT_FDCWD, "/proc/sys/kernel/overflowuid"); if (uid_data == NULL) die_with_error ("Can't read /proc/sys/kernel/overflowuid"); overflow_uid = strtol (uid_data, NULL, 10); if (overflow_uid == 0) die ("Can't parse /proc/sys/kernel/overflowuid"); gid_data = load_file_at (AT_FDCWD, "/proc/sys/kernel/overflowgid"); if (gid_data == NULL) die_with_error ("Can't read /proc/sys/kernel/overflowgid"); overflow_gid = strtol (gid_data, NULL, 10); if (overflow_gid == 0) die ("Can't parse /proc/sys/kernel/overflowgid"); } int main (int argc, char **argv) { mode_t old_umask; cleanup_free char *base_path = NULL; int clone_flags; char *old_cwd = NULL; pid_t pid; int event_fd = -1; int child_wait_fd = -1; const char *new_cwd; uid_t ns_uid; gid_t ns_gid; struct stat sbuf; uint64_t val; int res UNUSED; real_uid = getuid (); real_gid = getgid (); /* Get the (optional) privileges we need */ acquire_privs (); /* Never gain any more privs during exec */ if (prctl (PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) < 0) die_with_error ("prctl(PR_SET_NO_NEW_CAPS) failed"); /* The initial code is run with high permissions (i.e. CAP_SYS_ADMIN), so take lots of care. */ read_overflowids (); argv0 = argv[0]; if (isatty (1)) host_tty_dev = ttyname (1); argv++; argc--; if (argc == 0) usage (EXIT_FAILURE, stderr); parse_args (&argc, &argv); /* We have to do this if we weren't installed setuid (and we're not * root), so let's just DWIM */ if (!is_privileged && getuid () != 0) opt_unshare_user = TRUE; if (opt_unshare_user_try && stat ("/proc/self/ns/user", &sbuf) == 0) { bool disabled = FALSE; /* RHEL7 has a kernel module parameter that lets you enable user namespaces */ if (stat ("/sys/module/user_namespace/parameters/enable", &sbuf) == 0) { cleanup_free char *enable = NULL; enable = load_file_at (AT_FDCWD, "/sys/module/user_namespace/parameters/enable"); if (enable != NULL && enable[0] == 'N') disabled = TRUE; } /* Debian lets you disable *unprivileged* user namespaces. However this is not a problem if we're privileged, and if we're not opt_unshare_user is TRUE already, and there is not much we can do, its just a non-working setup. */ if (!disabled) opt_unshare_user = TRUE; } if (argc == 0) usage (EXIT_FAILURE, stderr); __debug__ (("Creating root mount point\n")); if (opt_sandbox_uid == -1) opt_sandbox_uid = real_uid; if (opt_sandbox_gid == -1) opt_sandbox_gid = real_gid; if (!opt_unshare_user && opt_sandbox_uid != real_uid) die ("Specifying --uid requires --unshare-user"); if (!opt_unshare_user && opt_sandbox_gid != real_gid) die ("Specifying --gid requires --unshare-user"); if (!opt_unshare_uts && opt_sandbox_hostname != NULL) die ("Specifying --hostname requires --unshare-uts"); /* We need to read stuff from proc during the pivot_root dance, etc. Lets keep a fd to it open */ proc_fd = open ("/proc", O_RDONLY | O_PATH); if (proc_fd == -1) die_with_error ("Can't open /proc"); /* We need *some* mountpoint where we can mount the root tmpfs. We first try in /run, and if that fails, try in /tmp. */ base_path = xasprintf ("/run/user/%d/.bubblewrap", real_uid); if (mkdir (base_path, 0755) && errno != EEXIST) { free (base_path); base_path = xasprintf ("/tmp/.bubblewrap-%d", real_uid); if (mkdir (base_path, 0755) && errno != EEXIST) die_with_error ("Creating root mountpoint failed"); } __debug__ (("creating new namespace\n")); if (opt_unshare_pid) { event_fd = eventfd (0, EFD_CLOEXEC | EFD_NONBLOCK); if (event_fd == -1) die_with_error ("eventfd()"); } /* We block sigchild here so that we can use signalfd in the monitor. */ block_sigchild (); clone_flags = SIGCHLD | CLONE_NEWNS; if (opt_unshare_user) clone_flags |= CLONE_NEWUSER; if (opt_unshare_pid) clone_flags |= CLONE_NEWPID; if (opt_unshare_net) clone_flags |= CLONE_NEWNET; if (opt_unshare_ipc) clone_flags |= CLONE_NEWIPC; if (opt_unshare_uts) clone_flags |= CLONE_NEWUTS; if (opt_unshare_cgroup) { if (stat ("/proc/self/ns/cgroup", &sbuf)) { if (errno == ENOENT) die ("Cannot create new cgroup namespace because the kernel does not support it"); else die_with_error ("stat on /proc/self/ns/cgroup failed"); } clone_flags |= CLONE_NEWCGROUP; } if (opt_unshare_cgroup_try) if (!stat ("/proc/self/ns/cgroup", &sbuf)) clone_flags |= CLONE_NEWCGROUP; child_wait_fd = eventfd (0, EFD_CLOEXEC); if (child_wait_fd == -1) die_with_error ("eventfd()"); pid = raw_clone (clone_flags, NULL); if (pid == -1) { if (opt_unshare_user) { if (errno == EINVAL) die ("Creating new namespace failed, likely because the kernel does not support user namespaces. bwrap must be installed setuid on such systems."); else if (errno == EPERM && !is_privileged) die ("No permissions to creating new namespace, likely because the kernel does not allow non-privileged user namespaces. On e.g. debian this can be enabled with 'sysctl kernel.unprivileged_userns_clone=1'."); } die_with_error ("Creating new namespace failed"); } ns_uid = opt_sandbox_uid; ns_gid = opt_sandbox_gid; if (pid != 0) { /* Parent, outside sandbox, privileged (initially) */ if (is_privileged && opt_unshare_user) { /* We're running as euid 0, but the uid we want to map is * not 0. This means we're not allowed to write this from * the child user namespace, so we do it from the parent. * * Also, we map uid/gid 0 in the namespace (to overflowuid) * if opt_needs_devpts is true, because otherwise the mount * of devpts fails due to root not being mapped. */ write_uid_gid_map (ns_uid, real_uid, ns_gid, real_gid, pid, TRUE, opt_needs_devpts); } /* Initial launched process, wait for exec:ed command to exit */ /* We don't need any privileges in the launcher, drop them immediately. */ drop_privs (); /* Let child run now that the uid maps are set up */ val = 1; res = write (child_wait_fd, &val, 8); /* Ignore res, if e.g. the child died and closed child_wait_fd we don't want to error out here */ close (child_wait_fd); if (opt_info_fd != -1) { cleanup_free char *output = xasprintf ("{\n \"child-pid\": %i\n}\n", pid); size_t len = strlen (output); if (write (opt_info_fd, output, len) != len) die_with_error ("Write to info_fd"); close (opt_info_fd); } monitor_child (event_fd); exit (0); /* Should not be reached, but better safe... */ } /* Child, in sandbox, privileged in the parent or in the user namespace (if --unshare-user). * * Note that for user namespaces we run as euid 0 during clone(), so * the child user namespace is owned by euid 0., This means that the * regular user namespace parent (with uid != 0) doesn't have any * capabilities in it, which is nice as we can't exploit those. In * particular the parent user namespace doesn't have CAP_PTRACE * which would otherwise allow the parent to hijack of the child * after this point. * * Unfortunately this also means you can't ptrace the final * sandboxed process from outside the sandbox either. */ if (opt_info_fd != -1) close (opt_info_fd); /* Wait for the parent to init uid/gid maps and drop caps */ res = read (child_wait_fd, &val, 8); close (child_wait_fd); /* At this point we can completely drop root uid, but retain the * required permitted caps. This allow us to do full setup as * the user uid, which makes e.g. fuse access work. */ switch_to_user_with_privs (); if (opt_unshare_net && loopback_setup () != 0) die ("Can't create loopback device"); ns_uid = opt_sandbox_uid; ns_gid = opt_sandbox_gid; if (!is_privileged && opt_unshare_user) { /* In the unprivileged case we have to write the uid/gid maps in * the child, because we have no caps in the parent */ if (opt_needs_devpts) { /* This is a bit hacky, but we need to first map the real uid/gid to 0, otherwise we can't mount the devpts filesystem because root is not mapped. Later we will create another child user namespace and map back to the real uid */ ns_uid = 0; ns_gid = 0; } write_uid_gid_map (ns_uid, real_uid, ns_gid, real_gid, -1, TRUE, FALSE); } old_umask = umask (0); /* Need to do this before the chroot, but after we're the real uid */ resolve_symlinks_in_ops (); /* Mark everything as slave, so that we still * receive mounts from the real root, but don't * propagate mounts to the real root. */ if (mount (NULL, "/", NULL, MS_SLAVE | MS_REC, NULL) < 0) die_with_error ("Failed to make / slave"); /* Create a tmpfs which we will use as / in the namespace */ if (mount ("", base_path, "tmpfs", MS_NODEV | MS_NOSUID, NULL) != 0) die_with_error ("Failed to mount tmpfs"); old_cwd = get_current_dir_name (); /* Chdir to the new root tmpfs mount. This will be the CWD during the entire setup. Access old or new root via "oldroot" and "newroot". */ if (chdir (base_path) != 0) die_with_error ("chdir base_path"); /* We create a subdir "$base_path/newroot" for the new root, that * way we can pivot_root to base_path, and put the old root at * "$base_path/oldroot". This avoids problems accessing the oldroot * dir if the user requested to bind mount something over / */ if (mkdir ("newroot", 0755)) die_with_error ("Creating newroot failed"); if (mkdir ("oldroot", 0755)) die_with_error ("Creating oldroot failed"); if (pivot_root (base_path, "oldroot")) die_with_error ("pivot_root"); if (chdir ("/") != 0) die_with_error ("chdir / (base path)"); if (is_privileged) { pid_t child; int privsep_sockets[2]; if (socketpair (AF_UNIX, SOCK_SEQPACKET | SOCK_CLOEXEC, 0, privsep_sockets) != 0) die_with_error ("Can't create privsep socket"); child = fork (); if (child == -1) die_with_error ("Can't fork unprivileged helper"); if (child == 0) { /* Unprivileged setup process */ drop_privs (); close (privsep_sockets[0]); setup_newroot (opt_unshare_pid, privsep_sockets[1]); exit (0); } else { int status; uint32_t buffer[2048]; /* 8k, but is int32 to guarantee nice alignment */ uint32_t op, flags; const char *arg1, *arg2; cleanup_fd int unpriv_socket = -1; unpriv_socket = privsep_sockets[0]; close (privsep_sockets[1]); do { op = read_priv_sec_op (unpriv_socket, buffer, sizeof (buffer), &flags, &arg1, &arg2); privileged_op (-1, op, flags, arg1, arg2); if (write (unpriv_socket, buffer, 1) != 1) die ("Can't write to op_socket"); } while (op != PRIV_SEP_OP_DONE); waitpid (child, &status, 0); /* Continue post setup */ } } else { setup_newroot (opt_unshare_pid, -1); } /* The old root better be rprivate or we will send unmount events to the parent namespace */ if (mount ("oldroot", "oldroot", NULL, MS_REC | MS_PRIVATE, NULL) != 0) die_with_error ("Failed to make old root rprivate"); if (umount2 ("oldroot", MNT_DETACH)) die_with_error ("unmount old root"); if (opt_unshare_user && (ns_uid != opt_sandbox_uid || ns_gid != opt_sandbox_gid)) { /* Now that devpts is mounted and we've no need for mount permissions we can create a new userspace and map our uid 1:1 */ if (unshare (CLONE_NEWUSER)) die_with_error ("unshare user ns"); write_uid_gid_map (opt_sandbox_uid, ns_uid, opt_sandbox_gid, ns_gid, -1, FALSE, FALSE); } /* Now make /newroot the real root */ if (chdir ("/newroot") != 0) die_with_error ("chdir newroot"); if (chroot ("/newroot") != 0) die_with_error ("chroot /newroot"); if (chdir ("/") != 0) die_with_error ("chdir /"); /* All privileged ops are done now, so drop it */ drop_privs (); if (opt_block_fd != -1) { char b[1]; read (opt_block_fd, b, 1); close (opt_block_fd); } if (opt_seccomp_fd != -1) { cleanup_free char *seccomp_data = NULL; size_t seccomp_len; struct sock_fprog prog; seccomp_data = load_file_data (opt_seccomp_fd, &seccomp_len); if (seccomp_data == NULL) die_with_error ("Can't read seccomp data"); if (seccomp_len % 8 != 0) die ("Invalid seccomp data, must be multiple of 8"); prog.len = seccomp_len / 8; prog.filter = (struct sock_filter *) seccomp_data; close (opt_seccomp_fd); if (prctl (PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &prog) != 0) die_with_error ("prctl(PR_SET_SECCOMP)"); } umask (old_umask); new_cwd = "/"; if (opt_chdir_path) { if (chdir (opt_chdir_path)) die_with_error ("Can't chdir to %s", opt_chdir_path); new_cwd = opt_chdir_path; } else if (chdir (old_cwd) == 0) { /* If the old cwd is mapped in the sandbox, go there */ new_cwd = old_cwd; } else { /* If the old cwd is not mapped, go to home */ const char *home = getenv ("HOME"); if (home != NULL && chdir (home) == 0) new_cwd = home; } xsetenv ("PWD", new_cwd, 1); free (old_cwd); __debug__ (("forking for child\n")); if (opt_unshare_pid || lock_files != NULL || opt_sync_fd != -1) { /* We have to have a pid 1 in the pid namespace, because * otherwise we'll get a bunch of zombies as nothing reaps * them. Alternatively if we're using sync_fd or lock_files we * need some process to own these. */ pid = fork (); if (pid == -1) die_with_error ("Can't fork for pid 1"); if (pid != 0) { /* Close fds in pid 1, except stdio and optionally event_fd (for syncing pid 2 lifetime with monitor_child) and opt_sync_fd (for syncing sandbox lifetime with outside process). Any other fds will been passed on to the child though. */ { int dont_close[3]; int j = 0; if (event_fd != -1) dont_close[j++] = event_fd; if (opt_sync_fd != -1) dont_close[j++] = opt_sync_fd; dont_close[j++] = -1; fdwalk (proc_fd, close_extra_fds, dont_close); } return do_init (event_fd, pid); } } __debug__ (("launch executable %s\n", argv[0])); if (proc_fd != -1) close (proc_fd); if (opt_sync_fd != -1) close (opt_sync_fd); /* We want sigchild in the child */ unblock_sigchild (); if (setsid () == (pid_t) -1) die_with_error ("setsid"); if (label_exec (opt_exec_label) == -1) die_with_error ("label_exec %s", argv[0]); if (execvp (argv[0], argv) == -1) die_with_error ("execvp %s", argv[0]); return 0; }
./CrossVul/dataset_final_sorted/CWE-20/c/good_3088_0
crossvul-cpp_data_bad_5418_3
/* * Copyright (c) 2001-2002 Michael David Adams. * All rights reserved. */ /* __START_OF_JASPER_LICENSE__ * * JasPer License Version 2.0 * * Copyright (c) 2001-2006 Michael David Adams * Copyright (c) 1999-2000 Image Power, Inc. * Copyright (c) 1999-2000 The University of British Columbia * * All rights reserved. * * Permission is hereby granted, free of charge, to any person (the * "User") obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, * publish, distribute, and/or sell copies of the Software, and to permit * persons to whom the Software is furnished to do so, subject to the * following conditions: * * 1. The above copyright notices and this permission notice (which * includes the disclaimer below) shall be included in all copies or * substantial portions of the Software. * * 2. The name of a copyright holder shall not be used to endorse or * promote products derived from the Software without specific prior * written permission. * * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY. * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES, * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH, * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. * * __END_OF_JASPER_LICENSE__ */ /******************************************************************************\ * Includes. \******************************************************************************/ #include <stdarg.h> #include <stdio.h> #include "jasper/jas_types.h" #include "jasper/jas_debug.h" /******************************************************************************\ * Local data. \******************************************************************************/ static int jas_dbglevel = 0; /* The debug level. */ /******************************************************************************\ * Code for getting/setting the debug level. \******************************************************************************/ /* Set the library debug level. */ int jas_setdbglevel(int dbglevel) { int olddbglevel; /* Save the old debug level. */ olddbglevel = jas_dbglevel; /* Change the debug level. */ jas_dbglevel = dbglevel; /* Return the old debug level. */ return olddbglevel; } /* Get the library debug level. */ int jas_getdbglevel() { return jas_dbglevel; } /******************************************************************************\ * Code. \******************************************************************************/ /* Perform formatted output to standard error. */ int jas_eprintf(const char *fmt, ...) { int ret; va_list ap; va_start(ap, fmt); ret = vfprintf(stderr, fmt, ap); va_end(ap); return ret; } /* Dump memory to a stream. */ int jas_memdump(FILE *out, void *data, size_t len) { size_t i; size_t j; uchar *dp; dp = data; for (i = 0; i < len; i += 16) { fprintf(out, "%04zx:", i); for (j = 0; j < 16; ++j) { if (i + j < len) { fprintf(out, " %02x", dp[i + j]); } } fprintf(out, "\n"); } return 0; } /******************************************************************************\ * Code. \******************************************************************************/ void jas_deprecated(const char *s) { static char message[] = "WARNING!!! WARNING!!! WARNING!!! WARNING!!! WARNING!!! WARNING!!!\n" "WARNING!!! WARNING!!! WARNING!!! WARNING!!! WARNING!!! WARNING!!!\n" "WARNING!!! WARNING!!! WARNING!!! WARNING!!! WARNING!!! WARNING!!!\n" "YOUR CODE IS RELYING ON DEPRECATED FUNCTIONALTIY IN THE JASPER LIBRARY.\n" "THIS FUNCTIONALITY WILL BE REMOVED IN THE NEAR FUTURE.\n" "PLEASE FIX THIS PROBLEM BEFORE YOUR CODE STOPS WORKING!\n" ; jas_eprintf("%s", message); jas_eprintf("The specific problem is as follows:\n%s\n", s); //abort(); }
./CrossVul/dataset_final_sorted/CWE-20/c/bad_5418_3
crossvul-cpp_data_bad_2433_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % DDDD DDDD SSSSS % % D D D D SS % % D D D D SSS % % D D D D SS % % DDDD DDDD SSSSS % % % % % % Read/Write Microsoft Direct Draw Surface Image Format % % % % Software Design % % Bianca van Schaik % % March 2008 % % Dirk Lemstra % % September 2013 % % % % % % 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 "magick/studio.h" #include "magick/attribute.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/cache.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/log.h" #include "magick/magick.h" #include "magick/memory_.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/option.h" #include "magick/pixel-accessor.h" #include "magick/profile.h" #include "magick/quantum.h" #include "magick/quantum-private.h" #include "magick/resource_.h" #include "magick/static.h" #include "magick/string_.h" #include "magick/string-private.h" #include "magick/module.h" #include "magick/transform.h" /* Definitions */ #define DDSD_CAPS 0x00000001 #define DDSD_HEIGHT 0x00000002 #define DDSD_WIDTH 0x00000004 #define DDSD_PITCH 0x00000008 #define DDSD_PIXELFORMAT 0x00001000 #define DDSD_MIPMAPCOUNT 0x00020000 #define DDSD_LINEARSIZE 0x00080000 #define DDSD_DEPTH 0x00800000 #define DDPF_ALPHAPIXELS 0x00000001 #define DDPF_FOURCC 0x00000004 #define DDPF_RGB 0x00000040 #define DDPF_LUMINANCE 0x00020000 #define FOURCC_DXT1 0x31545844 #define FOURCC_DXT3 0x33545844 #define FOURCC_DXT5 0x35545844 #define DDSCAPS_COMPLEX 0x00000008 #define DDSCAPS_TEXTURE 0x00001000 #define DDSCAPS_MIPMAP 0x00400000 #define DDSCAPS2_CUBEMAP 0x00000200 #define DDSCAPS2_CUBEMAP_POSITIVEX 0x00000400 #define DDSCAPS2_CUBEMAP_NEGATIVEX 0x00000800 #define DDSCAPS2_CUBEMAP_POSITIVEY 0x00001000 #define DDSCAPS2_CUBEMAP_NEGATIVEY 0x00002000 #define DDSCAPS2_CUBEMAP_POSITIVEZ 0x00004000 #define DDSCAPS2_CUBEMAP_NEGATIVEZ 0x00008000 #define DDSCAPS2_VOLUME 0x00200000 #ifndef SIZE_MAX #define SIZE_MAX ((size_t) -1) #endif /* Structure declarations. */ typedef struct _DDSPixelFormat { size_t flags, fourcc, rgb_bitcount, r_bitmask, g_bitmask, b_bitmask, alpha_bitmask; } DDSPixelFormat; typedef struct _DDSInfo { size_t flags, height, width, pitchOrLinearSize, depth, mipmapcount, ddscaps1, ddscaps2; DDSPixelFormat pixelformat; } DDSInfo; typedef struct _DDSColors { unsigned char r[4], g[4], b[4], a[4]; } DDSColors; typedef struct _DDSVector4 { float x, y, z, w; } DDSVector4; typedef struct _DDSVector3 { float x, y, z; } DDSVector3; typedef struct _DDSSourceBlock { unsigned char start, end, error; } DDSSourceBlock; typedef struct _DDSSingleColourLookup { DDSSourceBlock sources[2]; } DDSSingleColourLookup; typedef MagickBooleanType DDSDecoder(Image *, DDSInfo *, ExceptionInfo *); static const DDSSingleColourLookup DDSLookup_5_4[] = { { { { 0, 0, 0 }, { 0, 0, 0 } } }, { { { 0, 0, 1 }, { 0, 1, 1 } } }, { { { 0, 0, 2 }, { 0, 1, 0 } } }, { { { 0, 0, 3 }, { 0, 1, 1 } } }, { { { 0, 0, 4 }, { 0, 2, 1 } } }, { { { 1, 0, 3 }, { 0, 2, 0 } } }, { { { 1, 0, 2 }, { 0, 2, 1 } } }, { { { 1, 0, 1 }, { 0, 3, 1 } } }, { { { 1, 0, 0 }, { 0, 3, 0 } } }, { { { 1, 0, 1 }, { 1, 2, 1 } } }, { { { 1, 0, 2 }, { 1, 2, 0 } } }, { { { 1, 0, 3 }, { 0, 4, 0 } } }, { { { 1, 0, 4 }, { 0, 5, 1 } } }, { { { 2, 0, 3 }, { 0, 5, 0 } } }, { { { 2, 0, 2 }, { 0, 5, 1 } } }, { { { 2, 0, 1 }, { 0, 6, 1 } } }, { { { 2, 0, 0 }, { 0, 6, 0 } } }, { { { 2, 0, 1 }, { 2, 3, 1 } } }, { { { 2, 0, 2 }, { 2, 3, 0 } } }, { { { 2, 0, 3 }, { 0, 7, 0 } } }, { { { 2, 0, 4 }, { 1, 6, 1 } } }, { { { 3, 0, 3 }, { 1, 6, 0 } } }, { { { 3, 0, 2 }, { 0, 8, 0 } } }, { { { 3, 0, 1 }, { 0, 9, 1 } } }, { { { 3, 0, 0 }, { 0, 9, 0 } } }, { { { 3, 0, 1 }, { 0, 9, 1 } } }, { { { 3, 0, 2 }, { 0, 10, 1 } } }, { { { 3, 0, 3 }, { 0, 10, 0 } } }, { { { 3, 0, 4 }, { 2, 7, 1 } } }, { { { 4, 0, 4 }, { 2, 7, 0 } } }, { { { 4, 0, 3 }, { 0, 11, 0 } } }, { { { 4, 0, 2 }, { 1, 10, 1 } } }, { { { 4, 0, 1 }, { 1, 10, 0 } } }, { { { 4, 0, 0 }, { 0, 12, 0 } } }, { { { 4, 0, 1 }, { 0, 13, 1 } } }, { { { 4, 0, 2 }, { 0, 13, 0 } } }, { { { 4, 0, 3 }, { 0, 13, 1 } } }, { { { 4, 0, 4 }, { 0, 14, 1 } } }, { { { 5, 0, 3 }, { 0, 14, 0 } } }, { { { 5, 0, 2 }, { 2, 11, 1 } } }, { { { 5, 0, 1 }, { 2, 11, 0 } } }, { { { 5, 0, 0 }, { 0, 15, 0 } } }, { { { 5, 0, 1 }, { 1, 14, 1 } } }, { { { 5, 0, 2 }, { 1, 14, 0 } } }, { { { 5, 0, 3 }, { 0, 16, 0 } } }, { { { 5, 0, 4 }, { 0, 17, 1 } } }, { { { 6, 0, 3 }, { 0, 17, 0 } } }, { { { 6, 0, 2 }, { 0, 17, 1 } } }, { { { 6, 0, 1 }, { 0, 18, 1 } } }, { { { 6, 0, 0 }, { 0, 18, 0 } } }, { { { 6, 0, 1 }, { 2, 15, 1 } } }, { { { 6, 0, 2 }, { 2, 15, 0 } } }, { { { 6, 0, 3 }, { 0, 19, 0 } } }, { { { 6, 0, 4 }, { 1, 18, 1 } } }, { { { 7, 0, 3 }, { 1, 18, 0 } } }, { { { 7, 0, 2 }, { 0, 20, 0 } } }, { { { 7, 0, 1 }, { 0, 21, 1 } } }, { { { 7, 0, 0 }, { 0, 21, 0 } } }, { { { 7, 0, 1 }, { 0, 21, 1 } } }, { { { 7, 0, 2 }, { 0, 22, 1 } } }, { { { 7, 0, 3 }, { 0, 22, 0 } } }, { { { 7, 0, 4 }, { 2, 19, 1 } } }, { { { 8, 0, 4 }, { 2, 19, 0 } } }, { { { 8, 0, 3 }, { 0, 23, 0 } } }, { { { 8, 0, 2 }, { 1, 22, 1 } } }, { { { 8, 0, 1 }, { 1, 22, 0 } } }, { { { 8, 0, 0 }, { 0, 24, 0 } } }, { { { 8, 0, 1 }, { 0, 25, 1 } } }, { { { 8, 0, 2 }, { 0, 25, 0 } } }, { { { 8, 0, 3 }, { 0, 25, 1 } } }, { { { 8, 0, 4 }, { 0, 26, 1 } } }, { { { 9, 0, 3 }, { 0, 26, 0 } } }, { { { 9, 0, 2 }, { 2, 23, 1 } } }, { { { 9, 0, 1 }, { 2, 23, 0 } } }, { { { 9, 0, 0 }, { 0, 27, 0 } } }, { { { 9, 0, 1 }, { 1, 26, 1 } } }, { { { 9, 0, 2 }, { 1, 26, 0 } } }, { { { 9, 0, 3 }, { 0, 28, 0 } } }, { { { 9, 0, 4 }, { 0, 29, 1 } } }, { { { 10, 0, 3 }, { 0, 29, 0 } } }, { { { 10, 0, 2 }, { 0, 29, 1 } } }, { { { 10, 0, 1 }, { 0, 30, 1 } } }, { { { 10, 0, 0 }, { 0, 30, 0 } } }, { { { 10, 0, 1 }, { 2, 27, 1 } } }, { { { 10, 0, 2 }, { 2, 27, 0 } } }, { { { 10, 0, 3 }, { 0, 31, 0 } } }, { { { 10, 0, 4 }, { 1, 30, 1 } } }, { { { 11, 0, 3 }, { 1, 30, 0 } } }, { { { 11, 0, 2 }, { 4, 24, 0 } } }, { { { 11, 0, 1 }, { 1, 31, 1 } } }, { { { 11, 0, 0 }, { 1, 31, 0 } } }, { { { 11, 0, 1 }, { 1, 31, 1 } } }, { { { 11, 0, 2 }, { 2, 30, 1 } } }, { { { 11, 0, 3 }, { 2, 30, 0 } } }, { { { 11, 0, 4 }, { 2, 31, 1 } } }, { { { 12, 0, 4 }, { 2, 31, 0 } } }, { { { 12, 0, 3 }, { 4, 27, 0 } } }, { { { 12, 0, 2 }, { 3, 30, 1 } } }, { { { 12, 0, 1 }, { 3, 30, 0 } } }, { { { 12, 0, 0 }, { 4, 28, 0 } } }, { { { 12, 0, 1 }, { 3, 31, 1 } } }, { { { 12, 0, 2 }, { 3, 31, 0 } } }, { { { 12, 0, 3 }, { 3, 31, 1 } } }, { { { 12, 0, 4 }, { 4, 30, 1 } } }, { { { 13, 0, 3 }, { 4, 30, 0 } } }, { { { 13, 0, 2 }, { 6, 27, 1 } } }, { { { 13, 0, 1 }, { 6, 27, 0 } } }, { { { 13, 0, 0 }, { 4, 31, 0 } } }, { { { 13, 0, 1 }, { 5, 30, 1 } } }, { { { 13, 0, 2 }, { 5, 30, 0 } } }, { { { 13, 0, 3 }, { 8, 24, 0 } } }, { { { 13, 0, 4 }, { 5, 31, 1 } } }, { { { 14, 0, 3 }, { 5, 31, 0 } } }, { { { 14, 0, 2 }, { 5, 31, 1 } } }, { { { 14, 0, 1 }, { 6, 30, 1 } } }, { { { 14, 0, 0 }, { 6, 30, 0 } } }, { { { 14, 0, 1 }, { 6, 31, 1 } } }, { { { 14, 0, 2 }, { 6, 31, 0 } } }, { { { 14, 0, 3 }, { 8, 27, 0 } } }, { { { 14, 0, 4 }, { 7, 30, 1 } } }, { { { 15, 0, 3 }, { 7, 30, 0 } } }, { { { 15, 0, 2 }, { 8, 28, 0 } } }, { { { 15, 0, 1 }, { 7, 31, 1 } } }, { { { 15, 0, 0 }, { 7, 31, 0 } } }, { { { 15, 0, 1 }, { 7, 31, 1 } } }, { { { 15, 0, 2 }, { 8, 30, 1 } } }, { { { 15, 0, 3 }, { 8, 30, 0 } } }, { { { 15, 0, 4 }, { 10, 27, 1 } } }, { { { 16, 0, 4 }, { 10, 27, 0 } } }, { { { 16, 0, 3 }, { 8, 31, 0 } } }, { { { 16, 0, 2 }, { 9, 30, 1 } } }, { { { 16, 0, 1 }, { 9, 30, 0 } } }, { { { 16, 0, 0 }, { 12, 24, 0 } } }, { { { 16, 0, 1 }, { 9, 31, 1 } } }, { { { 16, 0, 2 }, { 9, 31, 0 } } }, { { { 16, 0, 3 }, { 9, 31, 1 } } }, { { { 16, 0, 4 }, { 10, 30, 1 } } }, { { { 17, 0, 3 }, { 10, 30, 0 } } }, { { { 17, 0, 2 }, { 10, 31, 1 } } }, { { { 17, 0, 1 }, { 10, 31, 0 } } }, { { { 17, 0, 0 }, { 12, 27, 0 } } }, { { { 17, 0, 1 }, { 11, 30, 1 } } }, { { { 17, 0, 2 }, { 11, 30, 0 } } }, { { { 17, 0, 3 }, { 12, 28, 0 } } }, { { { 17, 0, 4 }, { 11, 31, 1 } } }, { { { 18, 0, 3 }, { 11, 31, 0 } } }, { { { 18, 0, 2 }, { 11, 31, 1 } } }, { { { 18, 0, 1 }, { 12, 30, 1 } } }, { { { 18, 0, 0 }, { 12, 30, 0 } } }, { { { 18, 0, 1 }, { 14, 27, 1 } } }, { { { 18, 0, 2 }, { 14, 27, 0 } } }, { { { 18, 0, 3 }, { 12, 31, 0 } } }, { { { 18, 0, 4 }, { 13, 30, 1 } } }, { { { 19, 0, 3 }, { 13, 30, 0 } } }, { { { 19, 0, 2 }, { 16, 24, 0 } } }, { { { 19, 0, 1 }, { 13, 31, 1 } } }, { { { 19, 0, 0 }, { 13, 31, 0 } } }, { { { 19, 0, 1 }, { 13, 31, 1 } } }, { { { 19, 0, 2 }, { 14, 30, 1 } } }, { { { 19, 0, 3 }, { 14, 30, 0 } } }, { { { 19, 0, 4 }, { 14, 31, 1 } } }, { { { 20, 0, 4 }, { 14, 31, 0 } } }, { { { 20, 0, 3 }, { 16, 27, 0 } } }, { { { 20, 0, 2 }, { 15, 30, 1 } } }, { { { 20, 0, 1 }, { 15, 30, 0 } } }, { { { 20, 0, 0 }, { 16, 28, 0 } } }, { { { 20, 0, 1 }, { 15, 31, 1 } } }, { { { 20, 0, 2 }, { 15, 31, 0 } } }, { { { 20, 0, 3 }, { 15, 31, 1 } } }, { { { 20, 0, 4 }, { 16, 30, 1 } } }, { { { 21, 0, 3 }, { 16, 30, 0 } } }, { { { 21, 0, 2 }, { 18, 27, 1 } } }, { { { 21, 0, 1 }, { 18, 27, 0 } } }, { { { 21, 0, 0 }, { 16, 31, 0 } } }, { { { 21, 0, 1 }, { 17, 30, 1 } } }, { { { 21, 0, 2 }, { 17, 30, 0 } } }, { { { 21, 0, 3 }, { 20, 24, 0 } } }, { { { 21, 0, 4 }, { 17, 31, 1 } } }, { { { 22, 0, 3 }, { 17, 31, 0 } } }, { { { 22, 0, 2 }, { 17, 31, 1 } } }, { { { 22, 0, 1 }, { 18, 30, 1 } } }, { { { 22, 0, 0 }, { 18, 30, 0 } } }, { { { 22, 0, 1 }, { 18, 31, 1 } } }, { { { 22, 0, 2 }, { 18, 31, 0 } } }, { { { 22, 0, 3 }, { 20, 27, 0 } } }, { { { 22, 0, 4 }, { 19, 30, 1 } } }, { { { 23, 0, 3 }, { 19, 30, 0 } } }, { { { 23, 0, 2 }, { 20, 28, 0 } } }, { { { 23, 0, 1 }, { 19, 31, 1 } } }, { { { 23, 0, 0 }, { 19, 31, 0 } } }, { { { 23, 0, 1 }, { 19, 31, 1 } } }, { { { 23, 0, 2 }, { 20, 30, 1 } } }, { { { 23, 0, 3 }, { 20, 30, 0 } } }, { { { 23, 0, 4 }, { 22, 27, 1 } } }, { { { 24, 0, 4 }, { 22, 27, 0 } } }, { { { 24, 0, 3 }, { 20, 31, 0 } } }, { { { 24, 0, 2 }, { 21, 30, 1 } } }, { { { 24, 0, 1 }, { 21, 30, 0 } } }, { { { 24, 0, 0 }, { 24, 24, 0 } } }, { { { 24, 0, 1 }, { 21, 31, 1 } } }, { { { 24, 0, 2 }, { 21, 31, 0 } } }, { { { 24, 0, 3 }, { 21, 31, 1 } } }, { { { 24, 0, 4 }, { 22, 30, 1 } } }, { { { 25, 0, 3 }, { 22, 30, 0 } } }, { { { 25, 0, 2 }, { 22, 31, 1 } } }, { { { 25, 0, 1 }, { 22, 31, 0 } } }, { { { 25, 0, 0 }, { 24, 27, 0 } } }, { { { 25, 0, 1 }, { 23, 30, 1 } } }, { { { 25, 0, 2 }, { 23, 30, 0 } } }, { { { 25, 0, 3 }, { 24, 28, 0 } } }, { { { 25, 0, 4 }, { 23, 31, 1 } } }, { { { 26, 0, 3 }, { 23, 31, 0 } } }, { { { 26, 0, 2 }, { 23, 31, 1 } } }, { { { 26, 0, 1 }, { 24, 30, 1 } } }, { { { 26, 0, 0 }, { 24, 30, 0 } } }, { { { 26, 0, 1 }, { 26, 27, 1 } } }, { { { 26, 0, 2 }, { 26, 27, 0 } } }, { { { 26, 0, 3 }, { 24, 31, 0 } } }, { { { 26, 0, 4 }, { 25, 30, 1 } } }, { { { 27, 0, 3 }, { 25, 30, 0 } } }, { { { 27, 0, 2 }, { 28, 24, 0 } } }, { { { 27, 0, 1 }, { 25, 31, 1 } } }, { { { 27, 0, 0 }, { 25, 31, 0 } } }, { { { 27, 0, 1 }, { 25, 31, 1 } } }, { { { 27, 0, 2 }, { 26, 30, 1 } } }, { { { 27, 0, 3 }, { 26, 30, 0 } } }, { { { 27, 0, 4 }, { 26, 31, 1 } } }, { { { 28, 0, 4 }, { 26, 31, 0 } } }, { { { 28, 0, 3 }, { 28, 27, 0 } } }, { { { 28, 0, 2 }, { 27, 30, 1 } } }, { { { 28, 0, 1 }, { 27, 30, 0 } } }, { { { 28, 0, 0 }, { 28, 28, 0 } } }, { { { 28, 0, 1 }, { 27, 31, 1 } } }, { { { 28, 0, 2 }, { 27, 31, 0 } } }, { { { 28, 0, 3 }, { 27, 31, 1 } } }, { { { 28, 0, 4 }, { 28, 30, 1 } } }, { { { 29, 0, 3 }, { 28, 30, 0 } } }, { { { 29, 0, 2 }, { 30, 27, 1 } } }, { { { 29, 0, 1 }, { 30, 27, 0 } } }, { { { 29, 0, 0 }, { 28, 31, 0 } } }, { { { 29, 0, 1 }, { 29, 30, 1 } } }, { { { 29, 0, 2 }, { 29, 30, 0 } } }, { { { 29, 0, 3 }, { 29, 30, 1 } } }, { { { 29, 0, 4 }, { 29, 31, 1 } } }, { { { 30, 0, 3 }, { 29, 31, 0 } } }, { { { 30, 0, 2 }, { 29, 31, 1 } } }, { { { 30, 0, 1 }, { 30, 30, 1 } } }, { { { 30, 0, 0 }, { 30, 30, 0 } } }, { { { 30, 0, 1 }, { 30, 31, 1 } } }, { { { 30, 0, 2 }, { 30, 31, 0 } } }, { { { 30, 0, 3 }, { 30, 31, 1 } } }, { { { 30, 0, 4 }, { 31, 30, 1 } } }, { { { 31, 0, 3 }, { 31, 30, 0 } } }, { { { 31, 0, 2 }, { 31, 30, 1 } } }, { { { 31, 0, 1 }, { 31, 31, 1 } } }, { { { 31, 0, 0 }, { 31, 31, 0 } } } }; static const DDSSingleColourLookup DDSLookup_6_4[] = { { { { 0, 0, 0 }, { 0, 0, 0 } } }, { { { 0, 0, 1 }, { 0, 1, 0 } } }, { { { 0, 0, 2 }, { 0, 2, 0 } } }, { { { 1, 0, 1 }, { 0, 3, 1 } } }, { { { 1, 0, 0 }, { 0, 3, 0 } } }, { { { 1, 0, 1 }, { 0, 4, 0 } } }, { { { 1, 0, 2 }, { 0, 5, 0 } } }, { { { 2, 0, 1 }, { 0, 6, 1 } } }, { { { 2, 0, 0 }, { 0, 6, 0 } } }, { { { 2, 0, 1 }, { 0, 7, 0 } } }, { { { 2, 0, 2 }, { 0, 8, 0 } } }, { { { 3, 0, 1 }, { 0, 9, 1 } } }, { { { 3, 0, 0 }, { 0, 9, 0 } } }, { { { 3, 0, 1 }, { 0, 10, 0 } } }, { { { 3, 0, 2 }, { 0, 11, 0 } } }, { { { 4, 0, 1 }, { 0, 12, 1 } } }, { { { 4, 0, 0 }, { 0, 12, 0 } } }, { { { 4, 0, 1 }, { 0, 13, 0 } } }, { { { 4, 0, 2 }, { 0, 14, 0 } } }, { { { 5, 0, 1 }, { 0, 15, 1 } } }, { { { 5, 0, 0 }, { 0, 15, 0 } } }, { { { 5, 0, 1 }, { 0, 16, 0 } } }, { { { 5, 0, 2 }, { 1, 15, 0 } } }, { { { 6, 0, 1 }, { 0, 17, 0 } } }, { { { 6, 0, 0 }, { 0, 18, 0 } } }, { { { 6, 0, 1 }, { 0, 19, 0 } } }, { { { 6, 0, 2 }, { 3, 14, 0 } } }, { { { 7, 0, 1 }, { 0, 20, 0 } } }, { { { 7, 0, 0 }, { 0, 21, 0 } } }, { { { 7, 0, 1 }, { 0, 22, 0 } } }, { { { 7, 0, 2 }, { 4, 15, 0 } } }, { { { 8, 0, 1 }, { 0, 23, 0 } } }, { { { 8, 0, 0 }, { 0, 24, 0 } } }, { { { 8, 0, 1 }, { 0, 25, 0 } } }, { { { 8, 0, 2 }, { 6, 14, 0 } } }, { { { 9, 0, 1 }, { 0, 26, 0 } } }, { { { 9, 0, 0 }, { 0, 27, 0 } } }, { { { 9, 0, 1 }, { 0, 28, 0 } } }, { { { 9, 0, 2 }, { 7, 15, 0 } } }, { { { 10, 0, 1 }, { 0, 29, 0 } } }, { { { 10, 0, 0 }, { 0, 30, 0 } } }, { { { 10, 0, 1 }, { 0, 31, 0 } } }, { { { 10, 0, 2 }, { 9, 14, 0 } } }, { { { 11, 0, 1 }, { 0, 32, 0 } } }, { { { 11, 0, 0 }, { 0, 33, 0 } } }, { { { 11, 0, 1 }, { 2, 30, 0 } } }, { { { 11, 0, 2 }, { 0, 34, 0 } } }, { { { 12, 0, 1 }, { 0, 35, 0 } } }, { { { 12, 0, 0 }, { 0, 36, 0 } } }, { { { 12, 0, 1 }, { 3, 31, 0 } } }, { { { 12, 0, 2 }, { 0, 37, 0 } } }, { { { 13, 0, 1 }, { 0, 38, 0 } } }, { { { 13, 0, 0 }, { 0, 39, 0 } } }, { { { 13, 0, 1 }, { 5, 30, 0 } } }, { { { 13, 0, 2 }, { 0, 40, 0 } } }, { { { 14, 0, 1 }, { 0, 41, 0 } } }, { { { 14, 0, 0 }, { 0, 42, 0 } } }, { { { 14, 0, 1 }, { 6, 31, 0 } } }, { { { 14, 0, 2 }, { 0, 43, 0 } } }, { { { 15, 0, 1 }, { 0, 44, 0 } } }, { { { 15, 0, 0 }, { 0, 45, 0 } } }, { { { 15, 0, 1 }, { 8, 30, 0 } } }, { { { 15, 0, 2 }, { 0, 46, 0 } } }, { { { 16, 0, 2 }, { 0, 47, 0 } } }, { { { 16, 0, 1 }, { 1, 46, 0 } } }, { { { 16, 0, 0 }, { 0, 48, 0 } } }, { { { 16, 0, 1 }, { 0, 49, 0 } } }, { { { 16, 0, 2 }, { 0, 50, 0 } } }, { { { 17, 0, 1 }, { 2, 47, 0 } } }, { { { 17, 0, 0 }, { 0, 51, 0 } } }, { { { 17, 0, 1 }, { 0, 52, 0 } } }, { { { 17, 0, 2 }, { 0, 53, 0 } } }, { { { 18, 0, 1 }, { 4, 46, 0 } } }, { { { 18, 0, 0 }, { 0, 54, 0 } } }, { { { 18, 0, 1 }, { 0, 55, 0 } } }, { { { 18, 0, 2 }, { 0, 56, 0 } } }, { { { 19, 0, 1 }, { 5, 47, 0 } } }, { { { 19, 0, 0 }, { 0, 57, 0 } } }, { { { 19, 0, 1 }, { 0, 58, 0 } } }, { { { 19, 0, 2 }, { 0, 59, 0 } } }, { { { 20, 0, 1 }, { 7, 46, 0 } } }, { { { 20, 0, 0 }, { 0, 60, 0 } } }, { { { 20, 0, 1 }, { 0, 61, 0 } } }, { { { 20, 0, 2 }, { 0, 62, 0 } } }, { { { 21, 0, 1 }, { 8, 47, 0 } } }, { { { 21, 0, 0 }, { 0, 63, 0 } } }, { { { 21, 0, 1 }, { 1, 62, 0 } } }, { { { 21, 0, 2 }, { 1, 63, 0 } } }, { { { 22, 0, 1 }, { 10, 46, 0 } } }, { { { 22, 0, 0 }, { 2, 62, 0 } } }, { { { 22, 0, 1 }, { 2, 63, 0 } } }, { { { 22, 0, 2 }, { 3, 62, 0 } } }, { { { 23, 0, 1 }, { 11, 47, 0 } } }, { { { 23, 0, 0 }, { 3, 63, 0 } } }, { { { 23, 0, 1 }, { 4, 62, 0 } } }, { { { 23, 0, 2 }, { 4, 63, 0 } } }, { { { 24, 0, 1 }, { 13, 46, 0 } } }, { { { 24, 0, 0 }, { 5, 62, 0 } } }, { { { 24, 0, 1 }, { 5, 63, 0 } } }, { { { 24, 0, 2 }, { 6, 62, 0 } } }, { { { 25, 0, 1 }, { 14, 47, 0 } } }, { { { 25, 0, 0 }, { 6, 63, 0 } } }, { { { 25, 0, 1 }, { 7, 62, 0 } } }, { { { 25, 0, 2 }, { 7, 63, 0 } } }, { { { 26, 0, 1 }, { 16, 45, 0 } } }, { { { 26, 0, 0 }, { 8, 62, 0 } } }, { { { 26, 0, 1 }, { 8, 63, 0 } } }, { { { 26, 0, 2 }, { 9, 62, 0 } } }, { { { 27, 0, 1 }, { 16, 48, 0 } } }, { { { 27, 0, 0 }, { 9, 63, 0 } } }, { { { 27, 0, 1 }, { 10, 62, 0 } } }, { { { 27, 0, 2 }, { 10, 63, 0 } } }, { { { 28, 0, 1 }, { 16, 51, 0 } } }, { { { 28, 0, 0 }, { 11, 62, 0 } } }, { { { 28, 0, 1 }, { 11, 63, 0 } } }, { { { 28, 0, 2 }, { 12, 62, 0 } } }, { { { 29, 0, 1 }, { 16, 54, 0 } } }, { { { 29, 0, 0 }, { 12, 63, 0 } } }, { { { 29, 0, 1 }, { 13, 62, 0 } } }, { { { 29, 0, 2 }, { 13, 63, 0 } } }, { { { 30, 0, 1 }, { 16, 57, 0 } } }, { { { 30, 0, 0 }, { 14, 62, 0 } } }, { { { 30, 0, 1 }, { 14, 63, 0 } } }, { { { 30, 0, 2 }, { 15, 62, 0 } } }, { { { 31, 0, 1 }, { 16, 60, 0 } } }, { { { 31, 0, 0 }, { 15, 63, 0 } } }, { { { 31, 0, 1 }, { 24, 46, 0 } } }, { { { 31, 0, 2 }, { 16, 62, 0 } } }, { { { 32, 0, 2 }, { 16, 63, 0 } } }, { { { 32, 0, 1 }, { 17, 62, 0 } } }, { { { 32, 0, 0 }, { 25, 47, 0 } } }, { { { 32, 0, 1 }, { 17, 63, 0 } } }, { { { 32, 0, 2 }, { 18, 62, 0 } } }, { { { 33, 0, 1 }, { 18, 63, 0 } } }, { { { 33, 0, 0 }, { 27, 46, 0 } } }, { { { 33, 0, 1 }, { 19, 62, 0 } } }, { { { 33, 0, 2 }, { 19, 63, 0 } } }, { { { 34, 0, 1 }, { 20, 62, 0 } } }, { { { 34, 0, 0 }, { 28, 47, 0 } } }, { { { 34, 0, 1 }, { 20, 63, 0 } } }, { { { 34, 0, 2 }, { 21, 62, 0 } } }, { { { 35, 0, 1 }, { 21, 63, 0 } } }, { { { 35, 0, 0 }, { 30, 46, 0 } } }, { { { 35, 0, 1 }, { 22, 62, 0 } } }, { { { 35, 0, 2 }, { 22, 63, 0 } } }, { { { 36, 0, 1 }, { 23, 62, 0 } } }, { { { 36, 0, 0 }, { 31, 47, 0 } } }, { { { 36, 0, 1 }, { 23, 63, 0 } } }, { { { 36, 0, 2 }, { 24, 62, 0 } } }, { { { 37, 0, 1 }, { 24, 63, 0 } } }, { { { 37, 0, 0 }, { 32, 47, 0 } } }, { { { 37, 0, 1 }, { 25, 62, 0 } } }, { { { 37, 0, 2 }, { 25, 63, 0 } } }, { { { 38, 0, 1 }, { 26, 62, 0 } } }, { { { 38, 0, 0 }, { 32, 50, 0 } } }, { { { 38, 0, 1 }, { 26, 63, 0 } } }, { { { 38, 0, 2 }, { 27, 62, 0 } } }, { { { 39, 0, 1 }, { 27, 63, 0 } } }, { { { 39, 0, 0 }, { 32, 53, 0 } } }, { { { 39, 0, 1 }, { 28, 62, 0 } } }, { { { 39, 0, 2 }, { 28, 63, 0 } } }, { { { 40, 0, 1 }, { 29, 62, 0 } } }, { { { 40, 0, 0 }, { 32, 56, 0 } } }, { { { 40, 0, 1 }, { 29, 63, 0 } } }, { { { 40, 0, 2 }, { 30, 62, 0 } } }, { { { 41, 0, 1 }, { 30, 63, 0 } } }, { { { 41, 0, 0 }, { 32, 59, 0 } } }, { { { 41, 0, 1 }, { 31, 62, 0 } } }, { { { 41, 0, 2 }, { 31, 63, 0 } } }, { { { 42, 0, 1 }, { 32, 61, 0 } } }, { { { 42, 0, 0 }, { 32, 62, 0 } } }, { { { 42, 0, 1 }, { 32, 63, 0 } } }, { { { 42, 0, 2 }, { 41, 46, 0 } } }, { { { 43, 0, 1 }, { 33, 62, 0 } } }, { { { 43, 0, 0 }, { 33, 63, 0 } } }, { { { 43, 0, 1 }, { 34, 62, 0 } } }, { { { 43, 0, 2 }, { 42, 47, 0 } } }, { { { 44, 0, 1 }, { 34, 63, 0 } } }, { { { 44, 0, 0 }, { 35, 62, 0 } } }, { { { 44, 0, 1 }, { 35, 63, 0 } } }, { { { 44, 0, 2 }, { 44, 46, 0 } } }, { { { 45, 0, 1 }, { 36, 62, 0 } } }, { { { 45, 0, 0 }, { 36, 63, 0 } } }, { { { 45, 0, 1 }, { 37, 62, 0 } } }, { { { 45, 0, 2 }, { 45, 47, 0 } } }, { { { 46, 0, 1 }, { 37, 63, 0 } } }, { { { 46, 0, 0 }, { 38, 62, 0 } } }, { { { 46, 0, 1 }, { 38, 63, 0 } } }, { { { 46, 0, 2 }, { 47, 46, 0 } } }, { { { 47, 0, 1 }, { 39, 62, 0 } } }, { { { 47, 0, 0 }, { 39, 63, 0 } } }, { { { 47, 0, 1 }, { 40, 62, 0 } } }, { { { 47, 0, 2 }, { 48, 46, 0 } } }, { { { 48, 0, 2 }, { 40, 63, 0 } } }, { { { 48, 0, 1 }, { 41, 62, 0 } } }, { { { 48, 0, 0 }, { 41, 63, 0 } } }, { { { 48, 0, 1 }, { 48, 49, 0 } } }, { { { 48, 0, 2 }, { 42, 62, 0 } } }, { { { 49, 0, 1 }, { 42, 63, 0 } } }, { { { 49, 0, 0 }, { 43, 62, 0 } } }, { { { 49, 0, 1 }, { 48, 52, 0 } } }, { { { 49, 0, 2 }, { 43, 63, 0 } } }, { { { 50, 0, 1 }, { 44, 62, 0 } } }, { { { 50, 0, 0 }, { 44, 63, 0 } } }, { { { 50, 0, 1 }, { 48, 55, 0 } } }, { { { 50, 0, 2 }, { 45, 62, 0 } } }, { { { 51, 0, 1 }, { 45, 63, 0 } } }, { { { 51, 0, 0 }, { 46, 62, 0 } } }, { { { 51, 0, 1 }, { 48, 58, 0 } } }, { { { 51, 0, 2 }, { 46, 63, 0 } } }, { { { 52, 0, 1 }, { 47, 62, 0 } } }, { { { 52, 0, 0 }, { 47, 63, 0 } } }, { { { 52, 0, 1 }, { 48, 61, 0 } } }, { { { 52, 0, 2 }, { 48, 62, 0 } } }, { { { 53, 0, 1 }, { 56, 47, 0 } } }, { { { 53, 0, 0 }, { 48, 63, 0 } } }, { { { 53, 0, 1 }, { 49, 62, 0 } } }, { { { 53, 0, 2 }, { 49, 63, 0 } } }, { { { 54, 0, 1 }, { 58, 46, 0 } } }, { { { 54, 0, 0 }, { 50, 62, 0 } } }, { { { 54, 0, 1 }, { 50, 63, 0 } } }, { { { 54, 0, 2 }, { 51, 62, 0 } } }, { { { 55, 0, 1 }, { 59, 47, 0 } } }, { { { 55, 0, 0 }, { 51, 63, 0 } } }, { { { 55, 0, 1 }, { 52, 62, 0 } } }, { { { 55, 0, 2 }, { 52, 63, 0 } } }, { { { 56, 0, 1 }, { 61, 46, 0 } } }, { { { 56, 0, 0 }, { 53, 62, 0 } } }, { { { 56, 0, 1 }, { 53, 63, 0 } } }, { { { 56, 0, 2 }, { 54, 62, 0 } } }, { { { 57, 0, 1 }, { 62, 47, 0 } } }, { { { 57, 0, 0 }, { 54, 63, 0 } } }, { { { 57, 0, 1 }, { 55, 62, 0 } } }, { { { 57, 0, 2 }, { 55, 63, 0 } } }, { { { 58, 0, 1 }, { 56, 62, 1 } } }, { { { 58, 0, 0 }, { 56, 62, 0 } } }, { { { 58, 0, 1 }, { 56, 63, 0 } } }, { { { 58, 0, 2 }, { 57, 62, 0 } } }, { { { 59, 0, 1 }, { 57, 63, 1 } } }, { { { 59, 0, 0 }, { 57, 63, 0 } } }, { { { 59, 0, 1 }, { 58, 62, 0 } } }, { { { 59, 0, 2 }, { 58, 63, 0 } } }, { { { 60, 0, 1 }, { 59, 62, 1 } } }, { { { 60, 0, 0 }, { 59, 62, 0 } } }, { { { 60, 0, 1 }, { 59, 63, 0 } } }, { { { 60, 0, 2 }, { 60, 62, 0 } } }, { { { 61, 0, 1 }, { 60, 63, 1 } } }, { { { 61, 0, 0 }, { 60, 63, 0 } } }, { { { 61, 0, 1 }, { 61, 62, 0 } } }, { { { 61, 0, 2 }, { 61, 63, 0 } } }, { { { 62, 0, 1 }, { 62, 62, 1 } } }, { { { 62, 0, 0 }, { 62, 62, 0 } } }, { { { 62, 0, 1 }, { 62, 63, 0 } } }, { { { 62, 0, 2 }, { 63, 62, 0 } } }, { { { 63, 0, 1 }, { 63, 63, 1 } } }, { { { 63, 0, 0 }, { 63, 63, 0 } } } }; static const DDSSingleColourLookup* DDS_LOOKUP[] = { DDSLookup_5_4, DDSLookup_6_4, DDSLookup_5_4 }; /* Macros */ #define C565_r(x) (((x) & 0xF800) >> 11) #define C565_g(x) (((x) & 0x07E0) >> 5) #define C565_b(x) ((x) & 0x001F) #define C565_red(x) ( (C565_r(x) << 3 | C565_r(x) >> 2)) #define C565_green(x) ( (C565_g(x) << 2 | C565_g(x) >> 4)) #define C565_blue(x) ( (C565_b(x) << 3 | C565_b(x) >> 2)) #define DIV2(x) ((x) > 1 ? ((x) >> 1) : 1) #define FixRange(min, max, steps) \ if (min > max) \ min = max; \ if (max - min < steps) \ max = MagickMin(min + steps, 255); \ if (max - min < steps) \ min = MagickMax(min - steps, 0) #define Dot(left, right) (left.x*right.x) + (left.y*right.y) + (left.z*right.z) #define VectorInit(vector, value) vector.x = vector.y = vector.z = vector.w \ = value #define VectorInit3(vector, value) vector.x = vector.y = vector.z = value #define IsBitMask(mask, r, g, b, a) (mask.r_bitmask == r && mask.g_bitmask == \ g && mask.b_bitmask == b && mask.alpha_bitmask == a) /* Forward declarations */ static MagickBooleanType ConstructOrdering(const size_t,const DDSVector4 *,const DDSVector3, DDSVector4 *,DDSVector4 *,unsigned char *,size_t), ReadDDSInfo(Image *,DDSInfo *), ReadDXT1(Image *,DDSInfo *,ExceptionInfo *), ReadDXT3(Image *,DDSInfo *,ExceptionInfo *), ReadDXT5(Image *,DDSInfo *,ExceptionInfo *), ReadUncompressedRGB(Image *,DDSInfo *,ExceptionInfo *), ReadUncompressedRGBA(Image *,DDSInfo *,ExceptionInfo *), SkipDXTMipmaps(Image *,DDSInfo *,int,ExceptionInfo *), SkipRGBMipmaps(Image *,DDSInfo *,int,ExceptionInfo *), WriteDDSImage(const ImageInfo *,Image *), WriteMipmaps(Image *,const size_t,const size_t,const size_t, const MagickBooleanType,const MagickBooleanType,ExceptionInfo *); static void RemapIndices(const ssize_t *,const unsigned char *,unsigned char *), WriteDDSInfo(Image *,const size_t,const size_t,const size_t), WriteFourCC(Image *,const size_t,const MagickBooleanType, const MagickBooleanType,ExceptionInfo *), WriteImageData(Image *,const size_t,const size_t,const MagickBooleanType, const MagickBooleanType,ExceptionInfo *), WriteIndices(Image *,const DDSVector3,const DDSVector3, unsigned char *), WriteSingleColorFit(Image *,const DDSVector4 *,const ssize_t *), WriteUncompressed(Image *,ExceptionInfo *); static inline void VectorAdd(const DDSVector4 left, const DDSVector4 right, DDSVector4 *destination) { destination->x = left.x + right.x; destination->y = left.y + right.y; destination->z = left.z + right.z; destination->w = left.w + right.w; } static inline void VectorClamp(DDSVector4 *value) { value->x = MagickMin(1.0f,MagickMax(0.0f,value->x)); value->y = MagickMin(1.0f,MagickMax(0.0f,value->y)); value->z = MagickMin(1.0f,MagickMax(0.0f,value->z)); value->w = MagickMin(1.0f,MagickMax(0.0f,value->w)); } static inline void VectorClamp3(DDSVector3 *value) { value->x = MagickMin(1.0f,MagickMax(0.0f,value->x)); value->y = MagickMin(1.0f,MagickMax(0.0f,value->y)); value->z = MagickMin(1.0f,MagickMax(0.0f,value->z)); } static inline void VectorCopy43(const DDSVector4 source, DDSVector3 *destination) { destination->x = source.x; destination->y = source.y; destination->z = source.z; } static inline void VectorCopy44(const DDSVector4 source, DDSVector4 *destination) { destination->x = source.x; destination->y = source.y; destination->z = source.z; destination->w = source.w; } static inline void VectorNegativeMultiplySubtract(const DDSVector4 a, const DDSVector4 b, const DDSVector4 c, DDSVector4 *destination) { destination->x = c.x - (a.x * b.x); destination->y = c.y - (a.y * b.y); destination->z = c.z - (a.z * b.z); destination->w = c.w - (a.w * b.w); } static inline void VectorMultiply(const DDSVector4 left, const DDSVector4 right, DDSVector4 *destination) { destination->x = left.x * right.x; destination->y = left.y * right.y; destination->z = left.z * right.z; destination->w = left.w * right.w; } static inline void VectorMultiply3(const DDSVector3 left, const DDSVector3 right, DDSVector3 *destination) { destination->x = left.x * right.x; destination->y = left.y * right.y; destination->z = left.z * right.z; } static inline void VectorMultiplyAdd(const DDSVector4 a, const DDSVector4 b, const DDSVector4 c, DDSVector4 *destination) { destination->x = (a.x * b.x) + c.x; destination->y = (a.y * b.y) + c.y; destination->z = (a.z * b.z) + c.z; destination->w = (a.w * b.w) + c.w; } static inline void VectorMultiplyAdd3(const DDSVector3 a, const DDSVector3 b, const DDSVector3 c, DDSVector3 *destination) { destination->x = (a.x * b.x) + c.x; destination->y = (a.y * b.y) + c.y; destination->z = (a.z * b.z) + c.z; } static inline void VectorReciprocal(const DDSVector4 value, DDSVector4 *destination) { destination->x = 1.0f / value.x; destination->y = 1.0f / value.y; destination->z = 1.0f / value.z; destination->w = 1.0f / value.w; } static inline void VectorSubtract(const DDSVector4 left, const DDSVector4 right, DDSVector4 *destination) { destination->x = left.x - right.x; destination->y = left.y - right.y; destination->z = left.z - right.z; destination->w = left.w - right.w; } static inline void VectorSubtract3(const DDSVector3 left, const DDSVector3 right, DDSVector3 *destination) { destination->x = left.x - right.x; destination->y = left.y - right.y; destination->z = left.z - right.z; } static inline void VectorTruncate(DDSVector4 *value) { value->x = value->x > 0.0f ? floor(value->x) : ceil(value->x); value->y = value->y > 0.0f ? floor(value->y) : ceil(value->y); value->z = value->z > 0.0f ? floor(value->z) : ceil(value->z); value->w = value->w > 0.0f ? floor(value->w) : ceil(value->w); } static inline void VectorTruncate3(DDSVector3 *value) { value->x = value->x > 0.0f ? floor(value->x) : ceil(value->x); value->y = value->y > 0.0f ? floor(value->y) : ceil(value->y); value->z = value->z > 0.0f ? floor(value->z) : ceil(value->z); } static void CalculateColors(unsigned short c0, unsigned short c1, DDSColors *c, MagickBooleanType ignoreAlpha) { c->a[0] = c->a[1] = c->a[2] = c->a[3] = 0; c->r[0] = (unsigned char) C565_red(c0); c->g[0] = (unsigned char) C565_green(c0); c->b[0] = (unsigned char) C565_blue(c0); c->r[1] = (unsigned char) C565_red(c1); c->g[1] = (unsigned char) C565_green(c1); c->b[1] = (unsigned char) C565_blue(c1); if (ignoreAlpha != MagickFalse || c0 > c1) { c->r[2] = (unsigned char) ((2 * c->r[0] + c->r[1]) / 3); c->g[2] = (unsigned char) ((2 * c->g[0] + c->g[1]) / 3); c->b[2] = (unsigned char) ((2 * c->b[0] + c->b[1]) / 3); c->r[3] = (unsigned char) ((c->r[0] + 2 * c->r[1]) / 3); c->g[3] = (unsigned char) ((c->g[0] + 2 * c->g[1]) / 3); c->b[3] = (unsigned char) ((c->b[0] + 2 * c->b[1]) / 3); } else { c->r[2] = (unsigned char) ((c->r[0] + c->r[1]) / 2); c->g[2] = (unsigned char) ((c->g[0] + c->g[1]) / 2); c->b[2] = (unsigned char) ((c->b[0] + c->b[1]) / 2); c->r[3] = c->g[3] = c->b[3] = 0; c->a[3] = 255; } } static size_t CompressAlpha(const size_t min, const size_t max, const size_t steps, const ssize_t *alphas, unsigned char* indices) { unsigned char codes[8]; register ssize_t i; size_t error, index, j, least, value; codes[0] = (unsigned char) min; codes[1] = (unsigned char) max; codes[6] = 0; codes[7] = 255; for (i=1; i < (ssize_t) steps; i++) codes[i+1] = (unsigned char) (((steps-i)*min + i*max) / steps); error = 0; for (i=0; i<16; i++) { if (alphas[i] == -1) { indices[i] = 0; continue; } value = alphas[i]; least = SIZE_MAX; index = 0; for (j=0; j<8; j++) { size_t dist; dist = value - (size_t)codes[j]; dist *= dist; if (dist < least) { least = dist; index = j; } } indices[i] = (unsigned char)index; error += least; } return error; } static void CompressClusterFit(const size_t count, const DDSVector4 *points, const ssize_t *map, const DDSVector3 principle, const DDSVector4 metric, DDSVector3 *start, DDSVector3 *end, unsigned char *indices) { DDSVector3 axis; DDSVector4 grid, gridrcp, half, onethird_onethird2, pointsWeights[16], two, twonineths, twothirds_twothirds2, xSumwSum; float bestError = 1e+37f; size_t bestIteration = 0, besti = 0, bestj = 0, bestk = 0, iterationIndex; ssize_t i; unsigned char *o, order[128], unordered[16]; VectorInit(half,0.5f); VectorInit(two,2.0f); VectorInit(onethird_onethird2,1.0f/3.0f); onethird_onethird2.w = 1.0f/9.0f; VectorInit(twothirds_twothirds2,2.0f/3.0f); twothirds_twothirds2.w = 4.0f/9.0f; VectorInit(twonineths,2.0f/9.0f); grid.x = 31.0f; grid.y = 63.0f; grid.z = 31.0f; grid.w = 0.0f; gridrcp.x = 1.0f/31.0f; gridrcp.y = 1.0f/63.0f; gridrcp.z = 1.0f/31.0f; gridrcp.w = 0.0f; xSumwSum.x = 0.0f; xSumwSum.y = 0.0f; xSumwSum.z = 0.0f; xSumwSum.w = 0.0f; ConstructOrdering(count,points,principle,pointsWeights,&xSumwSum,order,0); for (iterationIndex = 0;;) { #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(dynamic,1) \ num_threads(GetMagickResourceLimit(ThreadResource)) #endif for (i=0; i < (ssize_t) count; i++) { DDSVector4 part0, part1, part2; size_t ii, j, k, kmin; VectorInit(part0,0.0f); for(ii=0; ii < (size_t) i; ii++) VectorAdd(pointsWeights[ii],part0,&part0); VectorInit(part1,0.0f); for (j=(size_t) i;;) { if (j == 0) { VectorCopy44(pointsWeights[0],&part2); kmin = 1; } else { VectorInit(part2,0.0f); kmin = j; } for (k=kmin;;) { DDSVector4 a, alpha2_sum, alphax_sum, alphabeta_sum, b, beta2_sum, betax_sum, e1, e2, factor, part3; float error; VectorSubtract(xSumwSum,part2,&part3); VectorSubtract(part3,part1,&part3); VectorSubtract(part3,part0,&part3); VectorMultiplyAdd(part1,twothirds_twothirds2,part0,&alphax_sum); VectorMultiplyAdd(part2,onethird_onethird2,alphax_sum,&alphax_sum); VectorInit(alpha2_sum,alphax_sum.w); VectorMultiplyAdd(part2,twothirds_twothirds2,part3,&betax_sum); VectorMultiplyAdd(part1,onethird_onethird2,betax_sum,&betax_sum); VectorInit(beta2_sum,betax_sum.w); VectorAdd(part1,part2,&alphabeta_sum); VectorInit(alphabeta_sum,alphabeta_sum.w); VectorMultiply(twonineths,alphabeta_sum,&alphabeta_sum); VectorMultiply(alpha2_sum,beta2_sum,&factor); VectorNegativeMultiplySubtract(alphabeta_sum,alphabeta_sum,factor, &factor); VectorReciprocal(factor,&factor); VectorMultiply(alphax_sum,beta2_sum,&a); VectorNegativeMultiplySubtract(betax_sum,alphabeta_sum,a,&a); VectorMultiply(a,factor,&a); VectorMultiply(betax_sum,alpha2_sum,&b); VectorNegativeMultiplySubtract(alphax_sum,alphabeta_sum,b,&b); VectorMultiply(b,factor,&b); VectorClamp(&a); VectorMultiplyAdd(grid,a,half,&a); VectorTruncate(&a); VectorMultiply(a,gridrcp,&a); VectorClamp(&b); VectorMultiplyAdd(grid,b,half,&b); VectorTruncate(&b); VectorMultiply(b,gridrcp,&b); VectorMultiply(b,b,&e1); VectorMultiply(e1,beta2_sum,&e1); VectorMultiply(a,a,&e2); VectorMultiplyAdd(e2,alpha2_sum,e1,&e1); VectorMultiply(a,b,&e2); VectorMultiply(e2,alphabeta_sum,&e2); VectorNegativeMultiplySubtract(a,alphax_sum,e2,&e2); VectorNegativeMultiplySubtract(b,betax_sum,e2,&e2); VectorMultiplyAdd(two,e2,e1,&e2); VectorMultiply(e2,metric,&e2); error = e2.x + e2.y + e2.z; if (error < bestError) { #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (DDS_CompressClusterFit) #endif { if (error < bestError) { VectorCopy43(a,start); VectorCopy43(b,end); bestError = error; besti = i; bestj = j; bestk = k; bestIteration = iterationIndex; } } } if (k == count) break; VectorAdd(pointsWeights[k],part2,&part2); k++; } if (j == count) break; VectorAdd(pointsWeights[j],part1,&part1); j++; } } if (bestIteration != iterationIndex) break; iterationIndex++; if (iterationIndex == 8) break; VectorSubtract3(*end,*start,&axis); if (ConstructOrdering(count,points,axis,pointsWeights,&xSumwSum,order, iterationIndex) == MagickFalse) break; } o = order + (16*bestIteration); for (i=0; i < (ssize_t) besti; i++) unordered[o[i]] = 0; for (i=besti; i < (ssize_t) bestj; i++) unordered[o[i]] = 2; for (i=bestj; i < (ssize_t) bestk; i++) unordered[o[i]] = 3; for (i=bestk; i < (ssize_t) count; i++) unordered[o[i]] = 1; RemapIndices(map,unordered,indices); } static void CompressRangeFit(const size_t count, const DDSVector4 *points, const ssize_t *map, const DDSVector3 principle, const DDSVector4 metric, DDSVector3 *start, DDSVector3 *end, unsigned char *indices) { float d, bestDist, max, min, val; DDSVector3 codes[4], grid, gridrcp, half, dist; register ssize_t i; size_t bestj, j; unsigned char closest[16]; VectorInit3(half,0.5f); grid.x = 31.0f; grid.y = 63.0f; grid.z = 31.0f; gridrcp.x = 1.0f/31.0f; gridrcp.y = 1.0f/63.0f; gridrcp.z = 1.0f/31.0f; if (count > 0) { VectorCopy43(points[0],start); VectorCopy43(points[0],end); min = max = Dot(points[0],principle); for (i=1; i < (ssize_t) count; i++) { val = Dot(points[i],principle); if (val < min) { VectorCopy43(points[i],start); min = val; } else if (val > max) { VectorCopy43(points[i],end); max = val; } } } VectorClamp3(start); VectorMultiplyAdd3(grid,*start,half,start); VectorTruncate3(start); VectorMultiply3(*start,gridrcp,start); VectorClamp3(end); VectorMultiplyAdd3(grid,*end,half,end); VectorTruncate3(end); VectorMultiply3(*end,gridrcp,end); codes[0] = *start; codes[1] = *end; codes[2].x = (start->x * (2.0f/3.0f)) + (end->x * (1.0f/3.0f)); codes[2].y = (start->y * (2.0f/3.0f)) + (end->y * (1.0f/3.0f)); codes[2].z = (start->z * (2.0f/3.0f)) + (end->z * (1.0f/3.0f)); codes[3].x = (start->x * (1.0f/3.0f)) + (end->x * (2.0f/3.0f)); codes[3].y = (start->y * (1.0f/3.0f)) + (end->y * (2.0f/3.0f)); codes[3].z = (start->z * (1.0f/3.0f)) + (end->z * (2.0f/3.0f)); for (i=0; i < (ssize_t) count; i++) { bestDist = 1e+37f; bestj = 0; for (j=0; j < 4; j++) { dist.x = (points[i].x - codes[j].x) * metric.x; dist.y = (points[i].y - codes[j].y) * metric.y; dist.z = (points[i].z - codes[j].z) * metric.z; d = Dot(dist,dist); if (d < bestDist) { bestDist = d; bestj = j; } } closest[i] = (unsigned char) bestj; } RemapIndices(map, closest, indices); } static void ComputeEndPoints(const DDSSingleColourLookup *lookup[], const unsigned char *color, DDSVector3 *start, DDSVector3 *end, unsigned char *index) { register ssize_t i; size_t c, maxError = SIZE_MAX; for (i=0; i < 2; i++) { const DDSSourceBlock* sources[3]; size_t error = 0; for (c=0; c < 3; c++) { sources[c] = &lookup[c][color[c]].sources[i]; error += ((size_t) sources[c]->error) * ((size_t) sources[c]->error); } if (error > maxError) continue; start->x = (float) sources[0]->start / 31.0f; start->y = (float) sources[1]->start / 63.0f; start->z = (float) sources[2]->start / 31.0f; end->x = (float) sources[0]->end / 31.0f; end->y = (float) sources[1]->end / 63.0f; end->z = (float) sources[2]->end / 31.0f; *index = (unsigned char) (2*i); maxError = error; } } static void ComputePrincipleComponent(const float *covariance, DDSVector3 *principle) { DDSVector4 row0, row1, row2, v; register ssize_t i; row0.x = covariance[0]; row0.y = covariance[1]; row0.z = covariance[2]; row0.w = 0.0f; row1.x = covariance[1]; row1.y = covariance[3]; row1.z = covariance[4]; row1.w = 0.0f; row2.x = covariance[2]; row2.y = covariance[4]; row2.z = covariance[5]; row2.w = 0.0f; VectorInit(v,1.0f); for (i=0; i < 8; i++) { DDSVector4 w; float a; w.x = row0.x * v.x; w.y = row0.y * v.x; w.z = row0.z * v.x; w.w = row0.w * v.x; w.x = (row1.x * v.y) + w.x; w.y = (row1.y * v.y) + w.y; w.z = (row1.z * v.y) + w.z; w.w = (row1.w * v.y) + w.w; w.x = (row2.x * v.z) + w.x; w.y = (row2.y * v.z) + w.y; w.z = (row2.z * v.z) + w.z; w.w = (row2.w * v.z) + w.w; a = 1.0f / MagickMax(w.x,MagickMax(w.y,w.z)); v.x = w.x * a; v.y = w.y * a; v.z = w.z * a; v.w = w.w * a; } VectorCopy43(v,principle); } static void ComputeWeightedCovariance(const size_t count, const DDSVector4 *points, float *covariance) { DDSVector3 centroid; float total; size_t i; total = 0.0f; VectorInit3(centroid,0.0f); for (i=0; i < count; i++) { total += points[i].w; centroid.x += (points[i].x * points[i].w); centroid.y += (points[i].y * points[i].w); centroid.z += (points[i].z * points[i].w); } if( total > 1.192092896e-07F) { centroid.x /= total; centroid.y /= total; centroid.z /= total; } for (i=0; i < 6; i++) covariance[i] = 0.0f; for (i = 0; i < count; i++) { DDSVector3 a, b; a.x = points[i].x - centroid.x; a.y = points[i].y - centroid.y; a.z = points[i].z - centroid.z; b.x = points[i].w * a.x; b.y = points[i].w * a.y; b.z = points[i].w * a.z; covariance[0] += a.x*b.x; covariance[1] += a.x*b.y; covariance[2] += a.x*b.z; covariance[3] += a.y*b.y; covariance[4] += a.y*b.z; covariance[5] += a.z*b.z; } } static MagickBooleanType ConstructOrdering(const size_t count, const DDSVector4 *points, const DDSVector3 axis, DDSVector4 *pointsWeights, DDSVector4 *xSumwSum, unsigned char *order, size_t iteration) { float dps[16], f; register ssize_t i; size_t j; unsigned char c, *o, *p; o = order + (16*iteration); for (i=0; i < (ssize_t) count; i++) { dps[i] = Dot(points[i],axis); o[i] = (unsigned char)i; } for (i=0; i < (ssize_t) count; i++) { for (j=i; j > 0 && dps[j] < dps[j - 1]; j--) { f = dps[j]; dps[j] = dps[j - 1]; dps[j - 1] = f; c = o[j]; o[j] = o[j - 1]; o[j - 1] = c; } } for (i=0; i < (ssize_t) iteration; i++) { MagickBooleanType same; p = order + (16*i); same = MagickTrue; for (j=0; j < count; j++) { if (o[j] != p[j]) { same = MagickFalse; break; } } if (same != MagickFalse) return MagickFalse; } xSumwSum->x = 0; xSumwSum->y = 0; xSumwSum->z = 0; xSumwSum->w = 0; for (i=0; i < (ssize_t) count; i++) { DDSVector4 v; j = (size_t) o[i]; v.x = points[j].w * points[j].x; v.y = points[j].w * points[j].y; v.z = points[j].w * points[j].z; v.w = points[j].w * 1.0f; VectorCopy44(v,&pointsWeights[i]); VectorAdd(*xSumwSum,v,xSumwSum); } return MagickTrue; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s D D S % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsDDS() returns MagickTrue if the image format type, identified by the % magick string, is DDS. % % The format of the IsDDS method is: % % MagickBooleanType IsDDS(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 IsDDS(const unsigned char *magick, const size_t length) { if (length < 4) return(MagickFalse); if (LocaleNCompare((char *) magick,"DDS ", 4) == 0) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d D D S I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadDDSImage() reads a DirectDraw Surface 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 ReadDDSImage method is: % % Image *ReadDDSImage(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 *ReadDDSImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; MagickBooleanType status, cubemap = MagickFalse, volume = MagickFalse, matte; CompressionType compression; DDSInfo dds_info; DDSDecoder *decoder; size_t n, num_images; /* 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); } /* Initialize image structure. */ if (ReadDDSInfo(image, &dds_info) != MagickTrue) { ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP) cubemap = MagickTrue; if (dds_info.ddscaps2 & DDSCAPS2_VOLUME && dds_info.depth > 0) volume = MagickTrue; (void) SeekBlob(image, 128, SEEK_SET); /* Determine pixel format */ if (dds_info.pixelformat.flags & DDPF_RGB) { compression = NoCompression; if (dds_info.pixelformat.flags & DDPF_ALPHAPIXELS) { matte = MagickTrue; decoder = ReadUncompressedRGBA; } else { matte = MagickTrue; decoder = ReadUncompressedRGB; } } else if (dds_info.pixelformat.flags & DDPF_LUMINANCE) { compression = NoCompression; if (dds_info.pixelformat.flags & DDPF_ALPHAPIXELS) { /* Not sure how to handle this */ ThrowReaderException(CorruptImageError, "ImageTypeNotSupported"); } else { matte = MagickFalse; decoder = ReadUncompressedRGB; } } else if (dds_info.pixelformat.flags & DDPF_FOURCC) { switch (dds_info.pixelformat.fourcc) { case FOURCC_DXT1: { matte = MagickFalse; compression = DXT1Compression; decoder = ReadDXT1; break; } case FOURCC_DXT3: { matte = MagickTrue; compression = DXT3Compression; decoder = ReadDXT3; break; } case FOURCC_DXT5: { matte = MagickTrue; compression = DXT5Compression; decoder = ReadDXT5; break; } default: { /* Unknown FOURCC */ ThrowReaderException(CorruptImageError, "ImageTypeNotSupported"); } } } else { /* Neither compressed nor uncompressed... thus unsupported */ ThrowReaderException(CorruptImageError, "ImageTypeNotSupported"); } num_images = 1; if (cubemap) { /* Determine number of faces defined in the cubemap */ num_images = 0; if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_POSITIVEX) num_images++; if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_NEGATIVEX) num_images++; if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_POSITIVEY) num_images++; if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_NEGATIVEY) num_images++; if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_POSITIVEZ) num_images++; if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_NEGATIVEZ) num_images++; } if (volume) num_images = dds_info.depth; for (n = 0; n < num_images; n++) { if (n != 0) { if (EOFBlob(image) != MagickFalse) ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); /* Start a new image */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } image->matte = matte; image->compression = compression; image->columns = dds_info.width; image->rows = dds_info.height; image->storage_class = DirectClass; image->endian = LSBEndian; image->depth = 8; 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)); } if ((decoder)(image, &dds_info, exception) != MagickTrue) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } } if (EOFBlob(image) != MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); (void) CloseBlob(image); return(GetFirstImageInList(image)); } static MagickBooleanType ReadDDSInfo(Image *image, DDSInfo *dds_info) { size_t hdr_size, required; /* Seek to start of header */ (void) SeekBlob(image, 4, SEEK_SET); /* Check header field */ hdr_size = ReadBlobLSBLong(image); if (hdr_size != 124) return MagickFalse; /* Fill in DDS info struct */ dds_info->flags = ReadBlobLSBLong(image); /* Check required flags */ required=(size_t) (DDSD_WIDTH | DDSD_HEIGHT | DDSD_PIXELFORMAT); if ((dds_info->flags & required) != required) return MagickFalse; dds_info->height = ReadBlobLSBLong(image); dds_info->width = ReadBlobLSBLong(image); dds_info->pitchOrLinearSize = ReadBlobLSBLong(image); dds_info->depth = ReadBlobLSBLong(image); dds_info->mipmapcount = ReadBlobLSBLong(image); (void) SeekBlob(image, 44, SEEK_CUR); /* reserved region of 11 DWORDs */ /* Read pixel format structure */ hdr_size = ReadBlobLSBLong(image); if (hdr_size != 32) return MagickFalse; dds_info->pixelformat.flags = ReadBlobLSBLong(image); dds_info->pixelformat.fourcc = ReadBlobLSBLong(image); dds_info->pixelformat.rgb_bitcount = ReadBlobLSBLong(image); dds_info->pixelformat.r_bitmask = ReadBlobLSBLong(image); dds_info->pixelformat.g_bitmask = ReadBlobLSBLong(image); dds_info->pixelformat.b_bitmask = ReadBlobLSBLong(image); dds_info->pixelformat.alpha_bitmask = ReadBlobLSBLong(image); dds_info->ddscaps1 = ReadBlobLSBLong(image); dds_info->ddscaps2 = ReadBlobLSBLong(image); (void) SeekBlob(image, 12, SEEK_CUR); /* 3 reserved DWORDs */ return MagickTrue; } static MagickBooleanType ReadDXT1(Image *image, DDSInfo *dds_info, ExceptionInfo *exception) { DDSColors colors; PixelPacket *q; register ssize_t i, x; size_t bits; ssize_t j, y; unsigned char code; unsigned short c0, c1; for (y = 0; y < (ssize_t) dds_info->height; y += 4) { for (x = 0; x < (ssize_t) dds_info->width; x += 4) { /* Get 4x4 patch of pixels to write on */ q = QueueAuthenticPixels(image, x, y, MagickMin(4, dds_info->width - x), MagickMin(4, dds_info->height - y),exception); if (q == (PixelPacket *) NULL) return MagickFalse; /* Read 8 bytes of data from the image */ c0 = ReadBlobLSBShort(image); c1 = ReadBlobLSBShort(image); bits = ReadBlobLSBLong(image); CalculateColors(c0, c1, &colors, MagickFalse); /* Write the pixels */ for (j = 0; j < 4; j++) { for (i = 0; i < 4; i++) { if ((x + i) < (ssize_t) dds_info->width && (y + j) < (ssize_t) dds_info->height) { code = (unsigned char) ((bits >> ((j*4+i)*2)) & 0x3); SetPixelRed(q,ScaleCharToQuantum(colors.r[code])); SetPixelGreen(q,ScaleCharToQuantum(colors.g[code])); SetPixelBlue(q,ScaleCharToQuantum(colors.b[code])); SetPixelOpacity(q,ScaleCharToQuantum(colors.a[code])); if (colors.a[code] && image->matte == MagickFalse) /* Correct matte */ image->matte = MagickTrue; q++; } } } if (SyncAuthenticPixels(image,exception) == MagickFalse) return MagickFalse; } } return(SkipDXTMipmaps(image,dds_info,8,exception)); } static MagickBooleanType ReadDXT3(Image *image, DDSInfo *dds_info, ExceptionInfo *exception) { DDSColors colors; ssize_t j, y; PixelPacket *q; register ssize_t i, x; unsigned char alpha; size_t a0, a1, bits, code; unsigned short c0, c1; for (y = 0; y < (ssize_t) dds_info->height; y += 4) { for (x = 0; x < (ssize_t) dds_info->width; x += 4) { /* Get 4x4 patch of pixels to write on */ q = QueueAuthenticPixels(image, x, y, MagickMin(4, dds_info->width - x), MagickMin(4, dds_info->height - y),exception); if (q == (PixelPacket *) NULL) return MagickFalse; /* Read alpha values (8 bytes) */ a0 = ReadBlobLSBLong(image); a1 = ReadBlobLSBLong(image); /* Read 8 bytes of data from the image */ c0 = ReadBlobLSBShort(image); c1 = ReadBlobLSBShort(image); bits = ReadBlobLSBLong(image); CalculateColors(c0, c1, &colors, MagickTrue); /* Write the pixels */ for (j = 0; j < 4; j++) { for (i = 0; i < 4; i++) { if ((x + i) < (ssize_t) dds_info->width && (y + j) < (ssize_t) dds_info->height) { code = (bits >> ((4*j+i)*2)) & 0x3; SetPixelRed(q,ScaleCharToQuantum(colors.r[code])); SetPixelGreen(q,ScaleCharToQuantum(colors.g[code])); SetPixelBlue(q,ScaleCharToQuantum(colors.b[code])); /* Extract alpha value: multiply 0..15 by 17 to get range 0..255 */ if (j < 2) alpha = 17U * (unsigned char) ((a0 >> (4*(4*j+i))) & 0xf); else alpha = 17U * (unsigned char) ((a1 >> (4*(4*(j-2)+i))) & 0xf); SetPixelAlpha(q,ScaleCharToQuantum((unsigned char) alpha)); q++; } } } if (SyncAuthenticPixels(image,exception) == MagickFalse) return MagickFalse; } } return(SkipDXTMipmaps(image,dds_info,16,exception)); } static MagickBooleanType ReadDXT5(Image *image, DDSInfo *dds_info, ExceptionInfo *exception) { DDSColors colors; ssize_t j, y; MagickSizeType alpha_bits; PixelPacket *q; register ssize_t i, x; unsigned char a0, a1; size_t alpha, bits, code, alpha_code; unsigned short c0, c1; for (y = 0; y < (ssize_t) dds_info->height; y += 4) { for (x = 0; x < (ssize_t) dds_info->width; x += 4) { /* Get 4x4 patch of pixels to write on */ q = QueueAuthenticPixels(image, x, y, MagickMin(4, dds_info->width - x), MagickMin(4, dds_info->height - y),exception); if (q == (PixelPacket *) NULL) return MagickFalse; /* Read alpha values (8 bytes) */ a0 = (unsigned char) ReadBlobByte(image); a1 = (unsigned char) ReadBlobByte(image); alpha_bits = (MagickSizeType)ReadBlobLSBLong(image); alpha_bits = alpha_bits | ((MagickSizeType)ReadBlobLSBShort(image) << 32); /* Read 8 bytes of data from the image */ c0 = ReadBlobLSBShort(image); c1 = ReadBlobLSBShort(image); bits = ReadBlobLSBLong(image); CalculateColors(c0, c1, &colors, MagickTrue); /* Write the pixels */ for (j = 0; j < 4; j++) { for (i = 0; i < 4; i++) { if ((x + i) < (ssize_t) dds_info->width && (y + j) < (ssize_t) dds_info->height) { code = (bits >> ((4*j+i)*2)) & 0x3; SetPixelRed(q,ScaleCharToQuantum(colors.r[code])); SetPixelGreen(q,ScaleCharToQuantum(colors.g[code])); SetPixelBlue(q,ScaleCharToQuantum(colors.b[code])); /* Extract alpha value */ alpha_code = (size_t) (alpha_bits >> (3*(4*j+i))) & 0x7; if (alpha_code == 0) alpha = a0; else if (alpha_code == 1) alpha = a1; else if (a0 > a1) alpha = ((8-alpha_code) * a0 + (alpha_code-1) * a1) / 7; else if (alpha_code == 6) alpha = 0; else if (alpha_code == 7) alpha = 255; else alpha = (((6-alpha_code) * a0 + (alpha_code-1) * a1) / 5); SetPixelAlpha(q,ScaleCharToQuantum((unsigned char) alpha)); q++; } } } if (SyncAuthenticPixels(image,exception) == MagickFalse) return MagickFalse; } } return(SkipDXTMipmaps(image,dds_info,16,exception)); } static MagickBooleanType ReadUncompressedRGB(Image *image, DDSInfo *dds_info, ExceptionInfo *exception) { PixelPacket *q; ssize_t x, y; unsigned short color; if (dds_info->pixelformat.rgb_bitcount == 8) (void) SetImageType(image,GrayscaleType); else if (dds_info->pixelformat.rgb_bitcount == 16 && !IsBitMask( dds_info->pixelformat,0xf800,0x07e0,0x001f,0x0000)) ThrowBinaryException(CorruptImageError,"ImageTypeNotSupported", image->filename); for (y = 0; y < (ssize_t) dds_info->height; y++) { q = QueueAuthenticPixels(image, 0, y, dds_info->width, 1,exception); if (q == (PixelPacket *) NULL) return MagickFalse; for (x = 0; x < (ssize_t) dds_info->width; x++) { if (dds_info->pixelformat.rgb_bitcount == 8) SetPixelGray(q,ScaleCharToQuantum(ReadBlobByte(image))); else if (dds_info->pixelformat.rgb_bitcount == 16) { color=ReadBlobShort(image); SetPixelRed(q,ScaleCharToQuantum((unsigned char) (((color >> 11)/31.0)*255))); SetPixelGreen(q,ScaleCharToQuantum((unsigned char) ((((unsigned short)(color << 5) >> 10)/63.0)*255))); SetPixelBlue(q,ScaleCharToQuantum((unsigned char) ((((unsigned short)(color << 11) >> 11)/31.0)*255))); } else { SetPixelBlue(q,ScaleCharToQuantum((unsigned char) ReadBlobByte(image))); SetPixelGreen(q,ScaleCharToQuantum((unsigned char) ReadBlobByte(image))); SetPixelRed(q,ScaleCharToQuantum((unsigned char) ReadBlobByte(image))); if (dds_info->pixelformat.rgb_bitcount == 32) (void) ReadBlobByte(image); } SetPixelAlpha(q,QuantumRange); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) return MagickFalse; } return(SkipRGBMipmaps(image,dds_info,3,exception)); } static MagickBooleanType ReadUncompressedRGBA(Image *image, DDSInfo *dds_info, ExceptionInfo *exception) { PixelPacket *q; ssize_t alphaBits, x, y; unsigned short color; alphaBits=0; if (dds_info->pixelformat.rgb_bitcount == 16) { if (IsBitMask(dds_info->pixelformat,0x7c00,0x03e0,0x001f,0x8000)) alphaBits=1; else if (IsBitMask(dds_info->pixelformat,0x00ff,0x00ff,0x00ff,0xff00)) { alphaBits=2; (void) SetImageType(image,GrayscaleMatteType); } else if (IsBitMask(dds_info->pixelformat,0x0f00,0x00f0,0x000f,0xf000)) alphaBits=4; else ThrowBinaryException(CorruptImageError,"ImageTypeNotSupported", image->filename); } for (y = 0; y < (ssize_t) dds_info->height; y++) { q = QueueAuthenticPixels(image, 0, y, dds_info->width, 1,exception); if (q == (PixelPacket *) NULL) return MagickFalse; for (x = 0; x < (ssize_t) dds_info->width; x++) { if (dds_info->pixelformat.rgb_bitcount == 16) { color=ReadBlobShort(image); if (alphaBits == 1) { SetPixelAlpha(q,(color & (1 << 15)) ? QuantumRange : 0); SetPixelRed(q,ScaleCharToQuantum((unsigned char) ((((unsigned short)(color << 1) >> 11)/31.0)*255))); SetPixelGreen(q,ScaleCharToQuantum((unsigned char) ((((unsigned short)(color << 6) >> 11)/31.0)*255))); SetPixelBlue(q,ScaleCharToQuantum((unsigned char) ((((unsigned short)(color << 11) >> 11)/31.0)*255))); } else if (alphaBits == 2) { SetPixelAlpha(q,ScaleCharToQuantum((unsigned char) (color >> 8))); SetPixelGray(q,ScaleCharToQuantum((unsigned char)color)); } else { SetPixelAlpha(q,ScaleCharToQuantum((unsigned char) (((color >> 12)/15.0)*255))); SetPixelRed(q,ScaleCharToQuantum((unsigned char) ((((unsigned short)(color << 4) >> 12)/15.0)*255))); SetPixelGreen(q,ScaleCharToQuantum((unsigned char) ((((unsigned short)(color << 8) >> 12)/15.0)*255))); SetPixelBlue(q,ScaleCharToQuantum((unsigned char) ((((unsigned short)(color << 12) >> 12)/15.0)*255))); } } else { SetPixelBlue(q,ScaleCharToQuantum((unsigned char) ReadBlobByte(image))); SetPixelGreen(q,ScaleCharToQuantum((unsigned char) ReadBlobByte(image))); SetPixelRed(q,ScaleCharToQuantum((unsigned char) ReadBlobByte(image))); SetPixelAlpha(q,ScaleCharToQuantum((unsigned char) ReadBlobByte(image))); } q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) return MagickFalse; } return(SkipRGBMipmaps(image,dds_info,4,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r D D S I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterDDSImage() adds attributes for the DDS 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 RegisterDDSImage method is: % % RegisterDDSImage(void) % */ ModuleExport size_t RegisterDDSImage(void) { MagickInfo *entry; entry = SetMagickInfo("DDS"); entry->decoder = (DecodeImageHandler *) ReadDDSImage; entry->encoder = (EncodeImageHandler *) WriteDDSImage; entry->magick = (IsImageFormatHandler *) IsDDS; entry->seekable_stream=MagickTrue; entry->description = ConstantString("Microsoft DirectDraw Surface"); entry->module = ConstantString("DDS"); (void) RegisterMagickInfo(entry); entry = SetMagickInfo("DXT1"); entry->decoder = (DecodeImageHandler *) ReadDDSImage; entry->encoder = (EncodeImageHandler *) WriteDDSImage; entry->magick = (IsImageFormatHandler *) IsDDS; entry->seekable_stream=MagickTrue; entry->description = ConstantString("Microsoft DirectDraw Surface"); entry->module = ConstantString("DDS"); (void) RegisterMagickInfo(entry); entry = SetMagickInfo("DXT5"); entry->decoder = (DecodeImageHandler *) ReadDDSImage; entry->encoder = (EncodeImageHandler *) WriteDDSImage; entry->magick = (IsImageFormatHandler *) IsDDS; entry->seekable_stream=MagickTrue; entry->description = ConstantString("Microsoft DirectDraw Surface"); entry->module = ConstantString("DDS"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } static void RemapIndices(const ssize_t *map, const unsigned char *source, unsigned char *target) { register ssize_t i; for (i = 0; i < 16; i++) { if (map[i] == -1) target[i] = 3; else target[i] = source[map[i]]; } } /* Skip the mipmap images for compressed (DXTn) dds files */ static MagickBooleanType SkipDXTMipmaps(Image *image,DDSInfo *dds_info, int texel_size,ExceptionInfo *exception) { register ssize_t i; MagickOffsetType offset; size_t h, w; /* Only skip mipmaps for textures and cube maps */ if (dds_info->ddscaps1 & DDSCAPS_MIPMAP && (dds_info->ddscaps1 & DDSCAPS_TEXTURE || dds_info->ddscaps2 & DDSCAPS2_CUBEMAP)) { if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); return(MagickFalse); } w = DIV2(dds_info->width); h = DIV2(dds_info->height); /* Mipmapcount includes the main image, so start from one */ for (i = 1; (i < (ssize_t) dds_info->mipmapcount) && w && h; i++) { offset = (MagickOffsetType) ((w + 3) / 4) * ((h + 3) / 4) * texel_size; (void) SeekBlob(image, offset, SEEK_CUR); w = DIV2(w); h = DIV2(h); } } return(MagickTrue); } /* Skip the mipmap images for uncompressed (RGB or RGBA) dds files */ static MagickBooleanType SkipRGBMipmaps(Image *image,DDSInfo *dds_info, int pixel_size,ExceptionInfo *exception) { MagickOffsetType offset; register ssize_t i; size_t h, w; /* Only skip mipmaps for textures and cube maps */ if (dds_info->ddscaps1 & DDSCAPS_MIPMAP && (dds_info->ddscaps1 & DDSCAPS_TEXTURE || dds_info->ddscaps2 & DDSCAPS2_CUBEMAP)) { if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); return(MagickFalse); } w = DIV2(dds_info->width); h = DIV2(dds_info->height); /* Mipmapcount includes the main image, so start from one */ for (i=1; (i < (ssize_t) dds_info->mipmapcount) && w && h; i++) { offset = (MagickOffsetType) w * h * pixel_size; (void) SeekBlob(image, offset, SEEK_CUR); w = DIV2(w); h = DIV2(h); } } return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r D D S I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterDDSImage() removes format registrations made by the % DDS module from the list of supported formats. % % The format of the UnregisterDDSImage method is: % % UnregisterDDSImage(void) % */ ModuleExport void UnregisterDDSImage(void) { (void) UnregisterMagickInfo("DDS"); (void) UnregisterMagickInfo("DXT1"); (void) UnregisterMagickInfo("DXT5"); } static void WriteAlphas(Image *image, const ssize_t* alphas, size_t min5, size_t max5, size_t min7, size_t max7) { register ssize_t i; size_t err5, err7, j; unsigned char indices5[16], indices7[16]; FixRange(min5,max5,5); err5 = CompressAlpha(min5,max5,5,alphas,indices5); FixRange(min7,max7,7); err7 = CompressAlpha(min7,max7,7,alphas,indices7); if (err7 < err5) { for (i=0; i < 16; i++) { unsigned char index; index = indices7[i]; if( index == 0 ) indices5[i] = 1; else if (index == 1) indices5[i] = 0; else indices5[i] = 9 - index; } min5 = max7; max5 = min7; } (void) WriteBlobByte(image,(unsigned char) min5); (void) WriteBlobByte(image,(unsigned char) max5); for(i=0; i < 2; i++) { size_t value = 0; for (j=0; j < 8; j++) { size_t index = (size_t) indices5[j + i*8]; value |= ( index << 3*j ); } for (j=0; j < 3; j++) { size_t byte = (value >> 8*j) & 0xff; (void) WriteBlobByte(image,(unsigned char) byte); } } } static void WriteCompressed(Image *image, const size_t count, DDSVector4* points, const ssize_t* map, const MagickBooleanType clusterFit) { float covariance[16]; DDSVector3 end, principle, start; DDSVector4 metric; unsigned char indices[16]; VectorInit(metric,1.0f); VectorInit3(start,0.0f); VectorInit3(end,0.0f); ComputeWeightedCovariance(count,points,covariance); ComputePrincipleComponent(covariance,&principle); if (clusterFit == MagickFalse || count == 0) CompressRangeFit(count,points,map,principle,metric,&start,&end,indices); else CompressClusterFit(count,points,map,principle,metric,&start,&end,indices); WriteIndices(image,start,end,indices); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e D D S I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteDDSImage() writes a DirectDraw Surface image file in the DXT5 format. % % The format of the WriteBMPImage method is: % % MagickBooleanType WriteDDSImage(const ImageInfo *image_info,Image *image) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % */ static MagickBooleanType WriteDDSImage(const ImageInfo *image_info, Image *image) { const char *option; size_t compression, columns, maxMipmaps, mipmaps, pixelFormat, rows; MagickBooleanType clusterFit, status, weightByAlpha; 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); pixelFormat=DDPF_FOURCC; compression=FOURCC_DXT5; if (!image->matte) compression=FOURCC_DXT1; if (LocaleCompare(image_info->magick,"dxt1") == 0) compression=FOURCC_DXT1; option=GetImageOption(image_info,"dds:compression"); if (option != (char *) NULL) { if (LocaleCompare(option,"dxt1") == 0) compression=FOURCC_DXT1; if (LocaleCompare(option,"none") == 0) pixelFormat=DDPF_RGB; } clusterFit=MagickFalse; weightByAlpha=MagickFalse; if (pixelFormat == DDPF_FOURCC) { option=GetImageOption(image_info,"dds:cluster-fit"); if (option != (char *) NULL && LocaleCompare(option,"true") == 0) { clusterFit=MagickTrue; if (compression != FOURCC_DXT1) { option=GetImageOption(image_info,"dds:weight-by-alpha"); if (option != (char *) NULL && LocaleCompare(option,"true") == 0) weightByAlpha=MagickTrue; } } } maxMipmaps=SIZE_MAX; mipmaps=0; if ((image->columns & (image->columns - 1)) == 0 && (image->rows & (image->rows - 1)) == 0) { option=GetImageOption(image_info,"dds:mipmaps"); if (option != (char *) NULL) maxMipmaps=StringToUnsignedLong(option); if (maxMipmaps != 0) { columns=image->columns; rows=image->rows; while (columns != 1 && rows != 1 && mipmaps != maxMipmaps) { columns=DIV2(columns); rows=DIV2(rows); mipmaps++; } } } WriteDDSInfo(image,pixelFormat,compression,mipmaps); WriteImageData(image,pixelFormat,compression,clusterFit,weightByAlpha, &image->exception); if (mipmaps > 0 && WriteMipmaps(image,pixelFormat,compression,mipmaps, clusterFit,weightByAlpha,&image->exception) == MagickFalse) return(MagickFalse); (void) CloseBlob(image); return(MagickTrue); } static void WriteDDSInfo(Image *image, const size_t pixelFormat, const size_t compression, const size_t mipmaps) { char software[MaxTextExtent]; register ssize_t i; unsigned int format, caps, flags; flags=(unsigned int) (DDSD_CAPS | DDSD_WIDTH | DDSD_HEIGHT | DDSD_PIXELFORMAT | DDSD_LINEARSIZE); caps=(unsigned int) DDSCAPS_TEXTURE; format=(unsigned int) pixelFormat; if (mipmaps > 0) { flags=flags | (unsigned int) DDSD_MIPMAPCOUNT; caps=caps | (unsigned int) (DDSCAPS_MIPMAP | DDSCAPS_COMPLEX); } if (format != DDPF_FOURCC && image->matte) format=format | DDPF_ALPHAPIXELS; (void) WriteBlob(image,4,(unsigned char *) "DDS "); (void) WriteBlobLSBLong(image,124); (void) WriteBlobLSBLong(image,flags); (void) WriteBlobLSBLong(image,(unsigned int) image->rows); (void) WriteBlobLSBLong(image,(unsigned int) image->columns); if (compression == FOURCC_DXT1) (void) WriteBlobLSBLong(image, (unsigned int) (MagickMax(1,(image->columns+3)/4) * 8)); else (void) WriteBlobLSBLong(image, (unsigned int) (MagickMax(1,(image->columns+3)/4) * 16)); (void) WriteBlobLSBLong(image,0x00); (void) WriteBlobLSBLong(image,(unsigned int) mipmaps+1); (void) ResetMagickMemory(software,0,sizeof(software)); (void) strcpy(software,"IMAGEMAGICK"); (void) WriteBlob(image,44,(unsigned char *) software); (void) WriteBlobLSBLong(image,32); (void) WriteBlobLSBLong(image,format); if (pixelFormat == DDPF_FOURCC) { (void) WriteBlobLSBLong(image,(unsigned int) compression); for(i=0;i < 5;i++) // bitcount / masks (void) WriteBlobLSBLong(image,0x00); } else { (void) WriteBlobLSBLong(image,0x00); if (image->matte) { (void) WriteBlobLSBLong(image,32); (void) WriteBlobLSBLong(image,0xff0000); (void) WriteBlobLSBLong(image,0xff00); (void) WriteBlobLSBLong(image,0xff); (void) WriteBlobLSBLong(image,0xff000000); } else { (void) WriteBlobLSBLong(image,24); (void) WriteBlobLSBLong(image,0xff); (void) WriteBlobLSBLong(image,0x00); (void) WriteBlobLSBLong(image,0x00); (void) WriteBlobLSBLong(image,0x00); } } (void) WriteBlobLSBLong(image,caps); for(i=0;i < 4;i++) // ddscaps2 + reserved region (void) WriteBlobLSBLong(image,0x00); } static void WriteFourCC(Image *image, const size_t compression, const MagickBooleanType clusterFit, const MagickBooleanType weightByAlpha, ExceptionInfo *exception) { register const PixelPacket *p; register ssize_t x; ssize_t i, y, bx, by; for (y=0; y < (ssize_t) image->rows; y+=4) { for (x=0; x < (ssize_t) image->columns; x+=4) { MagickBooleanType match; DDSVector4 point, points[16]; size_t count = 0, max5 = 0, max7 = 0, min5 = 255, min7 = 255, columns = 4, rows = 4; ssize_t alphas[16], map[16]; unsigned char alpha; if (x + columns >= image->columns) columns = image->columns - x; if (y + rows >= image->rows) rows = image->rows - y; p=GetVirtualPixels(image,x,y,columns,rows,exception); if (p == (const PixelPacket *) NULL) break; for (i=0; i<16; i++) { map[i] = -1; alphas[i] = -1; } for (by=0; by < (ssize_t) rows; by++) { for (bx=0; bx < (ssize_t) columns; bx++) { if (compression == FOURCC_DXT5) alpha = ScaleQuantumToChar(GetPixelAlpha(p)); else alpha = 255; alphas[4*by + bx] = (size_t)alpha; point.x = (float)ScaleQuantumToChar(GetPixelRed(p)) / 255.0f; point.y = (float)ScaleQuantumToChar(GetPixelGreen(p)) / 255.0f; point.z = (float)ScaleQuantumToChar(GetPixelBlue(p)) / 255.0f; point.w = weightByAlpha ? (float)(alpha + 1) / 256.0f : 1.0f; p++; match = MagickFalse; for (i=0; i < (ssize_t) count; i++) { if ((points[i].x == point.x) && (points[i].y == point.y) && (points[i].z == point.z) && (alpha >= 128 || compression == FOURCC_DXT5)) { points[i].w += point.w; map[4*by + bx] = i; match = MagickTrue; break; } } if (match != MagickFalse) continue; points[count].x = point.x; points[count].y = point.y; points[count].z = point.z; points[count].w = point.w; map[4*by + bx] = count; count++; if (compression == FOURCC_DXT5) { if (alpha < min7) min7 = alpha; if (alpha > max7) max7 = alpha; if (alpha != 0 && alpha < min5) min5 = alpha; if (alpha != 255 && alpha > max5) max5 = alpha; } } } for (i=0; i < (ssize_t) count; i++) points[i].w = sqrt(points[i].w); if (compression == FOURCC_DXT5) WriteAlphas(image,alphas,min5,max5,min7,max7); if (count == 1) WriteSingleColorFit(image,points,map); else WriteCompressed(image,count,points,map,clusterFit); } } } static void WriteImageData(Image *image, const size_t pixelFormat, const size_t compression, const MagickBooleanType clusterFit, const MagickBooleanType weightByAlpha, ExceptionInfo *exception) { if (pixelFormat == DDPF_FOURCC) WriteFourCC(image,compression,clusterFit,weightByAlpha,exception); else WriteUncompressed(image,exception); } static inline size_t ClampToLimit(const float value, const size_t limit) { size_t result = (int) (value + 0.5f); if (result < 0.0f) return(0); if (result > limit) return(limit); return result; } static inline size_t ColorTo565(const DDSVector3 point) { size_t r = ClampToLimit(31.0f*point.x,31); size_t g = ClampToLimit(63.0f*point.y,63); size_t b = ClampToLimit(31.0f*point.z,31); return (r << 11) | (g << 5) | b; } static void WriteIndices(Image *image, const DDSVector3 start, const DDSVector3 end, unsigned char* indices) { register ssize_t i; size_t a, b; unsigned char remapped[16]; const unsigned char *ind; a = ColorTo565(start); b = ColorTo565(end); for (i=0; i<16; i++) { if( a < b ) remapped[i] = (indices[i] ^ 0x1) & 0x3; else if( a == b ) remapped[i] = 0; else remapped[i] = indices[i]; } if( a < b ) Swap(a,b); (void) WriteBlobByte(image,(unsigned char) (a & 0xff)); (void) WriteBlobByte(image,(unsigned char) (a >> 8)); (void) WriteBlobByte(image,(unsigned char) (b & 0xff)); (void) WriteBlobByte(image,(unsigned char) (b >> 8)); for (i=0; i<4; i++) { ind = remapped + 4*i; (void) WriteBlobByte(image,ind[0] | (ind[1] << 2) | (ind[2] << 4) | (ind[3] << 6)); } } static MagickBooleanType WriteMipmaps(Image *image, const size_t pixelFormat, const size_t compression, const size_t mipmaps, const MagickBooleanType clusterFit, const MagickBooleanType weightByAlpha, ExceptionInfo *exception) { Image* resize_image; register ssize_t i; size_t columns, rows; columns = image->columns; rows = image->rows; for (i=0; i< (ssize_t) mipmaps; i++) { resize_image = ResizeImage(image,columns/2,rows/2,TriangleFilter,1.0, exception); if (resize_image == (Image *) NULL) return(MagickFalse); DestroyBlob(resize_image); resize_image->blob=ReferenceBlob(image->blob); WriteImageData(resize_image,pixelFormat,compression,weightByAlpha, clusterFit,exception); resize_image=DestroyImage(resize_image); columns = DIV2(columns); rows = DIV2(rows); } return(MagickTrue); } static void WriteSingleColorFit(Image *image, const DDSVector4* points, const ssize_t* map) { DDSVector3 start, end; register ssize_t i; unsigned char color[3], index, indexes[16], indices[16]; color[0] = (unsigned char) ClampToLimit(255.0f*points->x,255); color[1] = (unsigned char) ClampToLimit(255.0f*points->y,255); color[2] = (unsigned char) ClampToLimit(255.0f*points->z,255); index=0; ComputeEndPoints(DDS_LOOKUP,color,&start,&end,&index); for (i=0; i< 16; i++) indexes[i]=index; RemapIndices(map,indexes,indices); WriteIndices(image,start,end,indices); } static void WriteUncompressed(Image *image, ExceptionInfo *exception) { register const PixelPacket *p; register ssize_t x; ssize_t y; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { (void) WriteBlobByte(image,ScaleQuantumToChar(GetPixelBlue(p))); (void) WriteBlobByte(image,ScaleQuantumToChar(GetPixelGreen(p))); (void) WriteBlobByte(image,ScaleQuantumToChar(GetPixelRed(p))); if (image->matte) (void) WriteBlobByte(image,ScaleQuantumToChar(GetPixelAlpha(p))); p++; } } }
./CrossVul/dataset_final_sorted/CWE-20/c/bad_2433_0
crossvul-cpp_data_good_2221_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 Intel Corp. * Copyright (c) 2001 La Monte H.P. Yarroll * * This file is part of the SCTP kernel implementation * * This module provides the abstraction for an SCTP association. * * 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> * Jon Grimm <jgrimm@us.ibm.com> * Xingang Guo <xingang.guo@intel.com> * Hui Huang <hui.huang@nokia.com> * Sridhar Samudrala <sri@us.ibm.com> * Daisy Chang <daisyc@us.ibm.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/fcntl.h> #include <linux/poll.h> #include <linux/init.h> #include <linux/slab.h> #include <linux/in.h> #include <net/ipv6.h> #include <net/sctp/sctp.h> #include <net/sctp/sm.h> /* Forward declarations for internal functions. */ static void sctp_select_active_and_retran_path(struct sctp_association *asoc); static void sctp_assoc_bh_rcv(struct work_struct *work); static void sctp_assoc_free_asconf_acks(struct sctp_association *asoc); static void sctp_assoc_free_asconf_queue(struct sctp_association *asoc); /* 1st Level Abstractions. */ /* Initialize a new association from provided memory. */ static struct sctp_association *sctp_association_init(struct sctp_association *asoc, const struct sctp_endpoint *ep, const struct sock *sk, sctp_scope_t scope, gfp_t gfp) { struct net *net = sock_net(sk); struct sctp_sock *sp; int i; sctp_paramhdr_t *p; int err; /* Retrieve the SCTP per socket area. */ sp = sctp_sk((struct sock *)sk); /* Discarding const is appropriate here. */ asoc->ep = (struct sctp_endpoint *)ep; asoc->base.sk = (struct sock *)sk; sctp_endpoint_hold(asoc->ep); sock_hold(asoc->base.sk); /* Initialize the common base substructure. */ asoc->base.type = SCTP_EP_TYPE_ASSOCIATION; /* Initialize the object handling fields. */ atomic_set(&asoc->base.refcnt, 1); /* Initialize the bind addr area. */ sctp_bind_addr_init(&asoc->base.bind_addr, ep->base.bind_addr.port); asoc->state = SCTP_STATE_CLOSED; asoc->cookie_life = ms_to_ktime(sp->assocparams.sasoc_cookie_life); asoc->user_frag = sp->user_frag; /* Set the association max_retrans and RTO values from the * socket values. */ asoc->max_retrans = sp->assocparams.sasoc_asocmaxrxt; asoc->pf_retrans = net->sctp.pf_retrans; asoc->rto_initial = msecs_to_jiffies(sp->rtoinfo.srto_initial); asoc->rto_max = msecs_to_jiffies(sp->rtoinfo.srto_max); asoc->rto_min = msecs_to_jiffies(sp->rtoinfo.srto_min); /* Initialize the association's heartbeat interval based on the * sock configured value. */ asoc->hbinterval = msecs_to_jiffies(sp->hbinterval); /* Initialize path max retrans value. */ asoc->pathmaxrxt = sp->pathmaxrxt; /* Initialize default path MTU. */ asoc->pathmtu = sp->pathmtu; /* Set association default SACK delay */ asoc->sackdelay = msecs_to_jiffies(sp->sackdelay); asoc->sackfreq = sp->sackfreq; /* Set the association default flags controlling * Heartbeat, SACK delay, and Path MTU Discovery. */ asoc->param_flags = sp->param_flags; /* Initialize the maximum number of new data packets that can be sent * in a burst. */ asoc->max_burst = sp->max_burst; /* initialize association timers */ asoc->timeouts[SCTP_EVENT_TIMEOUT_T1_COOKIE] = asoc->rto_initial; asoc->timeouts[SCTP_EVENT_TIMEOUT_T1_INIT] = asoc->rto_initial; asoc->timeouts[SCTP_EVENT_TIMEOUT_T2_SHUTDOWN] = asoc->rto_initial; /* sctpimpguide Section 2.12.2 * If the 'T5-shutdown-guard' timer is used, it SHOULD be set to the * recommended value of 5 times 'RTO.Max'. */ asoc->timeouts[SCTP_EVENT_TIMEOUT_T5_SHUTDOWN_GUARD] = 5 * asoc->rto_max; asoc->timeouts[SCTP_EVENT_TIMEOUT_SACK] = asoc->sackdelay; asoc->timeouts[SCTP_EVENT_TIMEOUT_AUTOCLOSE] = sp->autoclose * HZ; /* Initializes the timers */ for (i = SCTP_EVENT_TIMEOUT_NONE; i < SCTP_NUM_TIMEOUT_TYPES; ++i) setup_timer(&asoc->timers[i], sctp_timer_events[i], (unsigned long)asoc); /* Pull default initialization values from the sock options. * Note: This assumes that the values have already been * validated in the sock. */ asoc->c.sinit_max_instreams = sp->initmsg.sinit_max_instreams; asoc->c.sinit_num_ostreams = sp->initmsg.sinit_num_ostreams; asoc->max_init_attempts = sp->initmsg.sinit_max_attempts; asoc->max_init_timeo = msecs_to_jiffies(sp->initmsg.sinit_max_init_timeo); /* Set the local window size for receive. * This is also the rcvbuf space per association. * RFC 6 - A SCTP receiver MUST be able to receive a minimum of * 1500 bytes in one SCTP packet. */ if ((sk->sk_rcvbuf/2) < SCTP_DEFAULT_MINWINDOW) asoc->rwnd = SCTP_DEFAULT_MINWINDOW; else asoc->rwnd = sk->sk_rcvbuf/2; asoc->a_rwnd = asoc->rwnd; /* Use my own max window until I learn something better. */ asoc->peer.rwnd = SCTP_DEFAULT_MAXWINDOW; /* Initialize the receive memory counter */ atomic_set(&asoc->rmem_alloc, 0); init_waitqueue_head(&asoc->wait); asoc->c.my_vtag = sctp_generate_tag(ep); asoc->c.my_port = ep->base.bind_addr.port; asoc->c.initial_tsn = sctp_generate_tsn(ep); asoc->next_tsn = asoc->c.initial_tsn; asoc->ctsn_ack_point = asoc->next_tsn - 1; asoc->adv_peer_ack_point = asoc->ctsn_ack_point; asoc->highest_sacked = asoc->ctsn_ack_point; asoc->last_cwr_tsn = asoc->ctsn_ack_point; /* 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 the following: * ... * A2) a serial number should be assigned to the chunk. The serial * number SHOULD be a monotonically increasing number. The serial * numbers SHOULD be initialized at the start of the * association to the same value as the initial TSN. */ asoc->addip_serial = asoc->c.initial_tsn; INIT_LIST_HEAD(&asoc->addip_chunk_list); INIT_LIST_HEAD(&asoc->asconf_ack_list); /* Make an empty list of remote transport addresses. */ INIT_LIST_HEAD(&asoc->peer.transport_addr_list); /* RFC 2960 5.1 Normal Establishment of an Association * * After the reception of the first data chunk in an * association the endpoint must immediately respond with a * sack to acknowledge the data chunk. Subsequent * acknowledgements should be done as described in Section * 6.2. * * [We implement this by telling a new association that it * already received one packet.] */ asoc->peer.sack_needed = 1; asoc->peer.sack_generation = 1; /* Assume that the peer will tell us if he recognizes ASCONF * as part of INIT exchange. * The sctp_addip_noauth option is there for backward compatibility * and will revert old behavior. */ if (net->sctp.addip_noauth) asoc->peer.asconf_capable = 1; /* Create an input queue. */ sctp_inq_init(&asoc->base.inqueue); sctp_inq_set_th_handler(&asoc->base.inqueue, sctp_assoc_bh_rcv); /* Create an output queue. */ sctp_outq_init(asoc, &asoc->outqueue); if (!sctp_ulpq_init(&asoc->ulpq, asoc)) goto fail_init; /* Assume that peer would support both address types unless we are * told otherwise. */ asoc->peer.ipv4_address = 1; if (asoc->base.sk->sk_family == PF_INET6) asoc->peer.ipv6_address = 1; INIT_LIST_HEAD(&asoc->asocs); asoc->default_stream = sp->default_stream; asoc->default_ppid = sp->default_ppid; asoc->default_flags = sp->default_flags; asoc->default_context = sp->default_context; asoc->default_timetolive = sp->default_timetolive; asoc->default_rcv_context = sp->default_rcv_context; /* AUTH related initializations */ INIT_LIST_HEAD(&asoc->endpoint_shared_keys); err = sctp_auth_asoc_copy_shkeys(ep, asoc, gfp); if (err) goto fail_init; asoc->active_key_id = ep->active_key_id; /* Save the hmacs and chunks list into this association */ if (ep->auth_hmacs_list) memcpy(asoc->c.auth_hmacs, ep->auth_hmacs_list, ntohs(ep->auth_hmacs_list->param_hdr.length)); if (ep->auth_chunk_list) memcpy(asoc->c.auth_chunks, ep->auth_chunk_list, ntohs(ep->auth_chunk_list->param_hdr.length)); /* Get the AUTH random number for this association */ p = (sctp_paramhdr_t *)asoc->c.auth_random; p->type = SCTP_PARAM_RANDOM; p->length = htons(sizeof(sctp_paramhdr_t) + SCTP_AUTH_RANDOM_LENGTH); get_random_bytes(p+1, SCTP_AUTH_RANDOM_LENGTH); return asoc; fail_init: sock_put(asoc->base.sk); sctp_endpoint_put(asoc->ep); return NULL; } /* Allocate and initialize a new association */ struct sctp_association *sctp_association_new(const struct sctp_endpoint *ep, const struct sock *sk, sctp_scope_t scope, gfp_t gfp) { struct sctp_association *asoc; asoc = kzalloc(sizeof(*asoc), gfp); if (!asoc) goto fail; if (!sctp_association_init(asoc, ep, sk, scope, gfp)) goto fail_init; SCTP_DBG_OBJCNT_INC(assoc); pr_debug("Created asoc %p\n", asoc); return asoc; fail_init: kfree(asoc); fail: return NULL; } /* Free this association if possible. There may still be users, so * the actual deallocation may be delayed. */ void sctp_association_free(struct sctp_association *asoc) { struct sock *sk = asoc->base.sk; struct sctp_transport *transport; struct list_head *pos, *temp; int i; /* Only real associations count against the endpoint, so * don't bother for if this is a temporary association. */ if (!list_empty(&asoc->asocs)) { list_del(&asoc->asocs); /* Decrement the backlog value for a TCP-style listening * socket. */ if (sctp_style(sk, TCP) && sctp_sstate(sk, LISTENING)) sk->sk_ack_backlog--; } /* Mark as dead, so other users can know this structure is * going away. */ asoc->base.dead = true; /* Dispose of any data lying around in the outqueue. */ sctp_outq_free(&asoc->outqueue); /* Dispose of any pending messages for the upper layer. */ sctp_ulpq_free(&asoc->ulpq); /* Dispose of any pending chunks on the inqueue. */ sctp_inq_free(&asoc->base.inqueue); sctp_tsnmap_free(&asoc->peer.tsn_map); /* Free ssnmap storage. */ sctp_ssnmap_free(asoc->ssnmap); /* Clean up the bound address list. */ sctp_bind_addr_free(&asoc->base.bind_addr); /* Do we need to go through all of our timers and * delete them? To be safe we will try to delete all, but we * should be able to go through and make a guess based * on our state. */ for (i = SCTP_EVENT_TIMEOUT_NONE; i < SCTP_NUM_TIMEOUT_TYPES; ++i) { if (del_timer(&asoc->timers[i])) sctp_association_put(asoc); } /* Free peer's cached cookie. */ kfree(asoc->peer.cookie); kfree(asoc->peer.peer_random); kfree(asoc->peer.peer_chunks); kfree(asoc->peer.peer_hmacs); /* Release the transport structures. */ list_for_each_safe(pos, temp, &asoc->peer.transport_addr_list) { transport = list_entry(pos, struct sctp_transport, transports); list_del_rcu(pos); sctp_transport_free(transport); } asoc->peer.transport_count = 0; sctp_asconf_queue_teardown(asoc); /* Free pending address space being deleted */ if (asoc->asconf_addr_del_pending != NULL) kfree(asoc->asconf_addr_del_pending); /* AUTH - Free the endpoint shared keys */ sctp_auth_destroy_keys(&asoc->endpoint_shared_keys); /* AUTH - Free the association shared key */ sctp_auth_key_put(asoc->asoc_shared_key); sctp_association_put(asoc); } /* Cleanup and free up an association. */ static void sctp_association_destroy(struct sctp_association *asoc) { if (unlikely(!asoc->base.dead)) { WARN(1, "Attempt to destroy undead association %p!\n", asoc); return; } sctp_endpoint_put(asoc->ep); sock_put(asoc->base.sk); if (asoc->assoc_id != 0) { spin_lock_bh(&sctp_assocs_id_lock); idr_remove(&sctp_assocs_id, asoc->assoc_id); spin_unlock_bh(&sctp_assocs_id_lock); } WARN_ON(atomic_read(&asoc->rmem_alloc)); kfree(asoc); SCTP_DBG_OBJCNT_DEC(assoc); } /* Change the primary destination address for the peer. */ void sctp_assoc_set_primary(struct sctp_association *asoc, struct sctp_transport *transport) { int changeover = 0; /* it's a changeover only if we already have a primary path * that we are changing */ if (asoc->peer.primary_path != NULL && asoc->peer.primary_path != transport) changeover = 1 ; asoc->peer.primary_path = transport; /* Set a default msg_name for events. */ memcpy(&asoc->peer.primary_addr, &transport->ipaddr, sizeof(union sctp_addr)); /* If the primary path is changing, assume that the * user wants to use this new path. */ if ((transport->state == SCTP_ACTIVE) || (transport->state == SCTP_UNKNOWN)) asoc->peer.active_path = transport; /* * SFR-CACC algorithm: * Upon the receipt of a request to change the primary * destination address, on the data structure for the new * primary destination, the sender MUST do the following: * * 1) If CHANGEOVER_ACTIVE is set, then there was a switch * to this destination address earlier. The sender MUST set * CYCLING_CHANGEOVER to indicate that this switch is a * double switch to the same destination address. * * Really, only bother is we have data queued or outstanding on * the association. */ if (!asoc->outqueue.outstanding_bytes && !asoc->outqueue.out_qlen) return; if (transport->cacc.changeover_active) transport->cacc.cycling_changeover = changeover; /* 2) The sender MUST set CHANGEOVER_ACTIVE to indicate that * a changeover has occurred. */ transport->cacc.changeover_active = changeover; /* 3) The sender MUST store the next TSN to be sent in * next_tsn_at_change. */ transport->cacc.next_tsn_at_change = asoc->next_tsn; } /* Remove a transport from an association. */ void sctp_assoc_rm_peer(struct sctp_association *asoc, struct sctp_transport *peer) { struct list_head *pos; struct sctp_transport *transport; pr_debug("%s: association:%p addr:%pISpc\n", __func__, asoc, &peer->ipaddr.sa); /* If we are to remove the current retran_path, update it * to the next peer before removing this peer from the list. */ if (asoc->peer.retran_path == peer) sctp_assoc_update_retran_path(asoc); /* Remove this peer from the list. */ list_del_rcu(&peer->transports); /* Get the first transport of asoc. */ pos = asoc->peer.transport_addr_list.next; transport = list_entry(pos, struct sctp_transport, transports); /* Update any entries that match the peer to be deleted. */ if (asoc->peer.primary_path == peer) sctp_assoc_set_primary(asoc, transport); if (asoc->peer.active_path == peer) asoc->peer.active_path = transport; if (asoc->peer.retran_path == peer) asoc->peer.retran_path = transport; if (asoc->peer.last_data_from == peer) asoc->peer.last_data_from = transport; /* If we remove the transport an INIT was last sent to, set it to * NULL. Combined with the update of the retran path above, this * will cause the next INIT to be sent to the next available * transport, maintaining the cycle. */ if (asoc->init_last_sent_to == peer) asoc->init_last_sent_to = NULL; /* If we remove the transport an SHUTDOWN was last sent to, set it * to NULL. Combined with the update of the retran path above, this * will cause the next SHUTDOWN to be sent to the next available * transport, maintaining the cycle. */ if (asoc->shutdown_last_sent_to == peer) asoc->shutdown_last_sent_to = NULL; /* If we remove the transport an ASCONF was last sent to, set it to * NULL. */ if (asoc->addip_last_asconf && asoc->addip_last_asconf->transport == peer) asoc->addip_last_asconf->transport = NULL; /* If we have something on the transmitted list, we have to * save it off. The best place is the active path. */ if (!list_empty(&peer->transmitted)) { struct sctp_transport *active = asoc->peer.active_path; struct sctp_chunk *ch; /* Reset the transport of each chunk on this list */ list_for_each_entry(ch, &peer->transmitted, transmitted_list) { ch->transport = NULL; ch->rtt_in_progress = 0; } list_splice_tail_init(&peer->transmitted, &active->transmitted); /* Start a T3 timer here in case it wasn't running so * that these migrated packets have a chance to get * retransmitted. */ if (!timer_pending(&active->T3_rtx_timer)) if (!mod_timer(&active->T3_rtx_timer, jiffies + active->rto)) sctp_transport_hold(active); } asoc->peer.transport_count--; sctp_transport_free(peer); } /* Add a transport address to an association. */ struct sctp_transport *sctp_assoc_add_peer(struct sctp_association *asoc, const union sctp_addr *addr, const gfp_t gfp, const int peer_state) { struct net *net = sock_net(asoc->base.sk); struct sctp_transport *peer; struct sctp_sock *sp; unsigned short port; sp = sctp_sk(asoc->base.sk); /* AF_INET and AF_INET6 share common port field. */ port = ntohs(addr->v4.sin_port); pr_debug("%s: association:%p addr:%pISpc state:%d\n", __func__, asoc, &addr->sa, peer_state); /* Set the port if it has not been set yet. */ if (0 == asoc->peer.port) asoc->peer.port = port; /* Check to see if this is a duplicate. */ peer = sctp_assoc_lookup_paddr(asoc, addr); if (peer) { /* An UNKNOWN state is only set on transports added by * user in sctp_connectx() call. Such transports should be * considered CONFIRMED per RFC 4960, Section 5.4. */ if (peer->state == SCTP_UNKNOWN) { peer->state = SCTP_ACTIVE; } return peer; } peer = sctp_transport_new(net, addr, gfp); if (!peer) return NULL; sctp_transport_set_owner(peer, asoc); /* Initialize the peer's heartbeat interval based on the * association configured value. */ peer->hbinterval = asoc->hbinterval; /* Set the path max_retrans. */ peer->pathmaxrxt = asoc->pathmaxrxt; /* And the partial failure retrans threshold */ peer->pf_retrans = asoc->pf_retrans; /* Initialize the peer's SACK delay timeout based on the * association configured value. */ peer->sackdelay = asoc->sackdelay; peer->sackfreq = asoc->sackfreq; /* Enable/disable heartbeat, SACK delay, and path MTU discovery * based on association setting. */ peer->param_flags = asoc->param_flags; sctp_transport_route(peer, NULL, sp); /* Initialize the pmtu of the transport. */ if (peer->param_flags & SPP_PMTUD_DISABLE) { if (asoc->pathmtu) peer->pathmtu = asoc->pathmtu; else peer->pathmtu = SCTP_DEFAULT_MAXSEGMENT; } /* If this is the first transport addr on this association, * initialize the association PMTU to the peer's PMTU. * If not and the current association PMTU is higher than the new * peer's PMTU, reset the association PMTU to the new peer's PMTU. */ if (asoc->pathmtu) asoc->pathmtu = min_t(int, peer->pathmtu, asoc->pathmtu); else asoc->pathmtu = peer->pathmtu; pr_debug("%s: association:%p PMTU set to %d\n", __func__, asoc, asoc->pathmtu); peer->pmtu_pending = 0; asoc->frag_point = sctp_frag_point(asoc, asoc->pathmtu); /* The asoc->peer.port might not be meaningful yet, but * initialize the packet structure anyway. */ sctp_packet_init(&peer->packet, peer, asoc->base.bind_addr.port, asoc->peer.port); /* 7.2.1 Slow-Start * * o The initial cwnd before DATA transmission or after a sufficiently * long idle period MUST be set to * min(4*MTU, max(2*MTU, 4380 bytes)) * * o The initial value of ssthresh MAY be arbitrarily high * (for example, implementations MAY use the size of the * receiver advertised window). */ peer->cwnd = min(4*asoc->pathmtu, max_t(__u32, 2*asoc->pathmtu, 4380)); /* At this point, we may not have the receiver's advertised window, * so initialize ssthresh to the default value and it will be set * later when we process the INIT. */ peer->ssthresh = SCTP_DEFAULT_MAXWINDOW; peer->partial_bytes_acked = 0; peer->flight_size = 0; peer->burst_limited = 0; /* Set the transport's RTO.initial value */ peer->rto = asoc->rto_initial; sctp_max_rto(asoc, peer); /* Set the peer's active state. */ peer->state = peer_state; /* Attach the remote transport to our asoc. */ list_add_tail_rcu(&peer->transports, &asoc->peer.transport_addr_list); asoc->peer.transport_count++; /* If we do not yet have a primary path, set one. */ if (!asoc->peer.primary_path) { sctp_assoc_set_primary(asoc, peer); asoc->peer.retran_path = peer; } if (asoc->peer.active_path == asoc->peer.retran_path && peer->state != SCTP_UNCONFIRMED) { asoc->peer.retran_path = peer; } return peer; } /* Delete a transport address from an association. */ void sctp_assoc_del_peer(struct sctp_association *asoc, const union sctp_addr *addr) { struct list_head *pos; struct list_head *temp; struct sctp_transport *transport; list_for_each_safe(pos, temp, &asoc->peer.transport_addr_list) { transport = list_entry(pos, struct sctp_transport, transports); if (sctp_cmp_addr_exact(addr, &transport->ipaddr)) { /* Do book keeping for removing the peer and free it. */ sctp_assoc_rm_peer(asoc, transport); break; } } } /* Lookup a transport by address. */ struct sctp_transport *sctp_assoc_lookup_paddr( const struct sctp_association *asoc, const union sctp_addr *address) { struct sctp_transport *t; /* Cycle through all transports searching for a peer address. */ list_for_each_entry(t, &asoc->peer.transport_addr_list, transports) { if (sctp_cmp_addr_exact(address, &t->ipaddr)) return t; } return NULL; } /* Remove all transports except a give one */ void sctp_assoc_del_nonprimary_peers(struct sctp_association *asoc, struct sctp_transport *primary) { struct sctp_transport *temp; struct sctp_transport *t; list_for_each_entry_safe(t, temp, &asoc->peer.transport_addr_list, transports) { /* if the current transport is not the primary one, delete it */ if (t != primary) sctp_assoc_rm_peer(asoc, t); } } /* Engage in transport control operations. * Mark the transport up or down and send a notification to the user. * Select and update the new active and retran paths. */ void sctp_assoc_control_transport(struct sctp_association *asoc, struct sctp_transport *transport, sctp_transport_cmd_t command, sctp_sn_error_t error) { struct sctp_ulpevent *event; struct sockaddr_storage addr; int spc_state = 0; bool ulp_notify = true; /* Record the transition on the transport. */ switch (command) { case SCTP_TRANSPORT_UP: /* If we are moving from UNCONFIRMED state due * to heartbeat success, report the SCTP_ADDR_CONFIRMED * state to the user, otherwise report SCTP_ADDR_AVAILABLE. */ if (SCTP_UNCONFIRMED == transport->state && SCTP_HEARTBEAT_SUCCESS == error) spc_state = SCTP_ADDR_CONFIRMED; else spc_state = SCTP_ADDR_AVAILABLE; /* Don't inform ULP about transition from PF to * active state and set cwnd to 1 MTU, see SCTP * Quick failover draft section 5.1, point 5 */ if (transport->state == SCTP_PF) { ulp_notify = false; transport->cwnd = asoc->pathmtu; } transport->state = SCTP_ACTIVE; break; case SCTP_TRANSPORT_DOWN: /* If the transport was never confirmed, do not transition it * to inactive state. Also, release the cached route since * there may be a better route next time. */ if (transport->state != SCTP_UNCONFIRMED) transport->state = SCTP_INACTIVE; else { dst_release(transport->dst); transport->dst = NULL; } spc_state = SCTP_ADDR_UNREACHABLE; break; case SCTP_TRANSPORT_PF: transport->state = SCTP_PF; ulp_notify = false; break; default: return; } /* Generate and send a SCTP_PEER_ADDR_CHANGE notification * to the user. */ if (ulp_notify) { memset(&addr, 0, sizeof(struct sockaddr_storage)); memcpy(&addr, &transport->ipaddr, transport->af_specific->sockaddr_len); event = sctp_ulpevent_make_peer_addr_change(asoc, &addr, 0, spc_state, error, GFP_ATOMIC); if (event) sctp_ulpq_tail_event(&asoc->ulpq, event); } /* Select new active and retran paths. */ sctp_select_active_and_retran_path(asoc); } /* Hold a reference to an association. */ void sctp_association_hold(struct sctp_association *asoc) { atomic_inc(&asoc->base.refcnt); } /* Release a reference to an association and cleanup * if there are no more references. */ void sctp_association_put(struct sctp_association *asoc) { if (atomic_dec_and_test(&asoc->base.refcnt)) sctp_association_destroy(asoc); } /* Allocate the next TSN, Transmission Sequence Number, for the given * association. */ __u32 sctp_association_get_next_tsn(struct sctp_association *asoc) { /* From Section 1.6 Serial Number Arithmetic: * Transmission Sequence Numbers wrap around when they reach * 2**32 - 1. That is, the next TSN a DATA chunk MUST use * after transmitting TSN = 2*32 - 1 is TSN = 0. */ __u32 retval = asoc->next_tsn; asoc->next_tsn++; asoc->unack_data++; return retval; } /* Compare two addresses to see if they match. Wildcard addresses * only match themselves. */ int sctp_cmp_addr_exact(const union sctp_addr *ss1, const union sctp_addr *ss2) { struct sctp_af *af; af = sctp_get_af_specific(ss1->sa.sa_family); if (unlikely(!af)) return 0; return af->cmp_addr(ss1, ss2); } /* Return an ecne chunk to get prepended to a packet. * Note: We are sly and return a shared, prealloced chunk. FIXME: * No we don't, but we could/should. */ struct sctp_chunk *sctp_get_ecne_prepend(struct sctp_association *asoc) { if (!asoc->need_ecne) return NULL; /* Send ECNE if needed. * Not being able to allocate a chunk here is not deadly. */ return sctp_make_ecne(asoc, asoc->last_ecne_tsn); } /* * Find which transport this TSN was sent on. */ struct sctp_transport *sctp_assoc_lookup_tsn(struct sctp_association *asoc, __u32 tsn) { struct sctp_transport *active; struct sctp_transport *match; struct sctp_transport *transport; struct sctp_chunk *chunk; __be32 key = htonl(tsn); match = NULL; /* * FIXME: In general, find a more efficient data structure for * searching. */ /* * The general strategy is to search each transport's transmitted * list. Return which transport this TSN lives on. * * Let's be hopeful and check the active_path first. * Another optimization would be to know if there is only one * outbound path and not have to look for the TSN at all. * */ active = asoc->peer.active_path; list_for_each_entry(chunk, &active->transmitted, transmitted_list) { if (key == chunk->subh.data_hdr->tsn) { match = active; goto out; } } /* If not found, go search all the other transports. */ list_for_each_entry(transport, &asoc->peer.transport_addr_list, transports) { if (transport == active) continue; list_for_each_entry(chunk, &transport->transmitted, transmitted_list) { if (key == chunk->subh.data_hdr->tsn) { match = transport; goto out; } } } out: return match; } /* Is this the association we are looking for? */ struct sctp_transport *sctp_assoc_is_match(struct sctp_association *asoc, struct net *net, const union sctp_addr *laddr, const union sctp_addr *paddr) { struct sctp_transport *transport; if ((htons(asoc->base.bind_addr.port) == laddr->v4.sin_port) && (htons(asoc->peer.port) == paddr->v4.sin_port) && net_eq(sock_net(asoc->base.sk), net)) { transport = sctp_assoc_lookup_paddr(asoc, paddr); if (!transport) goto out; if (sctp_bind_addr_match(&asoc->base.bind_addr, laddr, sctp_sk(asoc->base.sk))) goto out; } transport = NULL; out: return transport; } /* Do delayed input processing. This is scheduled by sctp_rcv(). */ static void sctp_assoc_bh_rcv(struct work_struct *work) { struct sctp_association *asoc = container_of(work, struct sctp_association, base.inqueue.immediate); struct net *net = sock_net(asoc->base.sk); struct sctp_endpoint *ep; struct sctp_chunk *chunk; struct sctp_inq *inqueue; int state; sctp_subtype_t subtype; int error = 0; /* The association should be held so we should be safe. */ ep = asoc->ep; inqueue = &asoc->base.inqueue; sctp_association_hold(asoc); while (NULL != (chunk = sctp_inq_pop(inqueue))) { state = asoc->state; subtype = SCTP_ST_CHUNK(chunk->chunk_hdr->type); /* SCTP-AUTH, Section 6.3: * The receiver has a list of chunk types which it expects * to be received only after an AUTH-chunk. This list has * been sent to the peer during the association setup. It * MUST silently discard these chunks if they are not placed * after an AUTH chunk in the packet. */ if (sctp_auth_recv_cid(subtype.chunk, asoc) && !chunk->auth) continue; /* Remember where the last DATA chunk came from so we * know where to send the SACK. */ if (sctp_chunk_is_data(chunk)) asoc->peer.last_data_from = chunk->transport; else { SCTP_INC_STATS(net, SCTP_MIB_INCTRLCHUNKS); asoc->stats.ictrlchunks++; if (chunk->chunk_hdr->type == SCTP_CID_SACK) asoc->stats.isacks++; } if (chunk->transport) chunk->transport->last_time_heard = ktime_get(); /* Run through the state machine. */ error = sctp_do_sm(net, SCTP_EVENT_T_CHUNK, subtype, state, ep, asoc, chunk, GFP_ATOMIC); /* Check to see if the association is freed in response to * the incoming chunk. If so, get out of the while loop. */ if (asoc->base.dead) break; /* If there is an error on chunk, discard this packet. */ if (error && chunk) chunk->pdiscard = 1; } sctp_association_put(asoc); } /* This routine moves an association from its old sk to a new sk. */ void sctp_assoc_migrate(struct sctp_association *assoc, struct sock *newsk) { struct sctp_sock *newsp = sctp_sk(newsk); struct sock *oldsk = assoc->base.sk; /* Delete the association from the old endpoint's list of * associations. */ list_del_init(&assoc->asocs); /* Decrement the backlog value for a TCP-style socket. */ if (sctp_style(oldsk, TCP)) oldsk->sk_ack_backlog--; /* Release references to the old endpoint and the sock. */ sctp_endpoint_put(assoc->ep); sock_put(assoc->base.sk); /* Get a reference to the new endpoint. */ assoc->ep = newsp->ep; sctp_endpoint_hold(assoc->ep); /* Get a reference to the new sock. */ assoc->base.sk = newsk; sock_hold(assoc->base.sk); /* Add the association to the new endpoint's list of associations. */ sctp_endpoint_add_asoc(newsp->ep, assoc); } /* Update an association (possibly from unexpected COOKIE-ECHO processing). */ void sctp_assoc_update(struct sctp_association *asoc, struct sctp_association *new) { struct sctp_transport *trans; struct list_head *pos, *temp; /* Copy in new parameters of peer. */ asoc->c = new->c; asoc->peer.rwnd = new->peer.rwnd; asoc->peer.sack_needed = new->peer.sack_needed; asoc->peer.i = new->peer.i; sctp_tsnmap_init(&asoc->peer.tsn_map, SCTP_TSN_MAP_INITIAL, asoc->peer.i.initial_tsn, GFP_ATOMIC); /* Remove any peer addresses not present in the new association. */ list_for_each_safe(pos, temp, &asoc->peer.transport_addr_list) { trans = list_entry(pos, struct sctp_transport, transports); if (!sctp_assoc_lookup_paddr(new, &trans->ipaddr)) { sctp_assoc_rm_peer(asoc, trans); continue; } if (asoc->state >= SCTP_STATE_ESTABLISHED) sctp_transport_reset(trans); } /* If the case is A (association restart), use * initial_tsn as next_tsn. If the case is B, use * current next_tsn in case data sent to peer * has been discarded and needs retransmission. */ if (asoc->state >= SCTP_STATE_ESTABLISHED) { asoc->next_tsn = new->next_tsn; asoc->ctsn_ack_point = new->ctsn_ack_point; asoc->adv_peer_ack_point = new->adv_peer_ack_point; /* Reinitialize SSN for both local streams * and peer's streams. */ sctp_ssnmap_clear(asoc->ssnmap); /* Flush the ULP reassembly and ordered queue. * Any data there will now be stale and will * cause problems. */ sctp_ulpq_flush(&asoc->ulpq); /* reset the overall association error count so * that the restarted association doesn't get torn * down on the next retransmission timer. */ asoc->overall_error_count = 0; } else { /* Add any peer addresses from the new association. */ list_for_each_entry(trans, &new->peer.transport_addr_list, transports) { if (!sctp_assoc_lookup_paddr(asoc, &trans->ipaddr)) sctp_assoc_add_peer(asoc, &trans->ipaddr, GFP_ATOMIC, trans->state); } asoc->ctsn_ack_point = asoc->next_tsn - 1; asoc->adv_peer_ack_point = asoc->ctsn_ack_point; if (!asoc->ssnmap) { /* Move the ssnmap. */ asoc->ssnmap = new->ssnmap; new->ssnmap = NULL; } if (!asoc->assoc_id) { /* get a new association id since we don't have one * yet. */ sctp_assoc_set_id(asoc, GFP_ATOMIC); } } /* SCTP-AUTH: Save the peer parameters from the new associations * and also move the association shared keys over */ kfree(asoc->peer.peer_random); asoc->peer.peer_random = new->peer.peer_random; new->peer.peer_random = NULL; kfree(asoc->peer.peer_chunks); asoc->peer.peer_chunks = new->peer.peer_chunks; new->peer.peer_chunks = NULL; kfree(asoc->peer.peer_hmacs); asoc->peer.peer_hmacs = new->peer.peer_hmacs; new->peer.peer_hmacs = NULL; sctp_auth_key_put(asoc->asoc_shared_key); sctp_auth_asoc_init_active_key(asoc, GFP_ATOMIC); } /* Update the retran path for sending a retransmitted packet. * See also RFC4960, 6.4. Multi-Homed SCTP Endpoints: * * When there is outbound data to send and the primary path * becomes inactive (e.g., due to failures), or where the * SCTP user explicitly requests to send data to an * inactive destination transport address, before reporting * an error to its ULP, the SCTP endpoint should try to send * the data to an alternate active destination transport * address if one exists. * * When retransmitting data that timed out, if the endpoint * is multihomed, it should consider each source-destination * address pair in its retransmission selection policy. * When retransmitting timed-out data, the endpoint should * attempt to pick the most divergent source-destination * pair from the original source-destination pair to which * the packet was transmitted. * * Note: Rules for picking the most divergent source-destination * pair are an implementation decision and are not specified * within this document. * * Our basic strategy is to round-robin transports in priorities * according to sctp_state_prio_map[] e.g., if no such * transport with state SCTP_ACTIVE exists, round-robin through * SCTP_UNKNOWN, etc. You get the picture. */ static const u8 sctp_trans_state_to_prio_map[] = { [SCTP_ACTIVE] = 3, /* best case */ [SCTP_UNKNOWN] = 2, [SCTP_PF] = 1, [SCTP_INACTIVE] = 0, /* worst case */ }; static u8 sctp_trans_score(const struct sctp_transport *trans) { return sctp_trans_state_to_prio_map[trans->state]; } static struct sctp_transport *sctp_trans_elect_tie(struct sctp_transport *trans1, struct sctp_transport *trans2) { if (trans1->error_count > trans2->error_count) { return trans2; } else if (trans1->error_count == trans2->error_count && ktime_after(trans2->last_time_heard, trans1->last_time_heard)) { return trans2; } else { return trans1; } } static struct sctp_transport *sctp_trans_elect_best(struct sctp_transport *curr, struct sctp_transport *best) { u8 score_curr, score_best; if (best == NULL) return curr; score_curr = sctp_trans_score(curr); score_best = sctp_trans_score(best); /* First, try a score-based selection if both transport states * differ. If we're in a tie, lets try to make a more clever * decision here based on error counts and last time heard. */ if (score_curr > score_best) return curr; else if (score_curr == score_best) return sctp_trans_elect_tie(curr, best); else return best; } void sctp_assoc_update_retran_path(struct sctp_association *asoc) { struct sctp_transport *trans = asoc->peer.retran_path; struct sctp_transport *trans_next = NULL; /* We're done as we only have the one and only path. */ if (asoc->peer.transport_count == 1) return; /* If active_path and retran_path are the same and active, * then this is the only active path. Use it. */ if (asoc->peer.active_path == asoc->peer.retran_path && asoc->peer.active_path->state == SCTP_ACTIVE) return; /* Iterate from retran_path's successor back to retran_path. */ for (trans = list_next_entry(trans, transports); 1; trans = list_next_entry(trans, transports)) { /* Manually skip the head element. */ if (&trans->transports == &asoc->peer.transport_addr_list) continue; if (trans->state == SCTP_UNCONFIRMED) continue; trans_next = sctp_trans_elect_best(trans, trans_next); /* Active is good enough for immediate return. */ if (trans_next->state == SCTP_ACTIVE) break; /* We've reached the end, time to update path. */ if (trans == asoc->peer.retran_path) break; } asoc->peer.retran_path = trans_next; pr_debug("%s: association:%p updated new path to addr:%pISpc\n", __func__, asoc, &asoc->peer.retran_path->ipaddr.sa); } static void sctp_select_active_and_retran_path(struct sctp_association *asoc) { struct sctp_transport *trans, *trans_pri = NULL, *trans_sec = NULL; struct sctp_transport *trans_pf = NULL; /* Look for the two most recently used active transports. */ list_for_each_entry(trans, &asoc->peer.transport_addr_list, transports) { /* Skip uninteresting transports. */ if (trans->state == SCTP_INACTIVE || trans->state == SCTP_UNCONFIRMED) continue; /* Keep track of the best PF transport from our * list in case we don't find an active one. */ if (trans->state == SCTP_PF) { trans_pf = sctp_trans_elect_best(trans, trans_pf); continue; } /* For active transports, pick the most recent ones. */ if (trans_pri == NULL || ktime_after(trans->last_time_heard, trans_pri->last_time_heard)) { trans_sec = trans_pri; trans_pri = trans; } else if (trans_sec == NULL || ktime_after(trans->last_time_heard, trans_sec->last_time_heard)) { trans_sec = trans; } } /* RFC 2960 6.4 Multi-Homed SCTP Endpoints * * By default, an endpoint should always transmit to the primary * path, unless the SCTP user explicitly specifies the * destination transport address (and possibly source transport * address) to use. [If the primary is active but not most recent, * bump the most recently used transport.] */ if ((asoc->peer.primary_path->state == SCTP_ACTIVE || asoc->peer.primary_path->state == SCTP_UNKNOWN) && asoc->peer.primary_path != trans_pri) { trans_sec = trans_pri; trans_pri = asoc->peer.primary_path; } /* We did not find anything useful for a possible retransmission * path; either primary path that we found is the the same as * the current one, or we didn't generally find an active one. */ if (trans_sec == NULL) trans_sec = trans_pri; /* If we failed to find a usable transport, just camp on the * primary or retran, even if they are inactive, if possible * pick a PF iff it's the better choice. */ if (trans_pri == NULL) { trans_pri = sctp_trans_elect_best(asoc->peer.primary_path, asoc->peer.retran_path); trans_pri = sctp_trans_elect_best(trans_pri, trans_pf); trans_sec = asoc->peer.primary_path; } /* Set the active and retran transports. */ asoc->peer.active_path = trans_pri; asoc->peer.retran_path = trans_sec; } struct sctp_transport * sctp_assoc_choose_alter_transport(struct sctp_association *asoc, struct sctp_transport *last_sent_to) { /* If this is the first time packet is sent, use the active path, * else use the retran path. If the last packet was sent over the * retran path, update the retran path and use it. */ if (last_sent_to == NULL) { return asoc->peer.active_path; } else { if (last_sent_to == asoc->peer.retran_path) sctp_assoc_update_retran_path(asoc); return asoc->peer.retran_path; } } /* Update the association's pmtu and frag_point by going through all the * transports. This routine is called when a transport's PMTU has changed. */ void sctp_assoc_sync_pmtu(struct sock *sk, struct sctp_association *asoc) { struct sctp_transport *t; __u32 pmtu = 0; if (!asoc) return; /* Get the lowest pmtu of all the transports. */ list_for_each_entry(t, &asoc->peer.transport_addr_list, transports) { if (t->pmtu_pending && t->dst) { sctp_transport_update_pmtu(sk, t, dst_mtu(t->dst)); t->pmtu_pending = 0; } if (!pmtu || (t->pathmtu < pmtu)) pmtu = t->pathmtu; } if (pmtu) { asoc->pathmtu = pmtu; asoc->frag_point = sctp_frag_point(asoc, pmtu); } pr_debug("%s: asoc:%p, pmtu:%d, frag_point:%d\n", __func__, asoc, asoc->pathmtu, asoc->frag_point); } /* Should we send a SACK to update our peer? */ static inline bool sctp_peer_needs_update(struct sctp_association *asoc) { struct net *net = sock_net(asoc->base.sk); switch (asoc->state) { case SCTP_STATE_ESTABLISHED: case SCTP_STATE_SHUTDOWN_PENDING: case SCTP_STATE_SHUTDOWN_RECEIVED: case SCTP_STATE_SHUTDOWN_SENT: if ((asoc->rwnd > asoc->a_rwnd) && ((asoc->rwnd - asoc->a_rwnd) >= max_t(__u32, (asoc->base.sk->sk_rcvbuf >> net->sctp.rwnd_upd_shift), asoc->pathmtu))) return true; break; default: break; } return false; } /* Increase asoc's rwnd by len and send any window update SACK if needed. */ void sctp_assoc_rwnd_increase(struct sctp_association *asoc, unsigned int len) { struct sctp_chunk *sack; struct timer_list *timer; if (asoc->rwnd_over) { if (asoc->rwnd_over >= len) { asoc->rwnd_over -= len; } else { asoc->rwnd += (len - asoc->rwnd_over); asoc->rwnd_over = 0; } } else { asoc->rwnd += len; } /* If we had window pressure, start recovering it * once our rwnd had reached the accumulated pressure * threshold. The idea is to recover slowly, but up * to the initial advertised window. */ if (asoc->rwnd_press && asoc->rwnd >= asoc->rwnd_press) { int change = min(asoc->pathmtu, asoc->rwnd_press); asoc->rwnd += change; asoc->rwnd_press -= change; } pr_debug("%s: asoc:%p rwnd increased by %d to (%u, %u) - %u\n", __func__, asoc, len, asoc->rwnd, asoc->rwnd_over, asoc->a_rwnd); /* Send a window update SACK if the rwnd has increased by at least the * minimum of the association's PMTU and half of the receive buffer. * The algorithm used is similar to the one described in * Section 4.2.3.3 of RFC 1122. */ if (sctp_peer_needs_update(asoc)) { asoc->a_rwnd = asoc->rwnd; pr_debug("%s: sending window update SACK- asoc:%p rwnd:%u " "a_rwnd:%u\n", __func__, asoc, asoc->rwnd, asoc->a_rwnd); sack = sctp_make_sack(asoc); if (!sack) return; asoc->peer.sack_needed = 0; sctp_outq_tail(&asoc->outqueue, sack); /* Stop the SACK timer. */ timer = &asoc->timers[SCTP_EVENT_TIMEOUT_SACK]; if (del_timer(timer)) sctp_association_put(asoc); } } /* Decrease asoc's rwnd by len. */ void sctp_assoc_rwnd_decrease(struct sctp_association *asoc, unsigned int len) { int rx_count; int over = 0; if (unlikely(!asoc->rwnd || asoc->rwnd_over)) pr_debug("%s: association:%p has asoc->rwnd:%u, " "asoc->rwnd_over:%u!\n", __func__, asoc, asoc->rwnd, asoc->rwnd_over); if (asoc->ep->rcvbuf_policy) rx_count = atomic_read(&asoc->rmem_alloc); else rx_count = atomic_read(&asoc->base.sk->sk_rmem_alloc); /* If we've reached or overflowed our receive buffer, announce * a 0 rwnd if rwnd would still be positive. Store the * the potential pressure overflow so that the window can be restored * back to original value. */ if (rx_count >= asoc->base.sk->sk_rcvbuf) over = 1; if (asoc->rwnd >= len) { asoc->rwnd -= len; if (over) { asoc->rwnd_press += asoc->rwnd; asoc->rwnd = 0; } } else { asoc->rwnd_over = len - asoc->rwnd; asoc->rwnd = 0; } pr_debug("%s: asoc:%p rwnd decreased by %d to (%u, %u, %u)\n", __func__, asoc, len, asoc->rwnd, asoc->rwnd_over, asoc->rwnd_press); } /* Build the bind address list for the association based on info from the * local endpoint and the remote peer. */ int sctp_assoc_set_bind_addr_from_ep(struct sctp_association *asoc, sctp_scope_t scope, gfp_t gfp) { int flags; /* Use scoping rules to determine the subset of addresses from * the endpoint. */ flags = (PF_INET6 == asoc->base.sk->sk_family) ? SCTP_ADDR6_ALLOWED : 0; if (asoc->peer.ipv4_address) flags |= SCTP_ADDR4_PEERSUPP; if (asoc->peer.ipv6_address) flags |= SCTP_ADDR6_PEERSUPP; return sctp_bind_addr_copy(sock_net(asoc->base.sk), &asoc->base.bind_addr, &asoc->ep->base.bind_addr, scope, gfp, flags); } /* Build the association's bind address list from the cookie. */ int sctp_assoc_set_bind_addr_from_cookie(struct sctp_association *asoc, struct sctp_cookie *cookie, gfp_t gfp) { int var_size2 = ntohs(cookie->peer_init->chunk_hdr.length); int var_size3 = cookie->raw_addr_list_len; __u8 *raw = (__u8 *)cookie->peer_init + var_size2; return sctp_raw_to_bind_addrs(&asoc->base.bind_addr, raw, var_size3, asoc->ep->base.bind_addr.port, gfp); } /* Lookup laddr in the bind address list of an association. */ int sctp_assoc_lookup_laddr(struct sctp_association *asoc, const union sctp_addr *laddr) { int found = 0; if ((asoc->base.bind_addr.port == ntohs(laddr->v4.sin_port)) && sctp_bind_addr_match(&asoc->base.bind_addr, laddr, sctp_sk(asoc->base.sk))) found = 1; return found; } /* Set an association id for a given association */ int sctp_assoc_set_id(struct sctp_association *asoc, gfp_t gfp) { bool preload = !!(gfp & __GFP_WAIT); int ret; /* If the id is already assigned, keep it. */ if (asoc->assoc_id) return 0; if (preload) idr_preload(gfp); spin_lock_bh(&sctp_assocs_id_lock); /* 0 is not a valid assoc_id, must be >= 1 */ ret = idr_alloc_cyclic(&sctp_assocs_id, asoc, 1, 0, GFP_NOWAIT); spin_unlock_bh(&sctp_assocs_id_lock); if (preload) idr_preload_end(); if (ret < 0) return ret; asoc->assoc_id = (sctp_assoc_t)ret; return 0; } /* Free the ASCONF queue */ static void sctp_assoc_free_asconf_queue(struct sctp_association *asoc) { struct sctp_chunk *asconf; struct sctp_chunk *tmp; list_for_each_entry_safe(asconf, tmp, &asoc->addip_chunk_list, list) { list_del_init(&asconf->list); sctp_chunk_free(asconf); } } /* Free asconf_ack cache */ static void sctp_assoc_free_asconf_acks(struct sctp_association *asoc) { struct sctp_chunk *ack; struct sctp_chunk *tmp; list_for_each_entry_safe(ack, tmp, &asoc->asconf_ack_list, transmitted_list) { list_del_init(&ack->transmitted_list); sctp_chunk_free(ack); } } /* Clean up the ASCONF_ACK queue */ void sctp_assoc_clean_asconf_ack_cache(const struct sctp_association *asoc) { struct sctp_chunk *ack; struct sctp_chunk *tmp; /* We can remove all the entries from the queue up to * the "Peer-Sequence-Number". */ list_for_each_entry_safe(ack, tmp, &asoc->asconf_ack_list, transmitted_list) { if (ack->subh.addip_hdr->serial == htonl(asoc->peer.addip_serial)) break; list_del_init(&ack->transmitted_list); sctp_chunk_free(ack); } } /* Find the ASCONF_ACK whose serial number matches ASCONF */ struct sctp_chunk *sctp_assoc_lookup_asconf_ack( const struct sctp_association *asoc, __be32 serial) { struct sctp_chunk *ack; /* Walk through the list of cached ASCONF-ACKs and find the * ack chunk whose serial number matches that of the request. */ list_for_each_entry(ack, &asoc->asconf_ack_list, transmitted_list) { if (ack->subh.addip_hdr->serial == serial) { sctp_chunk_hold(ack); return ack; } } return NULL; } void sctp_asconf_queue_teardown(struct sctp_association *asoc) { /* Free any cached ASCONF_ACK chunk. */ sctp_assoc_free_asconf_acks(asoc); /* Free the ASCONF queue. */ sctp_assoc_free_asconf_queue(asoc); /* Free any cached ASCONF chunk. */ if (asoc->addip_last_asconf) sctp_chunk_free(asoc->addip_last_asconf); }
./CrossVul/dataset_final_sorted/CWE-20/c/good_2221_0
crossvul-cpp_data_bad_5183_0
/* Crop support * manual crop using a gdRect or automatic crop using a background * color (automatic detections or using either the transparent color, * black or white). * An alternative method allows to crop using a given color and a * threshold. It works relatively well but it can be improved. * Maybe L*a*b* and Delta-E will give better results (and a better * granularity). */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <stdlib.h> #include "gd.h" #include "gd_color.h" static int gdGuessBackgroundColorFromCorners(gdImagePtr im, int *color); BGD_DECLARE(gdImagePtr) gdImageCrop(gdImagePtr src, const gdRect *crop) { gdImagePtr dst; dst = gdImageCreateTrueColor(crop->width, crop->height); if (!dst) return NULL; gdImageCopy(dst, src, 0, 0, crop->x, crop->y, crop->width, crop->height); return dst; } BGD_DECLARE(gdImagePtr) gdImageCropAuto(gdImagePtr im, const unsigned int mode) { const int width = gdImageSX(im); const int height = gdImageSY(im); int x,y; int color, match; gdRect crop; crop.x = 0; crop.y = 0; crop.width = 0; crop.height = 0; switch (mode) { case GD_CROP_TRANSPARENT: color = gdImageGetTransparent(im); break; case GD_CROP_BLACK: color = gdImageColorClosestAlpha(im, 0, 0, 0, 0); break; case GD_CROP_WHITE: color = gdImageColorClosestAlpha(im, 255, 255, 255, 0); break; case GD_CROP_SIDES: gdGuessBackgroundColorFromCorners(im, &color); break; case GD_CROP_DEFAULT: default: color = gdImageGetTransparent(im); break; } /* TODO: Add gdImageGetRowPtr and works with ptr at the row level * for the true color and palette images * new formats will simply work with ptr */ match = 1; for (y = 0; match && y < height; y++) { for (x = 0; match && x < width; x++) { match = (color == gdImageGetPixel(im, x,y)); } } /* Nothing to do > bye * Duplicate the image? */ if (y == height - 1) { return NULL; } crop.y = y -1; match = 1; for (y = height - 1; match && y >= 0; y--) { for (x = 0; match && x < width; x++) { match = (color == gdImageGetPixel(im, x,y)); } } if (y == 0) { crop.height = height - crop.y + 1; } else { crop.height = y - crop.y + 2; } match = 1; for (x = 0; match && x < width; x++) { for (y = 0; match && y < crop.y + crop.height - 1; y++) { match = (color == gdImageGetPixel(im, x,y)); } } crop.x = x - 1; match = 1; for (x = width - 1; match && x >= 0; x--) { for (y = 0; match && y < crop.y + crop.height - 1; y++) { match = (color == gdImageGetPixel(im, x,y)); } } crop.width = x - crop.x + 2; return gdImageCrop(im, &crop); } BGD_DECLARE(gdImagePtr) gdImageCropThreshold(gdImagePtr im, const unsigned int color, const float threshold) { const int width = gdImageSX(im); const int height = gdImageSY(im); int x,y; int match; gdRect crop; crop.x = 0; crop.y = 0; crop.width = 0; crop.height = 0; /* Pierre: crop everything sounds bad */ if (threshold > 100.0) { return NULL; } /* TODO: Add gdImageGetRowPtr and works with ptr at the row level * for the true color and palette images * new formats will simply work with ptr */ match = 1; for (y = 0; match && y < height; y++) { for (x = 0; match && x < width; x++) { match = (gdColorMatch(im, color, gdImageGetPixel(im, x,y), threshold)) > 0; } } /* Pierre * Nothing to do > bye * Duplicate the image? */ if (y == height - 1) { return NULL; } crop.y = y -1; match = 1; for (y = height - 1; match && y >= 0; y--) { for (x = 0; match && x < width; x++) { match = (gdColorMatch(im, color, gdImageGetPixel(im, x, y), threshold)) > 0; } } if (y == 0) { crop.height = height - crop.y + 1; } else { crop.height = y - crop.y + 2; } match = 1; for (x = 0; match && x < width; x++) { for (y = 0; match && y < crop.y + crop.height - 1; y++) { match = (gdColorMatch(im, color, gdImageGetPixel(im, x,y), threshold)) > 0; } } crop.x = x - 1; match = 1; for (x = width - 1; match && x >= 0; x--) { for (y = 0; match && y < crop.y + crop.height - 1; y++) { match = (gdColorMatch(im, color, gdImageGetPixel(im, x,y), threshold)) > 0; } } crop.width = x - crop.x + 2; return gdImageCrop(im, &crop); } /* This algorithm comes from pnmcrop (http://netpbm.sourceforge.net/) * Three steps: * - if 3 corners are equal. * - if two are equal. * - Last solution: average the colors */ static int gdGuessBackgroundColorFromCorners(gdImagePtr im, int *color) { const int tl = gdImageGetPixel(im, 0, 0); const int tr = gdImageGetPixel(im, gdImageSX(im) - 1, 0); const int bl = gdImageGetPixel(im, 0, gdImageSY(im) -1); const int br = gdImageGetPixel(im, gdImageSX(im) - 1, gdImageSY(im) -1); if (tr == bl && tr == br) { *color = tr; return 3; } else if (tl == bl && tl == br) { *color = tl; return 3; } else if (tl == tr && tl == br) { *color = tl; return 3; } else if (tl == tr && tl == bl) { *color = tl; return 3; } else if (tl == tr || tl == bl || tl == br) { *color = tl; return 2; } else if (tr == bl) { *color = tr; return 2; } else if (br == bl) { *color = bl; return 2; } else { register int r,b,g,a; r = (int)(0.5f + (gdImageRed(im, tl) + gdImageRed(im, tr) + gdImageRed(im, bl) + gdImageRed(im, br)) / 4); g = (int)(0.5f + (gdImageGreen(im, tl) + gdImageGreen(im, tr) + gdImageGreen(im, bl) + gdImageGreen(im, br)) / 4); b = (int)(0.5f + (gdImageBlue(im, tl) + gdImageBlue(im, tr) + gdImageBlue(im, bl) + gdImageBlue(im, br)) / 4); a = (int)(0.5f + (gdImageAlpha(im, tl) + gdImageAlpha(im, tr) + gdImageAlpha(im, bl) + gdImageAlpha(im, br)) / 4); *color = gdImageColorClosestAlpha(im, r, g, b, a); return 0; } }
./CrossVul/dataset_final_sorted/CWE-20/c/bad_5183_0
crossvul-cpp_data_good_5595_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_deliver(struct kvm_ioapic *vioapic, int irq); 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 int ioapic_service(struct kvm_ioapic *ioapic, unsigned int idx) { union kvm_ioapic_redirect_entry *pent; int injected = -1; pent = &ioapic->redirtbl[idx]; if (!pent->fields.mask) { injected = ioapic_deliver(ioapic, idx); if (injected && pent->fields.trig_mode == IOAPIC_LEVEL_TRIG) pent->fields.remote_irr = 1; } return injected; } static void update_handled_vectors(struct kvm_ioapic *ioapic) { DECLARE_BITMAP(handled_vectors, 256); int i; memset(handled_vectors, 0, sizeof(handled_vectors)); for (i = 0; i < IOAPIC_NUM_PINS; ++i) __set_bit(ioapic->redirtbl[i].fields.vector, handled_vectors); memcpy(ioapic->handled_vectors, handled_vectors, sizeof(handled_vectors)); smp_wmb(); } void kvm_ioapic_calculate_eoi_exitmap(struct kvm_vcpu *vcpu, u64 *eoi_exit_bitmap) { struct kvm_ioapic *ioapic = vcpu->kvm->arch.vioapic; union kvm_ioapic_redirect_entry *e; struct kvm_lapic_irq irqe; int index; spin_lock(&ioapic->lock); /* traverse ioapic entry to set eoi exit bitmap*/ for (index = 0; index < IOAPIC_NUM_PINS; index++) { e = &ioapic->redirtbl[index]; if (!e->fields.mask && (e->fields.trig_mode == IOAPIC_LEVEL_TRIG || kvm_irq_has_notifier(ioapic->kvm, KVM_IRQCHIP_IOAPIC, index))) { irqe.dest_id = e->fields.dest_id; irqe.vector = e->fields.vector; irqe.dest_mode = e->fields.dest_mode; irqe.delivery_mode = e->fields.delivery_mode << 8; kvm_calculate_eoi_exitmap(vcpu, &irqe, eoi_exit_bitmap); } } spin_unlock(&ioapic->lock); } EXPORT_SYMBOL_GPL(kvm_ioapic_calculate_eoi_exitmap); void kvm_ioapic_make_eoibitmap_request(struct kvm *kvm) { struct kvm_ioapic *ioapic = kvm->arch.vioapic; if (!kvm_apic_vid_enabled(kvm) || !ioapic) return; kvm_make_update_eoibitmap_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; } update_handled_vectors(ioapic); 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); kvm_ioapic_make_eoibitmap_request(ioapic->kvm); break; } } static int ioapic_deliver(struct kvm_ioapic *ioapic, int irq) { union kvm_ioapic_redirect_entry *entry = &ioapic->redirtbl[irq]; struct kvm_lapic_irq irqe; 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; return kvm_irq_delivery_to_apic(ioapic->kvm, NULL, &irqe); } int kvm_ioapic_set_irq(struct kvm_ioapic *ioapic, int irq, int irq_source_id, int level) { u32 old_irr; u32 mask = 1 << irq; union kvm_ioapic_redirect_entry entry; int ret, irq_level; BUG_ON(irq < 0 || irq >= IOAPIC_NUM_PINS); spin_lock(&ioapic->lock); old_irr = ioapic->irr; irq_level = __kvm_irq_line_state(&ioapic->irq_states[irq], irq_source_id, level); entry = ioapic->redirtbl[irq]; irq_level ^= entry.fields.polarity; if (!irq_level) { ioapic->irr &= ~mask; ret = 1; } else { int edge = (entry.fields.trig_mode == IOAPIC_EDGE_TRIG); ioapic->irr |= mask; if ((edge && old_irr != ioapic->irr) || (!edge && !entry.fields.remote_irr)) ret = ioapic_service(ioapic, irq); else ret = 0; /* report coalesced interrupt */ } trace_kvm_ioapic_set_irq(entry.bits, irq, ret == 0); 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_update_eoi(struct kvm_ioapic *ioapic, int vector, int trigger_mode) { int i; 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) continue; ASSERT(ent->fields.trig_mode == IOAPIC_LEVEL_TRIG); ent->fields.remote_irr = 0; if (!ent->fields.mask && (ioapic->irr & (1 << i))) ioapic_service(ioapic, i); } } bool kvm_ioapic_handles_vector(struct kvm *kvm, int vector) { struct kvm_ioapic *ioapic = kvm->arch.vioapic; smp_rmb(); return test_bit(vector, ioapic->handled_vectors); } void kvm_ioapic_update_eoi(struct kvm *kvm, int vector, int trigger_mode) { struct kvm_ioapic *ioapic = kvm->arch.vioapic; spin_lock(&ioapic->lock); __kvm_ioapic_update_eoi(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_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_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; #ifdef CONFIG_IA64 case IOAPIC_REG_EOI: __kvm_ioapic_update_eoi(ioapic, data, IOAPIC_LEVEL_TRIG); break; #endif default: break; } spin_unlock(&ioapic->lock); return 0; } void kvm_ioapic_reset(struct kvm_ioapic *ioapic) { int i; 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->id = 0; update_handled_vectors(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); 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; } void kvm_ioapic_destroy(struct kvm *kvm) { struct kvm_ioapic *ioapic = kvm->arch.vioapic; if (ioapic) { 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)); 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)); update_handled_vectors(ioapic); kvm_ioapic_make_eoibitmap_request(kvm); spin_unlock(&ioapic->lock); return 0; }
./CrossVul/dataset_final_sorted/CWE-20/c/good_5595_0
crossvul-cpp_data_bad_722_0
/* Copyright (C) 2007-2014 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * 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 * version 2 along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ /** * \file * * \author Victor Julien <victor@inliniac.net> * \author Anoop Saldanha <anoopsaldanha@gmail.com> */ #include "suricata-common.h" #include "debug.h" #include "decode.h" #include "threads.h" #include "threadvars.h" #include "tm-threads.h" #include "detect.h" #include "detect-engine-port.h" #include "detect-parse.h" #include "detect-engine.h" #include "detect-content.h" #include "detect-engine-mpm.h" #include "detect-engine-state.h" #include "util-print.h" #include "util-pool.h" #include "util-unittest.h" #include "util-unittest-helper.h" #include "flow.h" #include "flow-util.h" #include "flow-private.h" #include "stream-tcp-private.h" #include "stream-tcp-reassemble.h" #include "stream-tcp.h" #include "stream.h" #include "app-layer.h" #include "app-layer-protos.h" #include "app-layer-parser.h" #include "app-layer-detect-proto.h" #include "app-layer-expectation.h" #include "conf.h" #include "util-memcmp.h" #include "util-spm.h" #include "util-debug.h" #include "runmodes.h" typedef struct AppLayerProtoDetectProbingParserElement_ { AppProto alproto; /* \todo don't really need it. See if you can get rid of it */ uint16_t port; /* \todo calculate at runtime and get rid of this var */ uint32_t alproto_mask; /* \todo check if we can reduce the bottom 2 vars to uint16_t */ /* the min length of data that has to be supplied to invoke the parser */ uint32_t min_depth; /* the max length of data after which this parser won't be invoked */ uint32_t max_depth; /* the to_server probing parser function */ ProbingParserFPtr ProbingParserTs; /* the to_client probing parser function */ ProbingParserFPtr ProbingParserTc; struct AppLayerProtoDetectProbingParserElement_ *next; } AppLayerProtoDetectProbingParserElement; typedef struct AppLayerProtoDetectProbingParserPort_ { /* the port no for which probing parser(s) are invoked */ uint16_t port; uint32_t alproto_mask; /* the max depth for all the probing parsers registered for this port */ uint16_t dp_max_depth; uint16_t sp_max_depth; AppLayerProtoDetectProbingParserElement *dp; AppLayerProtoDetectProbingParserElement *sp; struct AppLayerProtoDetectProbingParserPort_ *next; } AppLayerProtoDetectProbingParserPort; typedef struct AppLayerProtoDetectProbingParser_ { uint8_t ipproto; AppLayerProtoDetectProbingParserPort *port; struct AppLayerProtoDetectProbingParser_ *next; } AppLayerProtoDetectProbingParser; typedef struct AppLayerProtoDetectPMSignature_ { AppProto alproto; SigIntId id; /* \todo Change this into a non-pointer */ DetectContentData *cd; struct AppLayerProtoDetectPMSignature_ *next; } AppLayerProtoDetectPMSignature; typedef struct AppLayerProtoDetectPMCtx_ { uint16_t max_len; uint16_t min_len; MpmCtx mpm_ctx; /** Mapping between pattern id and signature. As each signature has a * unique pattern with a unique id, we can lookup the signature by * the pattern id. */ AppLayerProtoDetectPMSignature **map; AppLayerProtoDetectPMSignature *head; /* \todo we don't need this except at setup time. Get rid of it. */ PatIntId max_pat_id; SigIntId max_sig_id; } AppLayerProtoDetectPMCtx; typedef struct AppLayerProtoDetectCtxIpproto_ { /* 0 - toserver, 1 - toclient */ AppLayerProtoDetectPMCtx ctx_pm[2]; } AppLayerProtoDetectCtxIpproto; /** * \brief The app layer protocol detection context. */ typedef struct AppLayerProtoDetectCtx_ { /* Context per ip_proto. * \todo Modify ctx_ipp to hold for only tcp and udp. The rest can be * implemented if needed. Waste of space otherwise. */ AppLayerProtoDetectCtxIpproto ctx_ipp[FLOW_PROTO_DEFAULT]; /* Global SPM thread context prototype. */ SpmGlobalThreadCtx *spm_global_thread_ctx; AppLayerProtoDetectProbingParser *ctx_pp; /* Indicates the protocols that have registered themselves * for protocol detection. This table is independent of the * ipproto. */ const char *alproto_names[ALPROTO_MAX]; } AppLayerProtoDetectCtx; /** * \brief The app layer protocol detection thread context. */ struct AppLayerProtoDetectThreadCtx_ { PrefilterRuleStore pmq; /* The value 2 is for direction(0 - toserver, 1 - toclient). */ MpmThreadCtx mpm_tctx[FLOW_PROTO_DEFAULT][2]; SpmThreadCtx *spm_thread_ctx; }; /* The global app layer proto detection context. */ static AppLayerProtoDetectCtx alpd_ctx; static void AppLayerProtoDetectPEGetIpprotos(AppProto alproto, uint8_t *ipprotos); /***** Static Internal Calls: Protocol Retrieval *****/ /** \internal * \brief Handle SPM search for Signature */ static AppProto AppLayerProtoDetectPMMatchSignature(const AppLayerProtoDetectPMSignature *s, AppLayerProtoDetectThreadCtx *tctx, uint8_t *buf, uint16_t buflen, uint8_t ipproto) { SCEnter(); AppProto proto = ALPROTO_UNKNOWN; uint8_t *found = NULL; if (s->cd->offset > buflen) { SCLogDebug("s->co->offset (%"PRIu16") > buflen (%"PRIu16")", s->cd->offset, buflen); goto end; } if (s->cd->depth > buflen) { SCLogDebug("s->co->depth (%"PRIu16") > buflen (%"PRIu16")", s->cd->depth, buflen); goto end; } uint8_t *sbuf = buf + s->cd->offset; uint16_t sbuflen = s->cd->depth - s->cd->offset; SCLogDebug("s->co->offset (%"PRIu16") s->cd->depth (%"PRIu16")", s->cd->offset, s->cd->depth); found = SpmScan(s->cd->spm_ctx, tctx->spm_thread_ctx, sbuf, sbuflen); if (found != NULL) proto = s->alproto; end: SCReturnUInt(proto); } /** \internal * \brief Run Pattern Sigs against buffer * \param pm_results[out] AppProto array of size ALPROTO_MAX */ static AppProto AppLayerProtoDetectPMGetProto(AppLayerProtoDetectThreadCtx *tctx, Flow *f, uint8_t *buf, uint16_t buflen, uint8_t direction, uint8_t ipproto, AppProto *pm_results) { SCEnter(); pm_results[0] = ALPROTO_UNKNOWN; AppLayerProtoDetectPMCtx *pm_ctx; MpmThreadCtx *mpm_tctx; uint16_t pm_matches = 0; uint8_t cnt; uint16_t searchlen; if (f->protomap >= FLOW_PROTO_DEFAULT) return ALPROTO_UNKNOWN; if (direction & STREAM_TOSERVER) { pm_ctx = &alpd_ctx.ctx_ipp[f->protomap].ctx_pm[0]; mpm_tctx = &tctx->mpm_tctx[f->protomap][0]; } else { pm_ctx = &alpd_ctx.ctx_ipp[f->protomap].ctx_pm[1]; mpm_tctx = &tctx->mpm_tctx[f->protomap][1]; } if (pm_ctx->mpm_ctx.pattern_cnt == 0) goto end; searchlen = buflen; if (searchlen > pm_ctx->max_len) searchlen = pm_ctx->max_len; uint32_t search_cnt = 0; /* do the mpm search */ search_cnt = mpm_table[pm_ctx->mpm_ctx.mpm_type].Search(&pm_ctx->mpm_ctx, mpm_tctx, &tctx->pmq, buf, searchlen); if (search_cnt == 0) goto end; /* alproto bit field */ uint8_t pm_results_bf[(ALPROTO_MAX / 8) + 1]; memset(pm_results_bf, 0, sizeof(pm_results_bf)); /* loop through unique pattern id's. Can't use search_cnt here, * as that contains all matches, tctx->pmq.pattern_id_array_cnt * contains only *unique* matches. */ for (cnt = 0; cnt < tctx->pmq.rule_id_array_cnt; cnt++) { const AppLayerProtoDetectPMSignature *s = pm_ctx->map[tctx->pmq.rule_id_array[cnt]]; while (s != NULL) { AppProto proto = AppLayerProtoDetectPMMatchSignature(s, tctx, buf, searchlen, ipproto); /* store each unique proto once */ if (proto != ALPROTO_UNKNOWN && !(pm_results_bf[proto / 8] & (1 << (proto % 8))) ) { pm_results[pm_matches++] = proto; pm_results_bf[proto / 8] |= 1 << (proto % 8); } s = s->next; } } end: PmqReset(&tctx->pmq); if (buflen >= pm_ctx->max_len) FLOW_SET_PM_DONE(f, direction); SCReturnUInt(pm_matches); } static AppLayerProtoDetectProbingParserPort *AppLayerProtoDetectGetProbingParsers(AppLayerProtoDetectProbingParser *pp, uint8_t ipproto, uint16_t port) { AppLayerProtoDetectProbingParserPort *pp_port = NULL; while (pp != NULL) { if (pp->ipproto == ipproto) break; pp = pp->next; } if (pp == NULL) goto end; pp_port = pp->port; while (pp_port != NULL) { if (pp_port->port == port || pp_port->port == 0) { break; } pp_port = pp_port->next; } end: SCReturnPtr(pp_port, "AppLayerProtoDetectProbingParserPort *"); } /** * \brief Call the probing expectation to see if there is some for this flow. * */ static AppProto AppLayerProtoDetectPEGetProto(Flow *f, uint8_t ipproto, uint8_t direction) { AppProto alproto = ALPROTO_UNKNOWN; SCLogDebug("expectation check for %p (dir %d)", f, direction); FLOW_SET_PE_DONE(f, direction); alproto = AppLayerExpectationHandle(f, direction); return alproto; } /** * \brief Call the probing parser if it exists for this flow. * * First we check the flow's dp as it's most likely to match. If that didn't * lead to a PP, we try the sp. * */ static AppProto AppLayerProtoDetectPPGetProto(Flow *f, uint8_t *buf, uint32_t buflen, uint8_t ipproto, uint8_t direction) { const AppLayerProtoDetectProbingParserPort *pp_port_dp = NULL; const AppLayerProtoDetectProbingParserPort *pp_port_sp = NULL; const AppLayerProtoDetectProbingParserElement *pe = NULL; const AppLayerProtoDetectProbingParserElement *pe1 = NULL; const AppLayerProtoDetectProbingParserElement *pe2 = NULL; AppProto alproto = ALPROTO_UNKNOWN; uint32_t *alproto_masks; uint32_t mask = 0; const uint16_t dp = f->protodetect_dp ? f->protodetect_dp : f->dp; const uint16_t sp = f->sp; if (direction & STREAM_TOSERVER) { /* first try the destination port */ pp_port_dp = AppLayerProtoDetectGetProbingParsers(alpd_ctx.ctx_pp, ipproto, dp); alproto_masks = &f->probing_parser_toserver_alproto_masks; if (pp_port_dp != NULL) { SCLogDebug("toserver - Probing parser found for destination port %"PRIu16, dp); /* found based on destination port, so use dp registration */ pe1 = pp_port_dp->dp; } else { SCLogDebug("toserver - No probing parser registered for dest port %"PRIu16, dp); } pp_port_sp = AppLayerProtoDetectGetProbingParsers(alpd_ctx.ctx_pp, ipproto, sp); if (pp_port_sp != NULL) { SCLogDebug("toserver - Probing parser found for source port %"PRIu16, sp); /* found based on source port, so use sp registration */ pe2 = pp_port_sp->sp; } else { SCLogDebug("toserver - No probing parser registered for source port %"PRIu16, sp); } } else { /* first try the destination port */ pp_port_dp = AppLayerProtoDetectGetProbingParsers(alpd_ctx.ctx_pp, ipproto, dp); alproto_masks = &f->probing_parser_toclient_alproto_masks; if (pp_port_dp != NULL) { SCLogDebug("toclient - Probing parser found for destination port %"PRIu16, dp); /* found based on destination port, so use dp registration */ pe1 = pp_port_dp->dp; } else { SCLogDebug("toclient - No probing parser registered for dest port %"PRIu16, dp); } pp_port_sp = AppLayerProtoDetectGetProbingParsers(alpd_ctx.ctx_pp, ipproto, sp); if (pp_port_sp != NULL) { SCLogDebug("toclient - Probing parser found for source port %"PRIu16, sp); pe2 = pp_port_sp->sp; } else { SCLogDebug("toclient - No probing parser registered for source port %"PRIu16, sp); } } if (pe1 == NULL && pe2 == NULL) { SCLogDebug("%s - No probing parsers found for either port", (direction & STREAM_TOSERVER) ? "toserver":"toclient"); FLOW_SET_PP_DONE(f, direction); goto end; } /* run the parser(s) */ pe = pe1; while (pe != NULL) { if ((buflen < pe->min_depth) || (alproto_masks[0] & pe->alproto_mask)) { pe = pe->next; continue; } if (direction & STREAM_TOSERVER && pe->ProbingParserTs != NULL) { alproto = pe->ProbingParserTs(f, buf, buflen); } else if (pe->ProbingParserTc != NULL) { alproto = pe->ProbingParserTc(f, buf, buflen); } if (alproto != ALPROTO_UNKNOWN && alproto != ALPROTO_FAILED) goto end; if (alproto == ALPROTO_FAILED || (pe->max_depth != 0 && buflen > pe->max_depth)) { alproto_masks[0] |= pe->alproto_mask; } pe = pe->next; } pe = pe2; while (pe != NULL) { if ((buflen < pe->min_depth) || (alproto_masks[0] & pe->alproto_mask)) { pe = pe->next; continue; } if (direction & STREAM_TOSERVER && pe->ProbingParserTs != NULL) { alproto = pe->ProbingParserTs(f, buf, buflen); } else if (pe->ProbingParserTc != NULL) { alproto = pe->ProbingParserTc(f, buf, buflen); } if (alproto != ALPROTO_UNKNOWN && alproto != ALPROTO_FAILED) goto end; if (alproto == ALPROTO_FAILED || (pe->max_depth != 0 && buflen > pe->max_depth)) { alproto_masks[0] |= pe->alproto_mask; } pe = pe->next; } /* get the mask we need for this direction */ if (pp_port_dp && pp_port_sp) mask = pp_port_dp->alproto_mask|pp_port_sp->alproto_mask; else if (pp_port_dp) mask = pp_port_dp->alproto_mask; else if (pp_port_sp) mask = pp_port_sp->alproto_mask; if (alproto_masks[0] == mask) { FLOW_SET_PP_DONE(f, direction); SCLogDebug("%s, mask is now %08x, needed %08x, so done", (direction & STREAM_TOSERVER) ? "toserver":"toclient", alproto_masks[0], mask); } else { SCLogDebug("%s, mask is now %08x, need %08x", (direction & STREAM_TOSERVER) ? "toserver":"toclient", alproto_masks[0], mask); } end: SCLogDebug("%s, mask is now %08x", (direction & STREAM_TOSERVER) ? "toserver":"toclient", alproto_masks[0]); SCReturnUInt(alproto); } /***** Static Internal Calls: PP registration *****/ static void AppLayerProtoDetectPPGetIpprotos(AppProto alproto, uint8_t *ipprotos) { SCEnter(); const AppLayerProtoDetectProbingParser *pp; const AppLayerProtoDetectProbingParserPort *pp_port; const AppLayerProtoDetectProbingParserElement *pp_pe; for (pp = alpd_ctx.ctx_pp; pp != NULL; pp = pp->next) { for (pp_port = pp->port; pp_port != NULL; pp_port = pp_port->next) { for (pp_pe = pp_port->dp; pp_pe != NULL; pp_pe = pp_pe->next) { if (alproto == pp_pe->alproto) ipprotos[pp->ipproto / 8] |= 1 << (pp->ipproto % 8); } for (pp_pe = pp_port->sp; pp_pe != NULL; pp_pe = pp_pe->next) { if (alproto == pp_pe->alproto) ipprotos[pp->ipproto / 8] |= 1 << (pp->ipproto % 8); } } } SCReturn; } static uint32_t AppLayerProtoDetectProbingParserGetMask(AppProto alproto) { SCEnter(); if (!(alproto > ALPROTO_UNKNOWN && alproto < ALPROTO_FAILED)) { SCLogError(SC_ERR_ALPARSER, "Unknown protocol detected - %"PRIu16, alproto); exit(EXIT_FAILURE); } SCReturnUInt(1 << alproto); } static AppLayerProtoDetectProbingParserElement *AppLayerProtoDetectProbingParserElementAlloc(void) { SCEnter(); AppLayerProtoDetectProbingParserElement *p = SCMalloc(sizeof(AppLayerProtoDetectProbingParserElement)); if (unlikely(p == NULL)) { exit(EXIT_FAILURE); } memset(p, 0, sizeof(AppLayerProtoDetectProbingParserElement)); SCReturnPtr(p, "AppLayerProtoDetectProbingParserElement"); } static void AppLayerProtoDetectProbingParserElementFree(AppLayerProtoDetectProbingParserElement *p) { SCEnter(); SCFree(p); SCReturn; } static AppLayerProtoDetectProbingParserPort *AppLayerProtoDetectProbingParserPortAlloc(void) { SCEnter(); AppLayerProtoDetectProbingParserPort *p = SCMalloc(sizeof(AppLayerProtoDetectProbingParserPort)); if (unlikely(p == NULL)) { exit(EXIT_FAILURE); } memset(p, 0, sizeof(AppLayerProtoDetectProbingParserPort)); SCReturnPtr(p, "AppLayerProtoDetectProbingParserPort"); } static void AppLayerProtoDetectProbingParserPortFree(AppLayerProtoDetectProbingParserPort *p) { SCEnter(); AppLayerProtoDetectProbingParserElement *e; e = p->dp; while (e != NULL) { AppLayerProtoDetectProbingParserElement *e_next = e->next; AppLayerProtoDetectProbingParserElementFree(e); e = e_next; } e = p->sp; while (e != NULL) { AppLayerProtoDetectProbingParserElement *e_next = e->next; AppLayerProtoDetectProbingParserElementFree(e); e = e_next; } SCFree(p); SCReturn; } static AppLayerProtoDetectProbingParser *AppLayerProtoDetectProbingParserAlloc(void) { SCEnter(); AppLayerProtoDetectProbingParser *p = SCMalloc(sizeof(AppLayerProtoDetectProbingParser)); if (unlikely(p == NULL)) { exit(EXIT_FAILURE); } memset(p, 0, sizeof(AppLayerProtoDetectProbingParser)); SCReturnPtr(p, "AppLayerProtoDetectProbingParser"); } static void AppLayerProtoDetectProbingParserFree(AppLayerProtoDetectProbingParser *p) { SCEnter(); AppLayerProtoDetectProbingParserPort *pt = p->port; while (pt != NULL) { AppLayerProtoDetectProbingParserPort *pt_next = pt->next; AppLayerProtoDetectProbingParserPortFree(pt); pt = pt_next; } SCFree(p); SCReturn; } static AppLayerProtoDetectProbingParserElement * AppLayerProtoDetectProbingParserElementCreate(AppProto alproto, uint16_t port, uint16_t min_depth, uint16_t max_depth) { AppLayerProtoDetectProbingParserElement *pe = AppLayerProtoDetectProbingParserElementAlloc(); pe->alproto = alproto; pe->port = port; pe->alproto_mask = AppLayerProtoDetectProbingParserGetMask(alproto); pe->min_depth = min_depth; pe->max_depth = max_depth; pe->next = NULL; if (max_depth != 0 && min_depth >= max_depth) { SCLogError(SC_ERR_ALPARSER, "Invalid arguments sent to " "register the probing parser. min_depth >= max_depth"); goto error; } if (alproto <= ALPROTO_UNKNOWN || alproto >= ALPROTO_MAX) { SCLogError(SC_ERR_ALPARSER, "Invalid arguments sent to register " "the probing parser. Invalid alproto - %d", alproto); goto error; } SCReturnPtr(pe, "AppLayerProtoDetectProbingParserElement"); error: AppLayerProtoDetectProbingParserElementFree(pe); SCReturnPtr(NULL, "AppLayerProtoDetectProbingParserElement"); } static AppLayerProtoDetectProbingParserElement * AppLayerProtoDetectProbingParserElementDuplicate(AppLayerProtoDetectProbingParserElement *pe) { SCEnter(); AppLayerProtoDetectProbingParserElement *new_pe = AppLayerProtoDetectProbingParserElementAlloc(); new_pe->alproto = pe->alproto; new_pe->port = pe->port; new_pe->alproto_mask = pe->alproto_mask; new_pe->min_depth = pe->min_depth; new_pe->max_depth = pe->max_depth; new_pe->ProbingParserTs = pe->ProbingParserTs; new_pe->ProbingParserTc = pe->ProbingParserTc; new_pe->next = NULL; SCReturnPtr(new_pe, "AppLayerProtoDetectProbingParserElement"); } #ifdef DEBUG static void AppLayerProtoDetectPrintProbingParsers(AppLayerProtoDetectProbingParser *pp) { SCEnter(); AppLayerProtoDetectProbingParserPort *pp_port = NULL; AppLayerProtoDetectProbingParserElement *pp_pe = NULL; printf("\nProtocol Detection Configuration\n"); for ( ; pp != NULL; pp = pp->next) { /* print ip protocol */ if (pp->ipproto == IPPROTO_TCP) printf("IPProto: TCP\n"); else if (pp->ipproto == IPPROTO_UDP) printf("IPProto: UDP\n"); else printf("IPProto: %"PRIu8"\n", pp->ipproto); pp_port = pp->port; for ( ; pp_port != NULL; pp_port = pp_port->next) { if (pp_port->dp != NULL) { printf(" Port: %"PRIu16 "\n", pp_port->port); printf(" Destination port: (max-depth: %"PRIu16 ", " "mask - %"PRIu32")\n", pp_port->dp_max_depth, pp_port->alproto_mask); pp_pe = pp_port->dp; for ( ; pp_pe != NULL; pp_pe = pp_pe->next) { if (pp_pe->alproto == ALPROTO_HTTP) printf(" alproto: ALPROTO_HTTP\n"); else if (pp_pe->alproto == ALPROTO_FTP) printf(" alproto: ALPROTO_FTP\n"); else if (pp_pe->alproto == ALPROTO_FTPDATA) printf(" alproto: ALPROTO_FTPDATA\n"); else if (pp_pe->alproto == ALPROTO_SMTP) printf(" alproto: ALPROTO_SMTP\n"); else if (pp_pe->alproto == ALPROTO_TLS) printf(" alproto: ALPROTO_TLS\n"); else if (pp_pe->alproto == ALPROTO_SSH) printf(" alproto: ALPROTO_SSH\n"); else if (pp_pe->alproto == ALPROTO_IMAP) printf(" alproto: ALPROTO_IMAP\n"); else if (pp_pe->alproto == ALPROTO_MSN) printf(" alproto: ALPROTO_MSN\n"); else if (pp_pe->alproto == ALPROTO_JABBER) printf(" alproto: ALPROTO_JABBER\n"); else if (pp_pe->alproto == ALPROTO_SMB) printf(" alproto: ALPROTO_SMB\n"); else if (pp_pe->alproto == ALPROTO_SMB2) printf(" alproto: ALPROTO_SMB2\n"); else if (pp_pe->alproto == ALPROTO_DCERPC) printf(" alproto: ALPROTO_DCERPC\n"); else if (pp_pe->alproto == ALPROTO_IRC) printf(" alproto: ALPROTO_IRC\n"); else if (pp_pe->alproto == ALPROTO_DNS) printf(" alproto: ALPROTO_DNS\n"); else if (pp_pe->alproto == ALPROTO_MODBUS) printf(" alproto: ALPROTO_MODBUS\n"); else if (pp_pe->alproto == ALPROTO_ENIP) printf(" alproto: ALPROTO_ENIP\n"); else if (pp_pe->alproto == ALPROTO_NFS) printf(" alproto: ALPROTO_NFS\n"); else if (pp_pe->alproto == ALPROTO_NTP) printf(" alproto: ALPROTO_NTP\n"); else if (pp_pe->alproto == ALPROTO_TFTP) printf(" alproto: ALPROTO_TFTP\n"); else if (pp_pe->alproto == ALPROTO_IKEV2) printf(" alproto: ALPROTO_IKEV2\n"); else if (pp_pe->alproto == ALPROTO_KRB5) printf(" alproto: ALPROTO_KRB5\n"); else if (pp_pe->alproto == ALPROTO_DHCP) printf(" alproto: ALPROTO_DHCP\n"); else if (pp_pe->alproto == ALPROTO_TEMPLATE_RUST) printf(" alproto: ALPROTO_TEMPLATE_RUST\n"); else if (pp_pe->alproto == ALPROTO_TEMPLATE) printf(" alproto: ALPROTO_TEMPLATE\n"); else if (pp_pe->alproto == ALPROTO_DNP3) printf(" alproto: ALPROTO_DNP3\n"); else printf("impossible\n"); printf(" port: %"PRIu16 "\n", pp_pe->port); printf(" mask: %"PRIu32 "\n", pp_pe->alproto_mask); printf(" min_depth: %"PRIu32 "\n", pp_pe->min_depth); printf(" max_depth: %"PRIu32 "\n", pp_pe->max_depth); printf("\n"); } } if (pp_port->sp == NULL) { continue; } printf(" Source port: (max-depth: %"PRIu16 ", " "mask - %"PRIu32")\n", pp_port->sp_max_depth, pp_port->alproto_mask); pp_pe = pp_port->sp; for ( ; pp_pe != NULL; pp_pe = pp_pe->next) { if (pp_pe->alproto == ALPROTO_HTTP) printf(" alproto: ALPROTO_HTTP\n"); else if (pp_pe->alproto == ALPROTO_FTP) printf(" alproto: ALPROTO_FTP\n"); else if (pp_pe->alproto == ALPROTO_FTPDATA) printf(" alproto: ALPROTO_FTPDATA\n"); else if (pp_pe->alproto == ALPROTO_SMTP) printf(" alproto: ALPROTO_SMTP\n"); else if (pp_pe->alproto == ALPROTO_TLS) printf(" alproto: ALPROTO_TLS\n"); else if (pp_pe->alproto == ALPROTO_SSH) printf(" alproto: ALPROTO_SSH\n"); else if (pp_pe->alproto == ALPROTO_IMAP) printf(" alproto: ALPROTO_IMAP\n"); else if (pp_pe->alproto == ALPROTO_MSN) printf(" alproto: ALPROTO_MSN\n"); else if (pp_pe->alproto == ALPROTO_JABBER) printf(" alproto: ALPROTO_JABBER\n"); else if (pp_pe->alproto == ALPROTO_SMB) printf(" alproto: ALPROTO_SMB\n"); else if (pp_pe->alproto == ALPROTO_SMB2) printf(" alproto: ALPROTO_SMB2\n"); else if (pp_pe->alproto == ALPROTO_DCERPC) printf(" alproto: ALPROTO_DCERPC\n"); else if (pp_pe->alproto == ALPROTO_IRC) printf(" alproto: ALPROTO_IRC\n"); else if (pp_pe->alproto == ALPROTO_DNS) printf(" alproto: ALPROTO_DNS\n"); else if (pp_pe->alproto == ALPROTO_MODBUS) printf(" alproto: ALPROTO_MODBUS\n"); else if (pp_pe->alproto == ALPROTO_ENIP) printf(" alproto: ALPROTO_ENIP\n"); else if (pp_pe->alproto == ALPROTO_NFS) printf(" alproto: ALPROTO_NFS\n"); else if (pp_pe->alproto == ALPROTO_NTP) printf(" alproto: ALPROTO_NTP\n"); else if (pp_pe->alproto == ALPROTO_TFTP) printf(" alproto: ALPROTO_TFTP\n"); else if (pp_pe->alproto == ALPROTO_IKEV2) printf(" alproto: ALPROTO_IKEV2\n"); else if (pp_pe->alproto == ALPROTO_KRB5) printf(" alproto: ALPROTO_KRB5\n"); else if (pp_pe->alproto == ALPROTO_DHCP) printf(" alproto: ALPROTO_DHCP\n"); else if (pp_pe->alproto == ALPROTO_TEMPLATE_RUST) printf(" alproto: ALPROTO_TEMPLATE_RUST\n"); else if (pp_pe->alproto == ALPROTO_TEMPLATE) printf(" alproto: ALPROTO_TEMPLATE\n"); else if (pp_pe->alproto == ALPROTO_DNP3) printf(" alproto: ALPROTO_DNP3\n"); else printf("impossible\n"); printf(" port: %"PRIu16 "\n", pp_pe->port); printf(" mask: %"PRIu32 "\n", pp_pe->alproto_mask); printf(" min_depth: %"PRIu32 "\n", pp_pe->min_depth); printf(" max_depth: %"PRIu32 "\n", pp_pe->max_depth); printf("\n"); } } } SCReturn; } #endif static void AppLayerProtoDetectProbingParserElementAppend(AppLayerProtoDetectProbingParserElement **head_pe, AppLayerProtoDetectProbingParserElement *new_pe) { SCEnter(); if (*head_pe == NULL) { *head_pe = new_pe; goto end; } if ((*head_pe)->port == 0) { if (new_pe->port != 0) { new_pe->next = *head_pe; *head_pe = new_pe; } else { AppLayerProtoDetectProbingParserElement *temp_pe = *head_pe; while (temp_pe->next != NULL) temp_pe = temp_pe->next; temp_pe->next = new_pe; } } else { AppLayerProtoDetectProbingParserElement *temp_pe = *head_pe; if (new_pe->port == 0) { while (temp_pe->next != NULL) temp_pe = temp_pe->next; temp_pe->next = new_pe; } else { while (temp_pe->next != NULL && temp_pe->next->port != 0) temp_pe = temp_pe->next; new_pe->next = temp_pe->next; temp_pe->next = new_pe; } } end: SCReturn; } static void AppLayerProtoDetectProbingParserAppend(AppLayerProtoDetectProbingParser **head_pp, AppLayerProtoDetectProbingParser *new_pp) { SCEnter(); if (*head_pp == NULL) { *head_pp = new_pp; goto end; } AppLayerProtoDetectProbingParser *temp_pp = *head_pp; while (temp_pp->next != NULL) temp_pp = temp_pp->next; temp_pp->next = new_pp; end: SCReturn; } static void AppLayerProtoDetectProbingParserPortAppend(AppLayerProtoDetectProbingParserPort **head_port, AppLayerProtoDetectProbingParserPort *new_port) { SCEnter(); if (*head_port == NULL) { *head_port = new_port; goto end; } if ((*head_port)->port == 0) { new_port->next = *head_port; *head_port = new_port; } else { AppLayerProtoDetectProbingParserPort *temp_port = *head_port; while (temp_port->next != NULL && temp_port->next->port != 0) { temp_port = temp_port->next; } new_port->next = temp_port->next; temp_port->next = new_port; } end: SCReturn; } static void AppLayerProtoDetectInsertNewProbingParser(AppLayerProtoDetectProbingParser **pp, uint8_t ipproto, uint16_t port, AppProto alproto, uint16_t min_depth, uint16_t max_depth, uint8_t direction, ProbingParserFPtr ProbingParser1, ProbingParserFPtr ProbingParser2) { SCEnter(); /* get the top level ipproto pp */ AppLayerProtoDetectProbingParser *curr_pp = *pp; while (curr_pp != NULL) { if (curr_pp->ipproto == ipproto) break; curr_pp = curr_pp->next; } if (curr_pp == NULL) { AppLayerProtoDetectProbingParser *new_pp = AppLayerProtoDetectProbingParserAlloc(); new_pp->ipproto = ipproto; AppLayerProtoDetectProbingParserAppend(pp, new_pp); curr_pp = new_pp; } /* get the top level port pp */ AppLayerProtoDetectProbingParserPort *curr_port = curr_pp->port; while (curr_port != NULL) { if (curr_port->port == port) break; curr_port = curr_port->next; } if (curr_port == NULL) { AppLayerProtoDetectProbingParserPort *new_port = AppLayerProtoDetectProbingParserPortAlloc(); new_port->port = port; AppLayerProtoDetectProbingParserPortAppend(&curr_pp->port, new_port); curr_port = new_port; if (direction & STREAM_TOSERVER) { curr_port->dp_max_depth = max_depth; } else { curr_port->sp_max_depth = max_depth; } AppLayerProtoDetectProbingParserPort *zero_port; zero_port = curr_pp->port; while (zero_port != NULL && zero_port->port != 0) { zero_port = zero_port->next; } if (zero_port != NULL) { AppLayerProtoDetectProbingParserElement *zero_pe; zero_pe = zero_port->dp; for ( ; zero_pe != NULL; zero_pe = zero_pe->next) { if (curr_port->dp == NULL) curr_port->dp_max_depth = zero_pe->max_depth; if (zero_pe->max_depth == 0) curr_port->dp_max_depth = zero_pe->max_depth; if (curr_port->dp_max_depth != 0 && curr_port->dp_max_depth < zero_pe->max_depth) { curr_port->dp_max_depth = zero_pe->max_depth; } AppLayerProtoDetectProbingParserElement *dup_pe = AppLayerProtoDetectProbingParserElementDuplicate(zero_pe); AppLayerProtoDetectProbingParserElementAppend(&curr_port->dp, dup_pe); curr_port->alproto_mask |= dup_pe->alproto_mask; } zero_pe = zero_port->sp; for ( ; zero_pe != NULL; zero_pe = zero_pe->next) { if (curr_port->sp == NULL) curr_port->sp_max_depth = zero_pe->max_depth; if (zero_pe->max_depth == 0) curr_port->sp_max_depth = zero_pe->max_depth; if (curr_port->sp_max_depth != 0 && curr_port->sp_max_depth < zero_pe->max_depth) { curr_port->sp_max_depth = zero_pe->max_depth; } AppLayerProtoDetectProbingParserElement *dup_pe = AppLayerProtoDetectProbingParserElementDuplicate(zero_pe); AppLayerProtoDetectProbingParserElementAppend(&curr_port->sp, dup_pe); curr_port->alproto_mask |= dup_pe->alproto_mask; } } /* if (zero_port != NULL) */ } /* if (curr_port == NULL) */ /* insert the pe_pp */ AppLayerProtoDetectProbingParserElement *curr_pe; if (direction & STREAM_TOSERVER) curr_pe = curr_port->dp; else curr_pe = curr_port->sp; while (curr_pe != NULL) { if (curr_pe->alproto == alproto) { SCLogError(SC_ERR_ALPARSER, "Duplicate pp registered - " "ipproto - %"PRIu8" Port - %"PRIu16" " "App Protocol - NULL, App Protocol(ID) - " "%"PRIu16" min_depth - %"PRIu16" " "max_dept - %"PRIu16".", ipproto, port, alproto, min_depth, max_depth); goto error; } curr_pe = curr_pe->next; } /* Get a new parser element */ AppLayerProtoDetectProbingParserElement *new_pe = AppLayerProtoDetectProbingParserElementCreate(alproto, curr_port->port, min_depth, max_depth); if (new_pe == NULL) goto error; curr_pe = new_pe; AppLayerProtoDetectProbingParserElement **head_pe; if (direction & STREAM_TOSERVER) { curr_pe->ProbingParserTs = ProbingParser1; curr_pe->ProbingParserTc = ProbingParser2; if (curr_port->dp == NULL) curr_port->dp_max_depth = new_pe->max_depth; if (new_pe->max_depth == 0) curr_port->dp_max_depth = new_pe->max_depth; if (curr_port->dp_max_depth != 0 && curr_port->dp_max_depth < new_pe->max_depth) { curr_port->dp_max_depth = new_pe->max_depth; } curr_port->alproto_mask |= new_pe->alproto_mask; head_pe = &curr_port->dp; } else { curr_pe->ProbingParserTs = ProbingParser2; curr_pe->ProbingParserTc = ProbingParser1; if (curr_port->sp == NULL) curr_port->sp_max_depth = new_pe->max_depth; if (new_pe->max_depth == 0) curr_port->sp_max_depth = new_pe->max_depth; if (curr_port->sp_max_depth != 0 && curr_port->sp_max_depth < new_pe->max_depth) { curr_port->sp_max_depth = new_pe->max_depth; } curr_port->alproto_mask |= new_pe->alproto_mask; head_pe = &curr_port->sp; } AppLayerProtoDetectProbingParserElementAppend(head_pe, new_pe); if (curr_port->port == 0) { AppLayerProtoDetectProbingParserPort *temp_port = curr_pp->port; while (temp_port != NULL && temp_port->port != 0) { if (direction & STREAM_TOSERVER) { if (temp_port->dp == NULL) temp_port->dp_max_depth = curr_pe->max_depth; if (curr_pe->max_depth == 0) temp_port->dp_max_depth = curr_pe->max_depth; if (temp_port->dp_max_depth != 0 && temp_port->dp_max_depth < curr_pe->max_depth) { temp_port->dp_max_depth = curr_pe->max_depth; } AppLayerProtoDetectProbingParserElementAppend(&temp_port->dp, AppLayerProtoDetectProbingParserElementDuplicate(curr_pe)); temp_port->alproto_mask |= curr_pe->alproto_mask; } else { if (temp_port->sp == NULL) temp_port->sp_max_depth = curr_pe->max_depth; if (curr_pe->max_depth == 0) temp_port->sp_max_depth = curr_pe->max_depth; if (temp_port->sp_max_depth != 0 && temp_port->sp_max_depth < curr_pe->max_depth) { temp_port->sp_max_depth = curr_pe->max_depth; } AppLayerProtoDetectProbingParserElementAppend(&temp_port->sp, AppLayerProtoDetectProbingParserElementDuplicate(curr_pe)); temp_port->alproto_mask |= curr_pe->alproto_mask; } temp_port = temp_port->next; } /* while */ } /* if */ error: SCReturn; } /***** Static Internal Calls: PM registration *****/ static void AppLayerProtoDetectPMGetIpprotos(AppProto alproto, uint8_t *ipprotos) { SCEnter(); const AppLayerProtoDetectPMSignature *s = NULL; int i, j; uint8_t ipproto; for (i = 0; i < FLOW_PROTO_DEFAULT; i++) { ipproto = FlowGetReverseProtoMapping(i); for (j = 0; j < 2; j++) { AppLayerProtoDetectPMCtx *pm_ctx = &alpd_ctx.ctx_ipp[i].ctx_pm[j]; SigIntId x; for (x = 0; x < pm_ctx->max_sig_id;x++) { s = pm_ctx->map[x]; if (s->alproto == alproto) ipprotos[ipproto / 8] |= 1 << (ipproto % 8); } } } SCReturn; } static int AppLayerProtoDetectPMSetContentIDs(AppLayerProtoDetectPMCtx *ctx) { SCEnter(); typedef struct TempContainer_ { PatIntId id; uint16_t content_len; uint8_t *content; } TempContainer; AppLayerProtoDetectPMSignature *s = NULL; uint32_t struct_total_size = 0; uint32_t content_total_size = 0; /* array hash buffer */ uint8_t *ahb = NULL; uint8_t *content = NULL; uint8_t content_len = 0; PatIntId max_id = 0; TempContainer *struct_offset = NULL; uint8_t *content_offset = NULL; int ret = 0; if (ctx->head == NULL) goto end; for (s = ctx->head; s != NULL; s = s->next) { struct_total_size += sizeof(TempContainer); content_total_size += s->cd->content_len; ctx->max_sig_id++; } ahb = SCMalloc(sizeof(uint8_t) * (struct_total_size + content_total_size)); if (unlikely(ahb == NULL)) goto error; struct_offset = (TempContainer *)ahb; content_offset = ahb + struct_total_size; for (s = ctx->head; s != NULL; s = s->next) { TempContainer *tcdup = (TempContainer *)ahb; content = s->cd->content; content_len = s->cd->content_len; for (; tcdup != struct_offset; tcdup++) { if (tcdup->content_len != content_len || SCMemcmp(tcdup->content, content, tcdup->content_len) != 0) { continue; } break; } if (tcdup != struct_offset) { s->cd->id = tcdup->id; continue; } struct_offset->content_len = content_len; struct_offset->content = content_offset; content_offset += content_len; memcpy(struct_offset->content, content, content_len); struct_offset->id = max_id++; s->cd->id = struct_offset->id; struct_offset++; } ctx->max_pat_id = max_id; goto end; error: ret = -1; end: if (ahb != NULL) SCFree(ahb); SCReturnInt(ret); } static int AppLayerProtoDetectPMMapSignatures(AppLayerProtoDetectPMCtx *ctx) { SCEnter(); int ret = 0; AppLayerProtoDetectPMSignature *s, *next_s; int mpm_ret; SigIntId id = 0; ctx->map = SCMalloc(ctx->max_sig_id * sizeof(AppLayerProtoDetectPMSignature *)); if (ctx->map == NULL) goto error; memset(ctx->map, 0, ctx->max_sig_id * sizeof(AppLayerProtoDetectPMSignature *)); /* add an array indexed by rule id to look up the sig */ for (s = ctx->head; s != NULL; ) { next_s = s->next; s->id = id++; SCLogDebug("s->id %u", s->id); if (s->cd->flags & DETECT_CONTENT_NOCASE) { mpm_ret = MpmAddPatternCI(&ctx->mpm_ctx, s->cd->content, s->cd->content_len, 0, 0, s->cd->id, s->id, 0); if (mpm_ret < 0) goto error; } else { mpm_ret = MpmAddPatternCS(&ctx->mpm_ctx, s->cd->content, s->cd->content_len, 0, 0, s->cd->id, s->id, 0); if (mpm_ret < 0) goto error; } ctx->map[s->id] = s; s->next = NULL; s = next_s; } ctx->head = NULL; goto end; error: ret = -1; end: SCReturnInt(ret); } static int AppLayerProtoDetectPMPrepareMpm(AppLayerProtoDetectPMCtx *ctx) { SCEnter(); int ret = 0; MpmCtx *mpm_ctx = &ctx->mpm_ctx; if (mpm_table[mpm_ctx->mpm_type].Prepare(mpm_ctx) < 0) goto error; goto end; error: ret = -1; end: SCReturnInt(ret); } static void AppLayerProtoDetectPMFreeSignature(AppLayerProtoDetectPMSignature *sig) { SCEnter(); if (sig == NULL) SCReturn; if (sig->cd) DetectContentFree(sig->cd); SCFree(sig); SCReturn; } static int AppLayerProtoDetectPMAddSignature(AppLayerProtoDetectPMCtx *ctx, DetectContentData *cd, AppProto alproto) { SCEnter(); int ret = 0; AppLayerProtoDetectPMSignature *s = SCMalloc(sizeof(*s)); if (unlikely(s == NULL)) goto error; memset(s, 0, sizeof(*s)); s->alproto = alproto; s->cd = cd; /* prepend to the list */ s->next = ctx->head; ctx->head = s; goto end; error: ret = -1; end: SCReturnInt(ret); } static int AppLayerProtoDetectPMRegisterPattern(uint8_t ipproto, AppProto alproto, const char *pattern, uint16_t depth, uint16_t offset, uint8_t direction, uint8_t is_cs) { SCEnter(); AppLayerProtoDetectCtxIpproto *ctx_ipp = &alpd_ctx.ctx_ipp[FlowGetProtoMapping(ipproto)]; AppLayerProtoDetectPMCtx *ctx_pm = NULL; DetectContentData *cd; int ret = 0; cd = DetectContentParseEncloseQuotes(alpd_ctx.spm_global_thread_ctx, pattern); if (cd == NULL) goto error; cd->depth = depth; cd->offset = offset; if (!is_cs) { /* Rebuild as nocase */ SpmDestroyCtx(cd->spm_ctx); cd->spm_ctx = SpmInitCtx(cd->content, cd->content_len, 1, alpd_ctx.spm_global_thread_ctx); if (cd->spm_ctx == NULL) { goto error; } cd->flags |= DETECT_CONTENT_NOCASE; } if (depth < cd->content_len) goto error; if (direction & STREAM_TOSERVER) ctx_pm = (AppLayerProtoDetectPMCtx *)&ctx_ipp->ctx_pm[0]; else ctx_pm = (AppLayerProtoDetectPMCtx *)&ctx_ipp->ctx_pm[1]; if (depth > ctx_pm->max_len) ctx_pm->max_len = depth; if (depth < ctx_pm->min_len) ctx_pm->min_len = depth; /* Finally turn it into a signature and add to the ctx. */ AppLayerProtoDetectPMAddSignature(ctx_pm, cd, alproto); goto end; error: ret = -1; end: SCReturnInt(ret); } /***** Protocol Retrieval *****/ AppProto AppLayerProtoDetectGetProto(AppLayerProtoDetectThreadCtx *tctx, Flow *f, uint8_t *buf, uint32_t buflen, uint8_t ipproto, uint8_t direction) { SCEnter(); SCLogDebug("buflen %u for %s direction", buflen, (direction & STREAM_TOSERVER) ? "toserver" : "toclient"); AppProto alproto = ALPROTO_UNKNOWN; if (!FLOW_IS_PM_DONE(f, direction)) { AppProto pm_results[ALPROTO_MAX]; uint16_t pm_matches = AppLayerProtoDetectPMGetProto(tctx, f, buf, buflen, direction, ipproto, pm_results); if (pm_matches > 0) { alproto = pm_results[0]; goto end; } } if (!FLOW_IS_PP_DONE(f, direction)) { alproto = AppLayerProtoDetectPPGetProto(f, buf, buflen, ipproto, direction); if (alproto != ALPROTO_UNKNOWN) goto end; } /* Look if flow can be found in expectation list */ if (!FLOW_IS_PE_DONE(f, direction)) { alproto = AppLayerProtoDetectPEGetProto(f, ipproto, direction); } end: SCReturnUInt(alproto); } static void AppLayerProtoDetectFreeProbingParsers(AppLayerProtoDetectProbingParser *pp) { SCEnter(); AppLayerProtoDetectProbingParser *tmp_pp = NULL; if (pp == NULL) goto end; while (pp != NULL) { tmp_pp = pp->next; AppLayerProtoDetectProbingParserFree(pp); pp = tmp_pp; } end: SCReturn; } /***** State Preparation *****/ int AppLayerProtoDetectPrepareState(void) { SCEnter(); AppLayerProtoDetectPMCtx *ctx_pm; int i, j; int ret = 0; for (i = 0; i < FLOW_PROTO_DEFAULT; i++) { for (j = 0; j < 2; j++) { ctx_pm = &alpd_ctx.ctx_ipp[i].ctx_pm[j]; if (AppLayerProtoDetectPMSetContentIDs(ctx_pm) < 0) goto error; if (ctx_pm->max_sig_id == 0) continue; if (AppLayerProtoDetectPMMapSignatures(ctx_pm) < 0) goto error; if (AppLayerProtoDetectPMPrepareMpm(ctx_pm) < 0) goto error; } } #ifdef DEBUG if (SCLogDebugEnabled()) { AppLayerProtoDetectPrintProbingParsers(alpd_ctx.ctx_pp); } #endif goto end; error: ret = -1; end: SCReturnInt(ret); } /***** PP registration *****/ /** \brief register parser at a port * * \param direction STREAM_TOSERVER or STREAM_TOCLIENT for dp or sp */ void AppLayerProtoDetectPPRegister(uint8_t ipproto, const char *portstr, AppProto alproto, uint16_t min_depth, uint16_t max_depth, uint8_t direction, ProbingParserFPtr ProbingParser1, ProbingParserFPtr ProbingParser2) { SCEnter(); DetectPort *head = NULL; DetectPortParse(NULL,&head, portstr); DetectPort *temp_dp = head; while (temp_dp != NULL) { uint32_t port = temp_dp->port; if (port == 0 && temp_dp->port2 != 0) port++; for ( ; port <= temp_dp->port2; port++) { AppLayerProtoDetectInsertNewProbingParser(&alpd_ctx.ctx_pp, ipproto, port, alproto, min_depth, max_depth, direction, ProbingParser1, ProbingParser2); } temp_dp = temp_dp->next; } DetectPortCleanupList(NULL,head); SCReturn; } int AppLayerProtoDetectPPParseConfPorts(const char *ipproto_name, uint8_t ipproto, const char *alproto_name, AppProto alproto, uint16_t min_depth, uint16_t max_depth, ProbingParserFPtr ProbingParserTs, ProbingParserFPtr ProbingParserTc) { SCEnter(); char param[100]; int r; ConfNode *node; ConfNode *port_node = NULL; int config = 0; r = snprintf(param, sizeof(param), "%s%s%s", "app-layer.protocols.", alproto_name, ".detection-ports"); if (r < 0) { SCLogError(SC_ERR_FATAL, "snprintf failure."); exit(EXIT_FAILURE); } else if (r > (int)sizeof(param)) { SCLogError(SC_ERR_FATAL, "buffer not big enough to write param."); exit(EXIT_FAILURE); } node = ConfGetNode(param); if (node == NULL) { SCLogDebug("Entry for %s not found.", param); r = snprintf(param, sizeof(param), "%s%s%s%s%s", "app-layer.protocols.", alproto_name, ".", ipproto_name, ".detection-ports"); if (r < 0) { SCLogError(SC_ERR_FATAL, "snprintf failure."); exit(EXIT_FAILURE); } else if (r > (int)sizeof(param)) { SCLogError(SC_ERR_FATAL, "buffer not big enough to write param."); exit(EXIT_FAILURE); } node = ConfGetNode(param); if (node == NULL) goto end; } /* detect by destination port of the flow (e.g. port 53 for DNS) */ port_node = ConfNodeLookupChild(node, "dp"); if (port_node == NULL) port_node = ConfNodeLookupChild(node, "toserver"); if (port_node != NULL && port_node->val != NULL) { AppLayerProtoDetectPPRegister(ipproto, port_node->val, alproto, min_depth, max_depth, STREAM_TOSERVER, /* to indicate dp */ ProbingParserTs, ProbingParserTc); } /* detect by source port of flow */ port_node = ConfNodeLookupChild(node, "sp"); if (port_node == NULL) port_node = ConfNodeLookupChild(node, "toclient"); if (port_node != NULL && port_node->val != NULL) { AppLayerProtoDetectPPRegister(ipproto, port_node->val, alproto, min_depth, max_depth, STREAM_TOCLIENT, /* to indicate sp */ ProbingParserTc, ProbingParserTs); } config = 1; end: SCReturnInt(config); } /***** PM registration *****/ int AppLayerProtoDetectPMRegisterPatternCS(uint8_t ipproto, AppProto alproto, const char *pattern, uint16_t depth, uint16_t offset, uint8_t direction) { SCEnter(); int r = 0; r = AppLayerProtoDetectPMRegisterPattern(ipproto, alproto, pattern, depth, offset, direction, 1 /* case-sensitive */); SCReturnInt(r); } int AppLayerProtoDetectPMRegisterPatternCI(uint8_t ipproto, AppProto alproto, const char *pattern, uint16_t depth, uint16_t offset, uint8_t direction) { SCEnter(); int r = 0; r = AppLayerProtoDetectPMRegisterPattern(ipproto, alproto, pattern, depth, offset, direction, 0 /* !case-sensitive */); SCReturnInt(r); } /***** Setup/General Registration *****/ int AppLayerProtoDetectSetup(void) { SCEnter(); int i, j; memset(&alpd_ctx, 0, sizeof(alpd_ctx)); uint16_t spm_matcher = SinglePatternMatchDefaultMatcher(); uint16_t mpm_matcher = PatternMatchDefaultMatcher(); alpd_ctx.spm_global_thread_ctx = SpmInitGlobalThreadCtx(spm_matcher); if (alpd_ctx.spm_global_thread_ctx == NULL) { SCLogError(SC_ERR_FATAL, "Unable to alloc SpmGlobalThreadCtx."); exit(EXIT_FAILURE); } for (i = 0; i < FLOW_PROTO_DEFAULT; i++) { for (j = 0; j < 2; j++) { MpmInitCtx(&alpd_ctx.ctx_ipp[i].ctx_pm[j].mpm_ctx, mpm_matcher); } } AppLayerExpectationSetup(); SCReturnInt(0); } /** * \todo incomplete. Need more work. */ int AppLayerProtoDetectDeSetup(void) { SCEnter(); int ipproto_map = 0; int dir = 0; PatIntId id = 0; AppLayerProtoDetectPMCtx *pm_ctx = NULL; AppLayerProtoDetectPMSignature *sig = NULL; for (ipproto_map = 0; ipproto_map < FLOW_PROTO_DEFAULT; ipproto_map++) { for (dir = 0; dir < 2; dir++) { pm_ctx = &alpd_ctx.ctx_ipp[ipproto_map].ctx_pm[dir]; mpm_table[pm_ctx->mpm_ctx.mpm_type].DestroyCtx(&pm_ctx->mpm_ctx); for (id = 0; id < pm_ctx->max_sig_id; id++) { sig = pm_ctx->map[id]; AppLayerProtoDetectPMFreeSignature(sig); } } } SpmDestroyGlobalThreadCtx(alpd_ctx.spm_global_thread_ctx); AppLayerProtoDetectFreeProbingParsers(alpd_ctx.ctx_pp); SCReturnInt(0); } void AppLayerProtoDetectRegisterProtocol(AppProto alproto, const char *alproto_name) { SCEnter(); if (alpd_ctx.alproto_names[alproto] == NULL) alpd_ctx.alproto_names[alproto] = alproto_name; SCReturn; } /** \brief request applayer to wrap up this protocol and rerun protocol * detection. * * When this is called, the old session is reset unconditionally. A * 'detect/log' flush packet is generated for both direction before * the reset, so allow for final detection and logging. * * \param f flow to act on * \param dp destination port to use in protocol detection. Set to 443 * for start tls, set to the HTTP uri port for CONNECT and * set to 0 to not use it. * \param expect_proto expected protocol. AppLayer event will be set if * detected protocol differs from this. */ void AppLayerRequestProtocolChange(Flow *f, uint16_t dp, AppProto expect_proto) { FlowSetChangeProtoFlag(f); f->protodetect_dp = dp; f->alproto_expect = expect_proto; } /** \brief request applayer to wrap up this protocol and rerun protocol * detection with expectation of TLS. Used by STARTTLS. * * Sets detection port to 443 to make port based TLS detection work for * SMTP, FTP etc as well. * * \param f flow to act on */ void AppLayerRequestProtocolTLSUpgrade(Flow *f) { AppLayerRequestProtocolChange(f, 443, ALPROTO_TLS); } void AppLayerProtoDetectReset(Flow *f) { FlowUnsetChangeProtoFlag(f); FLOW_RESET_PM_DONE(f, STREAM_TOSERVER); FLOW_RESET_PM_DONE(f, STREAM_TOCLIENT); FLOW_RESET_PP_DONE(f, STREAM_TOSERVER); FLOW_RESET_PP_DONE(f, STREAM_TOCLIENT); FLOW_RESET_PE_DONE(f, STREAM_TOSERVER); FLOW_RESET_PE_DONE(f, STREAM_TOCLIENT); f->probing_parser_toserver_alproto_masks = 0; f->probing_parser_toclient_alproto_masks = 0; AppLayerParserStateCleanup(f, f->alstate, f->alparser); f->alstate = NULL; f->alparser = NULL; f->alproto = ALPROTO_UNKNOWN; f->alproto_ts = ALPROTO_UNKNOWN; f->alproto_tc = ALPROTO_UNKNOWN; } int AppLayerProtoDetectConfProtoDetectionEnabled(const char *ipproto, const char *alproto) { SCEnter(); BUG_ON(ipproto == NULL || alproto == NULL); int enabled = 1; char param[100]; ConfNode *node; int r; #ifdef AFLFUZZ_APPLAYER goto enabled; #endif if (RunmodeIsUnittests()) goto enabled; r = snprintf(param, sizeof(param), "%s%s%s", "app-layer.protocols.", alproto, ".enabled"); if (r < 0) { SCLogError(SC_ERR_FATAL, "snprintf failure."); exit(EXIT_FAILURE); } else if (r > (int)sizeof(param)) { SCLogError(SC_ERR_FATAL, "buffer not big enough to write param."); exit(EXIT_FAILURE); } node = ConfGetNode(param); if (node == NULL) { SCLogDebug("Entry for %s not found.", param); r = snprintf(param, sizeof(param), "%s%s%s%s%s", "app-layer.protocols.", alproto, ".", ipproto, ".enabled"); if (r < 0) { SCLogError(SC_ERR_FATAL, "snprintf failure."); exit(EXIT_FAILURE); } else if (r > (int)sizeof(param)) { SCLogError(SC_ERR_FATAL, "buffer not big enough to write param."); exit(EXIT_FAILURE); } node = ConfGetNode(param); if (node == NULL) { SCLogDebug("Entry for %s not found.", param); goto enabled; } } if (node->val) { if (ConfValIsTrue(node->val)) { goto enabled; } else if (ConfValIsFalse(node->val)) { goto disabled; } else if (strcasecmp(node->val, "detection-only") == 0) { goto enabled; } } /* Invalid or null value. */ SCLogError(SC_ERR_FATAL, "Invalid value found for %s.", param); exit(EXIT_FAILURE); disabled: enabled = 0; enabled: SCReturnInt(enabled); } AppLayerProtoDetectThreadCtx *AppLayerProtoDetectGetCtxThread(void) { SCEnter(); AppLayerProtoDetectThreadCtx *alpd_tctx = NULL; MpmCtx *mpm_ctx; MpmThreadCtx *mpm_tctx; int i, j; PatIntId max_pat_id = 0; for (i = 0; i < FLOW_PROTO_DEFAULT; i++) { for (j = 0; j < 2; j++) { if (max_pat_id == 0) { max_pat_id = alpd_ctx.ctx_ipp[i].ctx_pm[j].max_pat_id; } else if (alpd_ctx.ctx_ipp[i].ctx_pm[j].max_pat_id && max_pat_id < alpd_ctx.ctx_ipp[i].ctx_pm[j].max_pat_id) { max_pat_id = alpd_ctx.ctx_ipp[i].ctx_pm[j].max_pat_id; } } } alpd_tctx = SCMalloc(sizeof(*alpd_tctx)); if (alpd_tctx == NULL) goto error; memset(alpd_tctx, 0, sizeof(*alpd_tctx)); /* Get the max pat id for all the mpm ctxs. */ if (PmqSetup(&alpd_tctx->pmq) < 0) goto error; for (i = 0; i < FLOW_PROTO_DEFAULT; i++) { for (j = 0; j < 2; j++) { mpm_ctx = &alpd_ctx.ctx_ipp[i].ctx_pm[j].mpm_ctx; mpm_tctx = &alpd_tctx->mpm_tctx[i][j]; mpm_table[mpm_ctx->mpm_type].InitThreadCtx(mpm_ctx, mpm_tctx); } } alpd_tctx->spm_thread_ctx = SpmMakeThreadCtx(alpd_ctx.spm_global_thread_ctx); if (alpd_tctx->spm_thread_ctx == NULL) { goto error; } goto end; error: if (alpd_tctx != NULL) AppLayerProtoDetectDestroyCtxThread(alpd_tctx); alpd_tctx = NULL; end: SCReturnPtr(alpd_tctx, "AppLayerProtoDetectThreadCtx"); } void AppLayerProtoDetectDestroyCtxThread(AppLayerProtoDetectThreadCtx *alpd_tctx) { SCEnter(); MpmCtx *mpm_ctx; MpmThreadCtx *mpm_tctx; int ipproto_map, dir; for (ipproto_map = 0; ipproto_map < FLOW_PROTO_DEFAULT; ipproto_map++) { for (dir = 0; dir < 2; dir++) { mpm_ctx = &alpd_ctx.ctx_ipp[ipproto_map].ctx_pm[dir].mpm_ctx; mpm_tctx = &alpd_tctx->mpm_tctx[ipproto_map][dir]; mpm_table[mpm_ctx->mpm_type].DestroyThreadCtx(mpm_ctx, mpm_tctx); } } PmqFree(&alpd_tctx->pmq); if (alpd_tctx->spm_thread_ctx != NULL) { SpmDestroyThreadCtx(alpd_tctx->spm_thread_ctx); } SCFree(alpd_tctx); SCReturn; } /***** Utility *****/ void AppLayerProtoDetectSupportedIpprotos(AppProto alproto, uint8_t *ipprotos) { SCEnter(); AppLayerProtoDetectPMGetIpprotos(alproto, ipprotos); AppLayerProtoDetectPPGetIpprotos(alproto, ipprotos); AppLayerProtoDetectPEGetIpprotos(alproto, ipprotos); SCReturn; } AppProto AppLayerProtoDetectGetProtoByName(const char *alproto_name) { SCEnter(); AppProto a; for (a = 0; a < ALPROTO_MAX; a++) { if (alpd_ctx.alproto_names[a] != NULL && strlen(alpd_ctx.alproto_names[a]) == strlen(alproto_name) && (SCMemcmp(alpd_ctx.alproto_names[a], alproto_name, strlen(alproto_name)) == 0)) { SCReturnCT(a, "AppProto"); } } SCReturnCT(ALPROTO_UNKNOWN, "AppProto"); } const char *AppLayerProtoDetectGetProtoName(AppProto alproto) { return alpd_ctx.alproto_names[alproto]; } void AppLayerProtoDetectSupportedAppProtocols(AppProto *alprotos) { SCEnter(); memset(alprotos, 0, ALPROTO_MAX * sizeof(AppProto)); int alproto; for (alproto = 0; alproto != ALPROTO_MAX; alproto++) { if (alpd_ctx.alproto_names[alproto] != NULL) alprotos[alproto] = 1; } SCReturn; } uint8_t expectation_proto[ALPROTO_MAX]; static void AppLayerProtoDetectPEGetIpprotos(AppProto alproto, uint8_t *ipprotos) { if (expectation_proto[alproto] == IPPROTO_TCP) { ipprotos[IPPROTO_TCP / 8] |= 1 << (IPPROTO_TCP % 8); } if (expectation_proto[alproto] == IPPROTO_UDP) { ipprotos[IPPROTO_UDP / 8] |= 1 << (IPPROTO_UDP % 8); } } void AppLayerRegisterExpectationProto(uint8_t proto, AppProto alproto) { if (expectation_proto[alproto]) { if (proto != expectation_proto[alproto]) { SCLogError(SC_ERR_NOT_SUPPORTED, "Expectation on 2 IP protocols are not supported"); } } expectation_proto[alproto] = proto; } /***** Unittests *****/ #ifdef UNITTESTS #include "app-layer-htp.h" static AppLayerProtoDetectCtx alpd_ctx_ut; void AppLayerProtoDetectUnittestCtxBackup(void) { SCEnter(); alpd_ctx_ut = alpd_ctx; memset(&alpd_ctx, 0, sizeof(alpd_ctx)); SCReturn; } void AppLayerProtoDetectUnittestCtxRestore(void) { SCEnter(); alpd_ctx = alpd_ctx_ut; memset(&alpd_ctx_ut, 0, sizeof(alpd_ctx_ut)); SCReturn; } static int AppLayerProtoDetectTest01(void) { AppLayerProtoDetectUnittestCtxBackup(); AppLayerProtoDetectSetup(); const char *buf; int r = 0; buf = "HTTP"; AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_HTTP, buf, 4, 0, STREAM_TOCLIENT); buf = "GET"; AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_HTTP, buf, 4, 0, STREAM_TOSERVER); AppLayerProtoDetectPrepareState(); if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].max_pat_id != 1) { printf("Failure - " "alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].max_pat_id != 1\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].max_pat_id != 1) { printf("Failure - " "alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].max_pat_id != 1\n"); goto end; } r = 1; end: AppLayerProtoDetectDeSetup(); AppLayerProtoDetectUnittestCtxRestore(); return r; } static int AppLayerProtoDetectTest02(void) { AppLayerProtoDetectUnittestCtxBackup(); AppLayerProtoDetectSetup(); int r = 0; const char *buf = "HTTP"; AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_HTTP, buf, 4, 0, STREAM_TOCLIENT); buf = "ftp"; AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_FTP, buf, 4, 0, STREAM_TOCLIENT); AppLayerProtoDetectPrepareState(); if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].max_pat_id != 0) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].max_pat_id != 0\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].max_pat_id != 2) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].max_pat_id != 2\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].map != NULL) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].map != NULL\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map == NULL) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map != NULL\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map[0]->alproto != ALPROTO_FTP) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map[0].alproto != ALPROTO_FTP\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map[1]->alproto != ALPROTO_HTTP) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map[1].alproto != ALPROTO_HTTP\n"); goto end; } r = 1; end: AppLayerProtoDetectDeSetup(); AppLayerProtoDetectUnittestCtxRestore(); return r; } static int AppLayerProtoDetectTest03(void) { AppLayerProtoDetectUnittestCtxBackup(); AppLayerProtoDetectSetup(); uint8_t l7data[] = "HTTP/1.1 200 OK\r\nServer: Apache/1.0\r\n\r\n"; const char *buf; int r = 0; Flow f; AppProto pm_results[ALPROTO_MAX]; AppLayerProtoDetectThreadCtx *alpd_tctx; memset(&f, 0x00, sizeof(f)); f.protomap = FlowGetProtoMapping(IPPROTO_TCP); memset(pm_results, 0, sizeof(pm_results)); buf = "HTTP"; AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_HTTP, buf, 4, 0, STREAM_TOCLIENT); buf = "220 "; AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_FTP, buf, 4, 0, STREAM_TOCLIENT); AppLayerProtoDetectPrepareState(); /* AppLayerProtoDetectGetCtxThread() should be called post AppLayerProtoDetectPrepareState(), since * it sets internal structures which depends on the above function. */ alpd_tctx = AppLayerProtoDetectGetCtxThread(); if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].max_pat_id != 0) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].max_pat_id != 0\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].max_pat_id != 2) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].max_pat_id != 2\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].map != NULL) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].map != NULL\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map == NULL) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map != NULL\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map[0]->alproto != ALPROTO_FTP) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map[0].alproto != ALPROTO_FTP\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map[1]->alproto != ALPROTO_HTTP) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map[1].alproto != ALPROTO_HTTP\n"); goto end; } uint32_t cnt = AppLayerProtoDetectPMGetProto(alpd_tctx, &f, l7data, sizeof(l7data), STREAM_TOCLIENT, IPPROTO_TCP, pm_results); if (cnt != 1 && pm_results[0] != ALPROTO_HTTP) { printf("cnt != 1 && pm_results[0] != AlPROTO_HTTP\n"); goto end; } r = 1; end: if (alpd_tctx != NULL) AppLayerProtoDetectDestroyCtxThread(alpd_tctx); AppLayerProtoDetectDeSetup(); AppLayerProtoDetectUnittestCtxRestore(); return r; } static int AppLayerProtoDetectTest04(void) { AppLayerProtoDetectUnittestCtxBackup(); AppLayerProtoDetectSetup(); uint8_t l7data[] = "HTTP/1.1 200 OK\r\nServer: Apache/1.0\r\n\r\n"; const char *buf; int r = 0; Flow f; AppProto pm_results[ALPROTO_MAX]; AppLayerProtoDetectThreadCtx *alpd_tctx; memset(&f, 0x00, sizeof(f)); f.protomap = FlowGetProtoMapping(IPPROTO_TCP); memset(pm_results, 0, sizeof(pm_results)); buf = "200 "; AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_HTTP, buf, 13, 0, STREAM_TOCLIENT); AppLayerProtoDetectPrepareState(); /* AppLayerProtoDetectGetCtxThread() should be called post AppLayerProtoDetectPrepareState(), since * it sets internal structures which depends on the above function. */ alpd_tctx = AppLayerProtoDetectGetCtxThread(); if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].max_pat_id != 0) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].max_pat_id != 0\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].max_pat_id != 1) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].max_pat_id != 2\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].map != NULL) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].map != NULL\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map == NULL) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map != NULL\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map[0]->alproto != ALPROTO_HTTP) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map[0].alproto != ALPROTO_HTTP\n"); goto end; } uint32_t cnt = AppLayerProtoDetectPMGetProto(alpd_tctx, &f, l7data, sizeof(l7data), STREAM_TOCLIENT, IPPROTO_TCP, pm_results); if (cnt != 1 && pm_results[0] != ALPROTO_HTTP) { printf("cnt != 1 && pm_results[0] != AlPROTO_HTTP\n"); goto end; } r = 1; end: if (alpd_tctx != NULL) AppLayerProtoDetectDestroyCtxThread(alpd_tctx); AppLayerProtoDetectDeSetup(); AppLayerProtoDetectUnittestCtxRestore(); return r; } static int AppLayerProtoDetectTest05(void) { AppLayerProtoDetectUnittestCtxBackup(); AppLayerProtoDetectSetup(); uint8_t l7data[] = "HTTP/1.1 200 OK\r\nServer: Apache/1.0\r\n\r\n<HTML><BODY>Blahblah</BODY></HTML>"; const char *buf; int r = 0; Flow f; AppProto pm_results[ALPROTO_MAX]; AppLayerProtoDetectThreadCtx *alpd_tctx; memset(&f, 0x00, sizeof(f)); f.protomap = FlowGetProtoMapping(IPPROTO_TCP); memset(pm_results, 0, sizeof(pm_results)); buf = "HTTP"; AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_HTTP, buf, 4, 0, STREAM_TOCLIENT); buf = "220 "; AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_FTP, buf, 4, 0, STREAM_TOCLIENT); AppLayerProtoDetectPrepareState(); /* AppLayerProtoDetectGetCtxThread() should be called post AppLayerProtoDetectPrepareState(), since * it sets internal structures which depends on the above function. */ alpd_tctx = AppLayerProtoDetectGetCtxThread(); if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].max_pat_id != 0) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].max_pat_id != 0\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].max_pat_id != 2) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].max_pat_id != 2\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].map != NULL) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].map != NULL\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map == NULL) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map != NULL\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map[0]->alproto != ALPROTO_FTP) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map[0].alproto != ALPROTO_FTP\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map[1]->alproto != ALPROTO_HTTP) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map[1].alproto != ALPROTO_HTTP\n"); goto end; } uint32_t cnt = AppLayerProtoDetectPMGetProto(alpd_tctx, &f, l7data, sizeof(l7data), STREAM_TOCLIENT, IPPROTO_TCP, pm_results); if (cnt != 1 && pm_results[0] != ALPROTO_HTTP) { printf("cnt != 1 && pm_results[0] != AlPROTO_HTTP\n"); goto end; } r = 1; end: if (alpd_tctx != NULL) AppLayerProtoDetectDestroyCtxThread(alpd_tctx); AppLayerProtoDetectDeSetup(); AppLayerProtoDetectUnittestCtxRestore(); return r; } static int AppLayerProtoDetectTest06(void) { AppLayerProtoDetectUnittestCtxBackup(); AppLayerProtoDetectSetup(); uint8_t l7data[] = "220 Welcome to the OISF FTP server\r\n"; const char *buf; int r = 0; Flow f; AppProto pm_results[ALPROTO_MAX]; AppLayerProtoDetectThreadCtx *alpd_tctx; memset(&f, 0x00, sizeof(f)); f.protomap = FlowGetProtoMapping(IPPROTO_TCP); buf = "HTTP"; AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_HTTP, buf, 4, 0, STREAM_TOCLIENT); buf = "220 "; AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_FTP, buf, 4, 0, STREAM_TOCLIENT); AppLayerProtoDetectPrepareState(); /* AppLayerProtoDetectGetCtxThread() should be called post AppLayerProtoDetectPrepareState(), since * it sets internal structures which depends on the above function. */ alpd_tctx = AppLayerProtoDetectGetCtxThread(); if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].max_pat_id != 0) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].max_pat_id != 0\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].max_pat_id != 2) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].max_pat_id != 2\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].map != NULL) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].map != NULL\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map == NULL) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map != NULL\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map[0]->alproto != ALPROTO_FTP) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map[0].alproto != ALPROTO_FTP\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map[1]->alproto != ALPROTO_HTTP) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map[1].alproto != ALPROTO_HTTP\n"); goto end; } uint32_t cnt = AppLayerProtoDetectPMGetProto(alpd_tctx, &f, l7data, sizeof(l7data), STREAM_TOCLIENT, IPPROTO_TCP, pm_results); if (cnt != 1 && pm_results[0] != ALPROTO_FTP) { printf("cnt != 1 && pm_results[0] != AlPROTO_FTP\n"); goto end; } r = 1; end: if (alpd_tctx != NULL) AppLayerProtoDetectDestroyCtxThread(alpd_tctx); AppLayerProtoDetectDeSetup(); AppLayerProtoDetectUnittestCtxRestore(); return r; } static int AppLayerProtoDetectTest07(void) { AppLayerProtoDetectUnittestCtxBackup(); AppLayerProtoDetectSetup(); uint8_t l7data[] = "220 Welcome to the OISF HTTP/FTP server\r\n"; const char *buf; int r = 0; Flow f; AppProto pm_results[ALPROTO_MAX]; AppLayerProtoDetectThreadCtx *alpd_tctx; memset(&f, 0x00, sizeof(f)); f.protomap = FlowGetProtoMapping(IPPROTO_TCP); memset(pm_results, 0, sizeof(pm_results)); buf = "HTTP"; AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_HTTP, buf, 4, 0, STREAM_TOCLIENT); AppLayerProtoDetectPrepareState(); /* AppLayerProtoDetectGetCtxThread() should be called post AppLayerProtoDetectPrepareState(), since * it sets internal structures which depends on the above function. */ alpd_tctx = AppLayerProtoDetectGetCtxThread(); if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].max_pat_id != 0) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].max_pat_id != 0\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].max_pat_id != 1) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].max_pat_id != 2\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].map != NULL) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].map != NULL\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map == NULL) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map != NULL\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map[0]->alproto != ALPROTO_HTTP) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map[0].alproto != ALPROTO_HTTP\n"); goto end; } uint32_t cnt = AppLayerProtoDetectPMGetProto(alpd_tctx, &f, l7data, sizeof(l7data), STREAM_TOCLIENT, IPPROTO_TCP, pm_results); if (cnt != 0) { printf("cnt != 0\n"); goto end; } r = 1; end: if (alpd_tctx != NULL) AppLayerProtoDetectDestroyCtxThread(alpd_tctx); AppLayerProtoDetectDeSetup(); AppLayerProtoDetectUnittestCtxRestore(); return r; } static int AppLayerProtoDetectTest08(void) { AppLayerProtoDetectUnittestCtxBackup(); AppLayerProtoDetectSetup(); uint8_t l7data[] = { 0x00, 0x00, 0x00, 0x85, 0xff, 0x53, 0x4d, 0x42, 0x72, 0x00, 0x00, 0x00, 0x00, 0x18, 0x53, 0xc8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xfe, 0x00, 0x00, 0x00, 0x00, 0x00, 0x62, 0x00, 0x02, 0x50, 0x43, 0x20, 0x4e, 0x45, 0x54, 0x57, 0x4f, 0x52, 0x4b, 0x20, 0x50, 0x52, 0x4f, 0x47, 0x52, 0x41, 0x4d, 0x20, 0x31, 0x2e, 0x30, 0x00, 0x02, 0x4c, 0x41, 0x4e, 0x4d, 0x41, 0x4e, 0x31, 0x2e, 0x30, 0x00, 0x02, 0x57, 0x69, 0x6e, 0x64, 0x6f, 0x77, 0x73, 0x20, 0x66, 0x6f, 0x72, 0x20, 0x57, 0x6f, 0x72, 0x6b, 0x67, 0x72, 0x6f, 0x75, 0x70, 0x73, 0x20, 0x33, 0x2e, 0x31, 0x61, 0x00, 0x02, 0x4c, 0x4d, 0x31, 0x2e, 0x32, 0x58, 0x30, 0x30, 0x32, 0x00, 0x02, 0x4c, 0x41, 0x4e, 0x4d, 0x41, 0x4e, 0x32, 0x2e, 0x31, 0x00, 0x02, 0x4e, 0x54, 0x20, 0x4c, 0x4d, 0x20, 0x30, 0x2e, 0x31, 0x32, 0x00 }; const char *buf; int r = 0; Flow f; AppProto pm_results[ALPROTO_MAX]; AppLayerProtoDetectThreadCtx *alpd_tctx; memset(&f, 0x00, sizeof(f)); f.protomap = FlowGetProtoMapping(IPPROTO_TCP); memset(pm_results, 0, sizeof(pm_results)); buf = "|ff|SMB"; AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_SMB, buf, 8, 4, STREAM_TOCLIENT); AppLayerProtoDetectPrepareState(); /* AppLayerProtoDetectGetCtxThread() should be called post AppLayerProtoDetectPrepareState(), since * it sets internal structures which depends on the above function. */ alpd_tctx = AppLayerProtoDetectGetCtxThread(); if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].max_pat_id != 0) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].max_pat_id != 0\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].max_pat_id != 1) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].max_pat_id != 2\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].map != NULL) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].map != NULL\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map == NULL) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map != NULL\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map[0]->alproto != ALPROTO_SMB) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map[0].alproto != ALPROTO_SMB\n"); goto end; } uint32_t cnt = AppLayerProtoDetectPMGetProto(alpd_tctx, &f, l7data, sizeof(l7data), STREAM_TOCLIENT, IPPROTO_TCP, pm_results); if (cnt != 1 && pm_results[0] != ALPROTO_SMB) { printf("cnt != 1 && pm_results[0] != AlPROTO_SMB\n"); goto end; } r = 1; end: if (alpd_tctx != NULL) AppLayerProtoDetectDestroyCtxThread(alpd_tctx); AppLayerProtoDetectDeSetup(); AppLayerProtoDetectUnittestCtxRestore(); return r; } static int AppLayerProtoDetectTest09(void) { AppLayerProtoDetectUnittestCtxBackup(); AppLayerProtoDetectSetup(); uint8_t l7data[] = { 0x00, 0x00, 0x00, 0x66, 0xfe, 0x53, 0x4d, 0x42, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x24, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x02 }; const char *buf; int r = 0; Flow f; AppProto pm_results[ALPROTO_MAX]; AppLayerProtoDetectThreadCtx *alpd_tctx; memset(&f, 0x00, sizeof(f)); f.protomap = FlowGetProtoMapping(IPPROTO_TCP); memset(pm_results, 0, sizeof(pm_results)); buf = "|fe|SMB"; AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_SMB2, buf, 8, 4, STREAM_TOCLIENT); AppLayerProtoDetectPrepareState(); /* AppLayerProtoDetectGetCtxThread() should be called post AppLayerProtoDetectPrepareState(), since * it sets internal structures which depends on the above function. */ alpd_tctx = AppLayerProtoDetectGetCtxThread(); if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].max_pat_id != 0) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].max_pat_id != 0\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].max_pat_id != 1) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].max_pat_id != 2\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].map != NULL) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].map != NULL\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map == NULL) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map != NULL\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map[0]->alproto != ALPROTO_SMB2) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map[0].alproto != ALPROTO_SMB2\n"); goto end; } uint32_t cnt = AppLayerProtoDetectPMGetProto(alpd_tctx, &f, l7data, sizeof(l7data), STREAM_TOCLIENT, IPPROTO_TCP, pm_results); if (cnt != 1 && pm_results[0] != ALPROTO_SMB2) { printf("cnt != 1 && pm_results[0] != AlPROTO_SMB2\n"); goto end; } r = 1; end: if (alpd_tctx != NULL) AppLayerProtoDetectDestroyCtxThread(alpd_tctx); AppLayerProtoDetectDeSetup(); AppLayerProtoDetectUnittestCtxRestore(); return r; } static int AppLayerProtoDetectTest10(void) { AppLayerProtoDetectUnittestCtxBackup(); AppLayerProtoDetectSetup(); uint8_t l7data[] = { 0x05, 0x00, 0x0b, 0x03, 0x10, 0x00, 0x00, 0x00, 0x48, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd0, 0x16, 0xd0, 0x16, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0xb8, 0x4a, 0x9f, 0x4d, 0x1c, 0x7d, 0xcf, 0x11, 0x86, 0x1e, 0x00, 0x20, 0xaf, 0x6e, 0x7c, 0x57, 0x00, 0x00, 0x00, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00 }; const char *buf; int r = 0; Flow f; AppProto pm_results[ALPROTO_MAX]; AppLayerProtoDetectThreadCtx *alpd_tctx; memset(&f, 0x00, sizeof(f)); f.protomap = FlowGetProtoMapping(IPPROTO_TCP); memset(pm_results, 0, sizeof(pm_results)); buf = "|05 00|"; AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_DCERPC, buf, 4, 0, STREAM_TOCLIENT); AppLayerProtoDetectPrepareState(); /* AppLayerProtoDetectGetCtxThread() should be called post AppLayerProtoDetectPrepareState(), since * it sets internal structures which depends on the above function. */ alpd_tctx = AppLayerProtoDetectGetCtxThread(); if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].max_pat_id != 0) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].max_pat_id != 0\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].max_pat_id != 1) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].max_pat_id != 2\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].map != NULL) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].map != NULL\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map == NULL) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map != NULL\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map[0]->alproto != ALPROTO_DCERPC) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map[0].alproto != ALPROTO_DCERPC\n"); goto end; } uint32_t cnt = AppLayerProtoDetectPMGetProto(alpd_tctx, &f, l7data, sizeof(l7data), STREAM_TOCLIENT, IPPROTO_TCP, pm_results); if (cnt != 1 && pm_results[0] != ALPROTO_DCERPC) { printf("cnt != 1 && pm_results[0] != AlPROTO_DCERPC\n"); goto end; } r = 1; end: if (alpd_tctx != NULL) AppLayerProtoDetectDestroyCtxThread(alpd_tctx); AppLayerProtoDetectDeSetup(); AppLayerProtoDetectUnittestCtxRestore(); return r; } /** * \test Why we still get http for connect... obviously because * we also match on the reply, duh */ static int AppLayerProtoDetectTest11(void) { AppLayerProtoDetectUnittestCtxBackup(); AppLayerProtoDetectSetup(); uint8_t l7data[] = "CONNECT www.ssllabs.com:443 HTTP/1.0\r\n"; uint8_t l7data_resp[] = "HTTP/1.1 405 Method Not Allowed\r\n"; int r = 0; Flow f; AppProto pm_results[ALPROTO_MAX]; AppLayerProtoDetectThreadCtx *alpd_tctx; memset(&f, 0x00, sizeof(f)); f.protomap = FlowGetProtoMapping(IPPROTO_TCP); memset(pm_results, 0, sizeof(pm_results)); AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_HTTP, "HTTP", 4, 0, STREAM_TOSERVER); AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_HTTP, "GET", 3, 0, STREAM_TOSERVER); AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_HTTP, "PUT", 3, 0, STREAM_TOSERVER); AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_HTTP, "POST", 4, 0, STREAM_TOSERVER); AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_HTTP, "TRACE", 5, 0, STREAM_TOSERVER); AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_HTTP, "OPTIONS", 7, 0, STREAM_TOSERVER); AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_HTTP, "CONNECT", 7, 0, STREAM_TOSERVER); AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_HTTP, "HTTP", 4, 0, STREAM_TOCLIENT); AppLayerProtoDetectPrepareState(); /* AppLayerProtoDetectGetCtxThread() should be called post AppLayerProtoDetectPrepareState(), since * it sets internal structures which depends on the above function. */ alpd_tctx = AppLayerProtoDetectGetCtxThread(); if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].max_pat_id != 7) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].max_pat_id != 7\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].max_pat_id != 1) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].max_pat_id != 1\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].map == NULL) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].map != NULL\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map == NULL) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map != NULL\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].map[0]->alproto != ALPROTO_HTTP || alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].map[1]->alproto != ALPROTO_HTTP || alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].map[2]->alproto != ALPROTO_HTTP || alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].map[3]->alproto != ALPROTO_HTTP || alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].map[4]->alproto != ALPROTO_HTTP || alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].map[5]->alproto != ALPROTO_HTTP || alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].map[6]->alproto != ALPROTO_HTTP || alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map[0]->alproto != ALPROTO_HTTP) { printf("failure 1\n"); goto end; } memset(pm_results, 0, sizeof(pm_results)); uint32_t cnt = AppLayerProtoDetectPMGetProto(alpd_tctx, &f, l7data, sizeof(l7data), STREAM_TOSERVER, IPPROTO_TCP, pm_results); if (cnt != 1 && pm_results[0] != ALPROTO_HTTP) { printf("l7data - cnt != 1 && pm_results[0] != AlPROTO_HTTP\n"); goto end; } memset(pm_results, 0, sizeof(pm_results)); cnt = AppLayerProtoDetectPMGetProto(alpd_tctx, &f, l7data_resp, sizeof(l7data_resp), STREAM_TOCLIENT, IPPROTO_TCP, pm_results); if (cnt != 1 && pm_results[0] != ALPROTO_HTTP) { printf("l7data_resp - cnt != 1 && pm_results[0] != AlPROTO_HTTP\n"); goto end; } r = 1; end: if (alpd_tctx != NULL) AppLayerProtoDetectDestroyCtxThread(alpd_tctx); AppLayerProtoDetectDeSetup(); AppLayerProtoDetectUnittestCtxRestore(); return r; } /** * \test AlpProtoSignature test */ static int AppLayerProtoDetectTest12(void) { AppLayerProtoDetectUnittestCtxBackup(); AppLayerProtoDetectSetup(); int r = 0; AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_HTTP, "HTTP", 4, 0, STREAM_TOSERVER); if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].head == NULL || alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].map != NULL) { printf("failure 1\n"); goto end; } AppLayerProtoDetectPrepareState(); if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].max_pat_id != 1) { printf("failure 2\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].head != NULL || alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].map == NULL) { printf("failure 3\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].map[0]->alproto != ALPROTO_HTTP) { printf("failure 4\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].map[0]->cd->id != 0) { printf("failure 5\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].map[0]->next != NULL) { printf("failure 6\n"); goto end; } r = 1; end: AppLayerProtoDetectDeSetup(); AppLayerProtoDetectUnittestCtxRestore(); return r; } /** * \test What about if we add some sigs only for udp but call for tcp? * It should not detect any proto */ static int AppLayerProtoDetectTest13(void) { AppLayerProtoDetectUnittestCtxBackup(); AppLayerProtoDetectSetup(); uint8_t l7data[] = "CONNECT www.ssllabs.com:443 HTTP/1.0\r\n"; uint8_t l7data_resp[] = "HTTP/1.1 405 Method Not Allowed\r\n"; int r = 0; Flow f; AppProto pm_results[ALPROTO_MAX]; AppLayerProtoDetectThreadCtx *alpd_tctx; uint32_t cnt; memset(&f, 0x00, sizeof(f)); f.protomap = FlowGetProtoMapping(IPPROTO_TCP); AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_UDP, ALPROTO_HTTP, "HTTP", 4, 0, STREAM_TOSERVER); AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_UDP, ALPROTO_HTTP, "GET", 3, 0, STREAM_TOSERVER); AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_UDP, ALPROTO_HTTP, "PUT", 3, 0, STREAM_TOSERVER); AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_UDP, ALPROTO_HTTP, "POST", 4, 0, STREAM_TOSERVER); AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_UDP, ALPROTO_HTTP, "TRACE", 5, 0, STREAM_TOSERVER); AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_UDP, ALPROTO_HTTP, "OPTIONS", 7, 0, STREAM_TOSERVER); AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_UDP, ALPROTO_HTTP, "CONNECT", 7, 0, STREAM_TOSERVER); AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_UDP, ALPROTO_HTTP, "HTTP", 4, 0, STREAM_TOCLIENT); AppLayerProtoDetectPrepareState(); /* AppLayerProtoDetectGetCtxThread() should be called post AppLayerProtoDetectPrepareState(), since * it sets internal structures which depends on the above function. */ alpd_tctx = AppLayerProtoDetectGetCtxThread(); if (alpd_ctx.ctx_ipp[FLOW_PROTO_UDP].ctx_pm[0].max_pat_id != 7) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_UDP].ctx_pm[0].max_pat_id != 7\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_UDP].ctx_pm[1].max_pat_id != 1) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_UDP].ctx_pm[1].max_pat_id != 1\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_UDP].ctx_pm[0].map[0]->alproto != ALPROTO_HTTP || alpd_ctx.ctx_ipp[FLOW_PROTO_UDP].ctx_pm[0].map[1]->alproto != ALPROTO_HTTP || alpd_ctx.ctx_ipp[FLOW_PROTO_UDP].ctx_pm[0].map[2]->alproto != ALPROTO_HTTP || alpd_ctx.ctx_ipp[FLOW_PROTO_UDP].ctx_pm[0].map[3]->alproto != ALPROTO_HTTP || alpd_ctx.ctx_ipp[FLOW_PROTO_UDP].ctx_pm[0].map[4]->alproto != ALPROTO_HTTP || alpd_ctx.ctx_ipp[FLOW_PROTO_UDP].ctx_pm[0].map[5]->alproto != ALPROTO_HTTP || alpd_ctx.ctx_ipp[FLOW_PROTO_UDP].ctx_pm[0].map[6]->alproto != ALPROTO_HTTP || alpd_ctx.ctx_ipp[FLOW_PROTO_UDP].ctx_pm[1].map[0]->alproto != ALPROTO_HTTP) { printf("failure 1\n"); goto end; } memset(pm_results, 0, sizeof(pm_results)); cnt = AppLayerProtoDetectPMGetProto(alpd_tctx, &f, l7data, sizeof(l7data), STREAM_TOSERVER, IPPROTO_TCP, pm_results); if (cnt != 0) { printf("l7data - cnt != 0\n"); goto end; } memset(pm_results, 0, sizeof(pm_results)); cnt = AppLayerProtoDetectPMGetProto(alpd_tctx, &f, l7data_resp, sizeof(l7data_resp), STREAM_TOCLIENT, IPPROTO_TCP, pm_results); if (cnt != 0) { printf("l7data_resp - cnt != 0\n"); goto end; } r = 1; end: if (alpd_tctx != NULL) AppLayerProtoDetectDestroyCtxThread(alpd_tctx); AppLayerProtoDetectDeSetup(); AppLayerProtoDetectUnittestCtxRestore(); return r; } /** * \test What about if we add some sigs only for udp calling it for UDP? * It should detect ALPROTO_HTTP (over udp). This is just a check * to ensure that TCP/UDP differences work correctly. */ static int AppLayerProtoDetectTest14(void) { AppLayerProtoDetectUnittestCtxBackup(); AppLayerProtoDetectSetup(); uint8_t l7data[] = "CONNECT www.ssllabs.com:443 HTTP/1.0\r\n"; uint8_t l7data_resp[] = "HTTP/1.1 405 Method Not Allowed\r\n"; int r = 0; Flow f; AppProto pm_results[ALPROTO_MAX]; AppLayerProtoDetectThreadCtx *alpd_tctx; uint32_t cnt; memset(&f, 0x00, sizeof(f)); f.protomap = FlowGetProtoMapping(IPPROTO_UDP); AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_UDP, ALPROTO_HTTP, "HTTP", 4, 0, STREAM_TOSERVER); AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_UDP, ALPROTO_HTTP, "GET", 3, 0, STREAM_TOSERVER); AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_UDP, ALPROTO_HTTP, "PUT", 3, 0, STREAM_TOSERVER); AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_UDP, ALPROTO_HTTP, "POST", 4, 0, STREAM_TOSERVER); AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_UDP, ALPROTO_HTTP, "TRACE", 5, 0, STREAM_TOSERVER); AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_UDP, ALPROTO_HTTP, "OPTIONS", 7, 0, STREAM_TOSERVER); AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_UDP, ALPROTO_HTTP, "CONNECT", 7, 0, STREAM_TOSERVER); AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_UDP, ALPROTO_HTTP, "HTTP", 4, 0, STREAM_TOCLIENT); AppLayerProtoDetectPrepareState(); /* AppLayerProtoDetectGetCtxThread() should be called post AppLayerProtoDetectPrepareState(), since * it sets internal structures which depends on the above function. */ alpd_tctx = AppLayerProtoDetectGetCtxThread(); if (alpd_ctx.ctx_ipp[FLOW_PROTO_UDP].ctx_pm[0].max_pat_id != 7) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_UDP].ctx_pm[0].max_pat_id != 7\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_UDP].ctx_pm[1].max_pat_id != 1) { printf("alpd_ctx.ctx_ipp[FLOW_PROTO_UDP].ctx_pm[1].max_pat_id != 1\n"); goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_UDP].ctx_pm[0].map[0]->alproto != ALPROTO_HTTP || alpd_ctx.ctx_ipp[FLOW_PROTO_UDP].ctx_pm[0].map[1]->alproto != ALPROTO_HTTP || alpd_ctx.ctx_ipp[FLOW_PROTO_UDP].ctx_pm[0].map[2]->alproto != ALPROTO_HTTP || alpd_ctx.ctx_ipp[FLOW_PROTO_UDP].ctx_pm[0].map[3]->alproto != ALPROTO_HTTP || alpd_ctx.ctx_ipp[FLOW_PROTO_UDP].ctx_pm[0].map[4]->alproto != ALPROTO_HTTP || alpd_ctx.ctx_ipp[FLOW_PROTO_UDP].ctx_pm[0].map[5]->alproto != ALPROTO_HTTP || alpd_ctx.ctx_ipp[FLOW_PROTO_UDP].ctx_pm[0].map[6]->alproto != ALPROTO_HTTP || alpd_ctx.ctx_ipp[FLOW_PROTO_UDP].ctx_pm[1].map[0]->alproto != ALPROTO_HTTP) { printf("failure 1\n"); goto end; } memset(pm_results, 0, sizeof(pm_results)); cnt = AppLayerProtoDetectPMGetProto(alpd_tctx, &f, l7data, sizeof(l7data), STREAM_TOSERVER, IPPROTO_UDP, pm_results); if (cnt != 1 && pm_results[0] != ALPROTO_HTTP) { printf("l7data - cnt != 0\n"); goto end; } memset(pm_results, 0, sizeof(pm_results)); cnt = AppLayerProtoDetectPMGetProto(alpd_tctx, &f, l7data_resp, sizeof(l7data_resp), STREAM_TOCLIENT, IPPROTO_UDP, pm_results); if (cnt != 1 && pm_results[0] != ALPROTO_HTTP) { printf("l7data_resp - cnt != 0\n"); goto end; } r = 1; end: if (alpd_tctx != NULL) AppLayerProtoDetectDestroyCtxThread(alpd_tctx); AppLayerProtoDetectDeSetup(); AppLayerProtoDetectUnittestCtxRestore(); return r; } typedef struct AppLayerProtoDetectPPTestDataElement_ { const char *alproto_name; AppProto alproto; uint16_t port; uint32_t alproto_mask; uint32_t min_depth; uint32_t max_depth; } AppLayerProtoDetectPPTestDataElement; typedef struct AppLayerProtoDetectPPTestDataPort_ { uint16_t port; uint32_t alproto_mask; uint16_t dp_max_depth; uint16_t sp_max_depth; AppLayerProtoDetectPPTestDataElement *toserver_element; AppLayerProtoDetectPPTestDataElement *toclient_element; int ts_no_of_element; int tc_no_of_element; } AppLayerProtoDetectPPTestDataPort; typedef struct AppLayerProtoDetectPPTestDataIPProto_ { uint8_t ipproto; AppLayerProtoDetectPPTestDataPort *port; int no_of_port; } AppLayerProtoDetectPPTestDataIPProto; static int AppLayerProtoDetectPPTestData(AppLayerProtoDetectProbingParser *pp, AppLayerProtoDetectPPTestDataIPProto *ip_proto, int no_of_ip_proto) { int result = 0; int i = -1, j = -1 , k = -1; #ifdef DEBUG int dir = 0; #endif for (i = 0; i < no_of_ip_proto; i++, pp = pp->next) { if (pp->ipproto != ip_proto[i].ipproto) goto end; AppLayerProtoDetectProbingParserPort *pp_port = pp->port; for (k = 0; k < ip_proto[i].no_of_port; k++, pp_port = pp_port->next) { if (pp_port->port != ip_proto[i].port[k].port) goto end; if (pp_port->alproto_mask != ip_proto[i].port[k].alproto_mask) goto end; if (pp_port->alproto_mask != ip_proto[i].port[k].alproto_mask) goto end; if (pp_port->dp_max_depth != ip_proto[i].port[k].dp_max_depth) goto end; if (pp_port->sp_max_depth != ip_proto[i].port[k].sp_max_depth) goto end; AppLayerProtoDetectProbingParserElement *pp_element = pp_port->dp; #ifdef DEBUG dir = 0; #endif for (j = 0 ; j < ip_proto[i].port[k].ts_no_of_element; j++, pp_element = pp_element->next) { if (pp_element->alproto != ip_proto[i].port[k].toserver_element[j].alproto) { goto end; } if (pp_element->port != ip_proto[i].port[k].toserver_element[j].port) { goto end; } if (pp_element->alproto_mask != ip_proto[i].port[k].toserver_element[j].alproto_mask) { goto end; } if (pp_element->min_depth != ip_proto[i].port[k].toserver_element[j].min_depth) { goto end; } if (pp_element->max_depth != ip_proto[i].port[k].toserver_element[j].max_depth) { goto end; } } /* for */ if (pp_element != NULL) goto end; pp_element = pp_port->sp; #ifdef DEBUG dir = 1; #endif for (j = 0 ; j < ip_proto[i].port[k].tc_no_of_element; j++, pp_element = pp_element->next) { if (pp_element->alproto != ip_proto[i].port[k].toclient_element[j].alproto) { goto end; } if (pp_element->port != ip_proto[i].port[k].toclient_element[j].port) { goto end; } if (pp_element->alproto_mask != ip_proto[i].port[k].toclient_element[j].alproto_mask) { goto end; } if (pp_element->min_depth != ip_proto[i].port[k].toclient_element[j].min_depth) { goto end; } if (pp_element->max_depth != ip_proto[i].port[k].toclient_element[j].max_depth) { goto end; } } /* for */ if (pp_element != NULL) goto end; } if (pp_port != NULL) goto end; } if (pp != NULL) goto end; result = 1; end: #ifdef DEBUG printf("i = %d, k = %d, j = %d(%s)\n", i, k, j, (dir == 0) ? "ts" : "tc"); #endif return result; } static uint16_t ProbingParserDummyForTesting(Flow *f, uint8_t *input, uint32_t input_len) { return 0; } static int AppLayerProtoDetectTest15(void) { AppLayerProtoDetectUnittestCtxBackup(); AppLayerProtoDetectSetup(); int result = 0; AppLayerProtoDetectPPRegister(IPPROTO_TCP, "80", ALPROTO_HTTP, 5, 8, STREAM_TOSERVER, ProbingParserDummyForTesting, NULL); AppLayerProtoDetectPPRegister(IPPROTO_TCP, "80", ALPROTO_SMB, 5, 6, STREAM_TOSERVER, ProbingParserDummyForTesting, NULL); AppLayerProtoDetectPPRegister(IPPROTO_TCP, "80", ALPROTO_FTP, 7, 10, STREAM_TOSERVER, ProbingParserDummyForTesting, NULL); AppLayerProtoDetectPPRegister(IPPROTO_TCP, "81", ALPROTO_DCERPC, 9, 10, STREAM_TOSERVER, ProbingParserDummyForTesting, NULL); AppLayerProtoDetectPPRegister(IPPROTO_TCP, "81", ALPROTO_FTP, 7, 15, STREAM_TOSERVER, ProbingParserDummyForTesting, NULL); AppLayerProtoDetectPPRegister(IPPROTO_TCP, "0", ALPROTO_SMTP, 12, 0, STREAM_TOSERVER, ProbingParserDummyForTesting, NULL); AppLayerProtoDetectPPRegister(IPPROTO_TCP, "0", ALPROTO_TLS, 12, 18, STREAM_TOSERVER, ProbingParserDummyForTesting, NULL); AppLayerProtoDetectPPRegister(IPPROTO_TCP, "85", ALPROTO_DCERPC, 9, 10, STREAM_TOSERVER, ProbingParserDummyForTesting, NULL); AppLayerProtoDetectPPRegister(IPPROTO_TCP, "85", ALPROTO_FTP, 7, 15, STREAM_TOSERVER, ProbingParserDummyForTesting, NULL); result = 1; AppLayerProtoDetectPPRegister(IPPROTO_UDP, "85", ALPROTO_IMAP, 12, 23, STREAM_TOSERVER, ProbingParserDummyForTesting, NULL); /* toclient */ AppLayerProtoDetectPPRegister(IPPROTO_TCP, "0", ALPROTO_JABBER, 12, 23, STREAM_TOCLIENT, ProbingParserDummyForTesting, NULL); AppLayerProtoDetectPPRegister(IPPROTO_TCP, "0", ALPROTO_IRC, 12, 14, STREAM_TOCLIENT, ProbingParserDummyForTesting, NULL); AppLayerProtoDetectPPRegister(IPPROTO_TCP, "85", ALPROTO_DCERPC, 9, 10, STREAM_TOCLIENT, ProbingParserDummyForTesting, NULL); AppLayerProtoDetectPPRegister(IPPROTO_TCP, "81", ALPROTO_FTP, 7, 15, STREAM_TOCLIENT, ProbingParserDummyForTesting, NULL); AppLayerProtoDetectPPRegister(IPPROTO_TCP, "0", ALPROTO_TLS, 12, 18, STREAM_TOCLIENT, ProbingParserDummyForTesting, NULL); AppLayerProtoDetectPPRegister(IPPROTO_TCP, "80", ALPROTO_HTTP, 5, 8, STREAM_TOCLIENT, ProbingParserDummyForTesting, NULL); AppLayerProtoDetectPPRegister(IPPROTO_TCP, "81", ALPROTO_DCERPC, 9, 10, STREAM_TOCLIENT, ProbingParserDummyForTesting, NULL); AppLayerProtoDetectPPRegister(IPPROTO_TCP, "90", ALPROTO_FTP, 7, 15, STREAM_TOCLIENT, ProbingParserDummyForTesting, NULL); AppLayerProtoDetectPPRegister(IPPROTO_TCP, "80", ALPROTO_SMB, 5, 6, STREAM_TOCLIENT, ProbingParserDummyForTesting, NULL); AppLayerProtoDetectPPRegister(IPPROTO_UDP, "85", ALPROTO_IMAP, 12, 23, STREAM_TOCLIENT, ProbingParserDummyForTesting, NULL); AppLayerProtoDetectPPRegister(IPPROTO_TCP, "0", ALPROTO_SMTP, 12, 17, STREAM_TOCLIENT, ProbingParserDummyForTesting, NULL); AppLayerProtoDetectPPRegister(IPPROTO_TCP, "80", ALPROTO_FTP, 7, 10, STREAM_TOCLIENT, ProbingParserDummyForTesting, NULL); AppLayerProtoDetectPPTestDataElement element_ts_80[] = { { "http", ALPROTO_HTTP, 80, 1 << ALPROTO_HTTP, 5, 8 }, { "smb", ALPROTO_SMB, 80, 1 << ALPROTO_SMB, 5, 6 }, { "ftp", ALPROTO_FTP, 80, 1 << ALPROTO_FTP, 7, 10 }, { "smtp", ALPROTO_SMTP, 0, 1 << ALPROTO_SMTP, 12, 0 }, { "tls", ALPROTO_TLS, 0, 1 << ALPROTO_TLS, 12, 18 }, { "irc", ALPROTO_IRC, 0, 1 << ALPROTO_IRC, 12, 25 }, { "jabber", ALPROTO_JABBER, 0, 1 << ALPROTO_JABBER, 12, 23 }, }; AppLayerProtoDetectPPTestDataElement element_tc_80[] = { { "http", ALPROTO_HTTP, 80, 1 << ALPROTO_HTTP, 5, 8 }, { "smb", ALPROTO_SMB, 80, 1 << ALPROTO_SMB, 5, 6 }, { "ftp", ALPROTO_FTP, 80, 1 << ALPROTO_FTP, 7, 10 }, { "jabber", ALPROTO_JABBER, 0, 1 << ALPROTO_JABBER, 12, 23 }, { "irc", ALPROTO_IRC, 0, 1 << ALPROTO_IRC, 12, 14 }, { "tls", ALPROTO_TLS, 0, 1 << ALPROTO_TLS, 12, 18 }, { "smtp", ALPROTO_SMTP, 0, 1 << ALPROTO_SMTP, 12, 17 } }; AppLayerProtoDetectPPTestDataElement element_ts_81[] = { { "dcerpc", ALPROTO_DCERPC, 81, 1 << ALPROTO_DCERPC, 9, 10 }, { "ftp", ALPROTO_FTP, 81, 1 << ALPROTO_FTP, 7, 15 }, { "smtp", ALPROTO_SMTP, 0, 1 << ALPROTO_SMTP, 12, 0 }, { "tls", ALPROTO_TLS, 0, 1 << ALPROTO_TLS, 12, 18 }, { "irc", ALPROTO_IRC, 0, 1 << ALPROTO_IRC, 12, 25 }, { "jabber", ALPROTO_JABBER, 0, 1 << ALPROTO_JABBER, 12, 23 }, }; AppLayerProtoDetectPPTestDataElement element_tc_81[] = { { "ftp", ALPROTO_FTP, 81, 1 << ALPROTO_FTP, 7, 15 }, { "dcerpc", ALPROTO_DCERPC, 81, 1 << ALPROTO_DCERPC, 9, 10 }, { "jabber", ALPROTO_JABBER, 0, 1 << ALPROTO_JABBER, 12, 23 }, { "irc", ALPROTO_IRC, 0, 1 << ALPROTO_IRC, 12, 14 }, { "tls", ALPROTO_TLS, 0, 1 << ALPROTO_TLS, 12, 18 }, { "smtp", ALPROTO_SMTP, 0, 1 << ALPROTO_SMTP, 12, 17 } }; AppLayerProtoDetectPPTestDataElement element_ts_85[] = { { "dcerpc", ALPROTO_DCERPC, 85, 1 << ALPROTO_DCERPC, 9, 10 }, { "ftp", ALPROTO_FTP, 85, 1 << ALPROTO_FTP, 7, 15 }, { "smtp", ALPROTO_SMTP, 0, 1 << ALPROTO_SMTP, 12, 0 }, { "tls", ALPROTO_TLS, 0, 1 << ALPROTO_TLS, 12, 18 }, { "irc", ALPROTO_IRC, 0, 1 << ALPROTO_IRC, 12, 25 }, { "jabber", ALPROTO_JABBER, 0, 1 << ALPROTO_JABBER, 12, 23 }, }; AppLayerProtoDetectPPTestDataElement element_tc_85[] = { { "dcerpc", ALPROTO_DCERPC, 85, 1 << ALPROTO_DCERPC, 9, 10 }, { "jabber", ALPROTO_JABBER, 0, 1 << ALPROTO_JABBER, 12, 23 }, { "irc", ALPROTO_IRC, 0, 1 << ALPROTO_IRC, 12, 14 }, { "tls", ALPROTO_TLS, 0, 1 << ALPROTO_TLS, 12, 18 }, { "smtp", ALPROTO_SMTP, 0, 1 << ALPROTO_SMTP, 12, 17 } }; AppLayerProtoDetectPPTestDataElement element_ts_90[] = { { "smtp", ALPROTO_SMTP, 0, 1 << ALPROTO_SMTP, 12, 0 }, { "tls", ALPROTO_TLS, 0, 1 << ALPROTO_TLS, 12, 18 }, { "irc", ALPROTO_IRC, 0, 1 << ALPROTO_IRC, 12, 25 }, { "jabber", ALPROTO_JABBER, 0, 1 << ALPROTO_JABBER, 12, 23 }, }; AppLayerProtoDetectPPTestDataElement element_tc_90[] = { { "ftp", ALPROTO_FTP, 90, 1 << ALPROTO_FTP, 7, 15 }, { "jabber", ALPROTO_JABBER, 0, 1 << ALPROTO_JABBER, 12, 23 }, { "irc", ALPROTO_IRC, 0, 1 << ALPROTO_IRC, 12, 14 }, { "tls", ALPROTO_TLS, 0, 1 << ALPROTO_TLS, 12, 18 }, { "smtp", ALPROTO_SMTP, 0, 1 << ALPROTO_SMTP, 12, 17 } }; AppLayerProtoDetectPPTestDataElement element_ts_0[] = { { "smtp", ALPROTO_SMTP, 0, 1 << ALPROTO_SMTP, 12, 0 }, { "tls", ALPROTO_TLS, 0, 1 << ALPROTO_TLS, 12, 18 }, { "irc", ALPROTO_IRC, 0, 1 << ALPROTO_IRC, 12, 25 }, { "jabber", ALPROTO_JABBER, 0, 1 << ALPROTO_JABBER, 12, 23 }, }; AppLayerProtoDetectPPTestDataElement element_tc_0[] = { { "jabber", ALPROTO_JABBER, 0, 1 << ALPROTO_JABBER, 12, 23 }, { "irc", ALPROTO_IRC, 0, 1 << ALPROTO_IRC, 12, 14 }, { "tls", ALPROTO_TLS, 0, 1 << ALPROTO_TLS, 12, 18 }, { "smtp", ALPROTO_SMTP, 0, 1 << ALPROTO_SMTP, 12, 17 } }; AppLayerProtoDetectPPTestDataElement element_ts_85_udp[] = { { "imap", ALPROTO_IMAP, 85, 1 << ALPROTO_IMAP, 12, 23 }, }; AppLayerProtoDetectPPTestDataElement element_tc_85_udp[] = { { "imap", ALPROTO_IMAP, 85, 1 << ALPROTO_IMAP, 12, 23 }, }; AppLayerProtoDetectPPTestDataPort ports_tcp[] = { { 80, ((1 << ALPROTO_HTTP) | (1 << ALPROTO_SMB) | (1 << ALPROTO_FTP) | (1 << ALPROTO_SMTP) | (1 << ALPROTO_TLS) | (1 << ALPROTO_IRC) | (1 << ALPROTO_JABBER)), ((1 << ALPROTO_HTTP) | (1 << ALPROTO_SMB) | (1 << ALPROTO_FTP) | (1 << ALPROTO_JABBER) | (1 << ALPROTO_IRC) | (1 << ALPROTO_TLS) | (1 << ALPROTO_SMTP)), 23, element_ts_80, element_tc_80, sizeof(element_ts_80) / sizeof(AppLayerProtoDetectPPTestDataElement), sizeof(element_tc_80) / sizeof(AppLayerProtoDetectPPTestDataElement), }, { 81, ((1 << ALPROTO_DCERPC) | (1 << ALPROTO_FTP) | (1 << ALPROTO_SMTP) | (1 << ALPROTO_TLS) | (1 << ALPROTO_IRC) | (1 << ALPROTO_JABBER)), ((1 << ALPROTO_FTP) | (1 << ALPROTO_DCERPC) | (1 << ALPROTO_JABBER) | (1 << ALPROTO_IRC) | (1 << ALPROTO_TLS) | (1 << ALPROTO_SMTP)), 23, element_ts_81, element_tc_81, sizeof(element_ts_81) / sizeof(AppLayerProtoDetectPPTestDataElement), sizeof(element_tc_81) / sizeof(AppLayerProtoDetectPPTestDataElement), }, { 85, ((1 << ALPROTO_DCERPC) | (1 << ALPROTO_FTP) | (1 << ALPROTO_SMTP) | (1 << ALPROTO_TLS) | (1 << ALPROTO_IRC) | (1 << ALPROTO_JABBER)), ((1 << ALPROTO_DCERPC) | (1 << ALPROTO_JABBER) | (1 << ALPROTO_IRC) | (1 << ALPROTO_TLS) | (1 << ALPROTO_SMTP)), 23, element_ts_85, element_tc_85, sizeof(element_ts_85) / sizeof(AppLayerProtoDetectPPTestDataElement), sizeof(element_tc_85) / sizeof(AppLayerProtoDetectPPTestDataElement) }, { 90, ((1 << ALPROTO_SMTP) | (1 << ALPROTO_TLS) | (1 << ALPROTO_IRC) | (1 << ALPROTO_JABBER)), ((1 << ALPROTO_FTP) | (1 << ALPROTO_JABBER) | (1 << ALPROTO_IRC) | (1 << ALPROTO_TLS) | (1 << ALPROTO_SMTP)), 23, element_ts_90, element_tc_90, sizeof(element_ts_90) / sizeof(AppLayerProtoDetectPPTestDataElement), sizeof(element_tc_90) / sizeof(AppLayerProtoDetectPPTestDataElement) }, { 0, ((1 << ALPROTO_SMTP) | (1 << ALPROTO_TLS) | (1 << ALPROTO_IRC) | (1 << ALPROTO_JABBER)), ((1 << ALPROTO_JABBER) | (1 << ALPROTO_IRC) | (1 << ALPROTO_TLS) | (1 << ALPROTO_SMTP)), 23, element_ts_0, element_tc_0, sizeof(element_ts_0) / sizeof(AppLayerProtoDetectPPTestDataElement), sizeof(element_tc_0) / sizeof(AppLayerProtoDetectPPTestDataElement) } }; AppLayerProtoDetectPPTestDataPort ports_udp[] = { { 85, (1 << ALPROTO_IMAP), (1 << ALPROTO_IMAP), 23, element_ts_85_udp, element_tc_85_udp, sizeof(element_ts_85_udp) / sizeof(AppLayerProtoDetectPPTestDataElement), sizeof(element_tc_85_udp) / sizeof(AppLayerProtoDetectPPTestDataElement), }, }; AppLayerProtoDetectPPTestDataIPProto ip_proto[] = { { IPPROTO_TCP, ports_tcp, sizeof(ports_tcp) / sizeof(AppLayerProtoDetectPPTestDataPort), }, { IPPROTO_UDP, ports_udp, sizeof(ports_udp) / sizeof(AppLayerProtoDetectPPTestDataPort), }, }; if (AppLayerProtoDetectPPTestData(alpd_ctx.ctx_pp, ip_proto, sizeof(ip_proto) / sizeof(AppLayerProtoDetectPPTestDataIPProto)) == 0) { goto end; } result = 1; end: AppLayerProtoDetectDeSetup(); AppLayerProtoDetectUnittestCtxRestore(); return result; } /** \test test if the engine detect the proto and match with it */ static int AppLayerProtoDetectTest16(void) { int result = 0; Flow *f = NULL; HtpState *http_state = NULL; uint8_t http_buf1[] = "POST /one HTTP/1.0\r\n" "User-Agent: Mozilla/1.0\r\n" "Cookie: hellocatch\r\n\r\n"; uint32_t http_buf1_len = sizeof(http_buf1) - 1; TcpSession ssn; Packet *p = NULL; Signature *s = NULL; ThreadVars tv; DetectEngineThreadCtx *det_ctx = NULL; DetectEngineCtx *de_ctx = NULL; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); memset(&tv, 0, sizeof(ThreadVars)); memset(&ssn, 0, sizeof(TcpSession)); p = UTHBuildPacket(NULL, 0, IPPROTO_TCP); if (p == NULL) { printf("packet setup failed: "); goto end; } f = UTHBuildFlow(AF_INET, "1.1.1.1", "2.2.2.2", 1024, 80); if (f == NULL) { printf("flow setup failed: "); goto end; } f->protoctx = &ssn; f->proto = IPPROTO_TCP; p->flow = f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; f->alproto = ALPROTO_HTTP; StreamTcpInitConfig(TRUE); de_ctx = DetectEngineCtxInit(); if (de_ctx == NULL) { goto end; } de_ctx->flags |= DE_QUIET; s = de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " "(msg:\"Test content option\"; " "sid:1;)"); if (s == NULL) { goto end; } SigGroupBuild(de_ctx); DetectEngineThreadCtxInit(&tv, (void *)de_ctx, (void *)&det_ctx); FLOWLOCK_WRLOCK(f); int r = AppLayerParserParse(NULL, alp_tctx, f, ALPROTO_HTTP, STREAM_TOSERVER, http_buf1, http_buf1_len); if (r != 0) { printf("toserver chunk 1 returned %" PRId32 ", expected 0: ", r); FLOWLOCK_UNLOCK(f); goto end; } FLOWLOCK_UNLOCK(f); http_state = f->alstate; if (http_state == NULL) { printf("no http state: "); goto end; } /* do detect */ SigMatchSignatures(&tv, de_ctx, det_ctx, p); if (!PacketAlertCheck(p, 1)) { printf("sig 1 didn't alert, but it should: "); goto end; } result = 1; end: if (alp_tctx != NULL) AppLayerParserThreadCtxFree(alp_tctx); if (det_ctx != NULL) DetectEngineThreadCtxDeinit(&tv, det_ctx); if (de_ctx != NULL) SigGroupCleanup(de_ctx); if (de_ctx != NULL) DetectEngineCtxFree(de_ctx); StreamTcpFreeConfig(TRUE); UTHFreePackets(&p, 1); UTHFreeFlow(f); return result; } /** \test test if the engine detect the proto on a non standar port * and match with it */ static int AppLayerProtoDetectTest17(void) { int result = 0; Flow *f = NULL; HtpState *http_state = NULL; uint8_t http_buf1[] = "POST /one HTTP/1.0\r\n" "User-Agent: Mozilla/1.0\r\n" "Cookie: hellocatch\r\n\r\n"; uint32_t http_buf1_len = sizeof(http_buf1) - 1; TcpSession ssn; Packet *p = NULL; Signature *s = NULL; ThreadVars tv; DetectEngineThreadCtx *det_ctx = NULL; DetectEngineCtx *de_ctx = NULL; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); memset(&tv, 0, sizeof(ThreadVars)); memset(&ssn, 0, sizeof(TcpSession)); p = UTHBuildPacketSrcDstPorts(http_buf1, http_buf1_len, IPPROTO_TCP, 12345, 88); f = UTHBuildFlow(AF_INET, "1.1.1.1", "2.2.2.2", 1024, 80); if (f == NULL) goto end; f->protoctx = &ssn; f->proto = IPPROTO_TCP; p->flow = f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; f->alproto = ALPROTO_HTTP; StreamTcpInitConfig(TRUE); de_ctx = DetectEngineCtxInit(); if (de_ctx == NULL) { goto end; } de_ctx->flags |= DE_QUIET; s = de_ctx->sig_list = SigInit(de_ctx, "alert http any !80 -> any any " "(msg:\"http over non standar port\"; " "sid:1;)"); if (s == NULL) { goto end; } SigGroupBuild(de_ctx); DetectEngineThreadCtxInit(&tv, (void *)de_ctx, (void *)&det_ctx); FLOWLOCK_WRLOCK(f); int r = AppLayerParserParse(NULL, alp_tctx, f, ALPROTO_HTTP, STREAM_TOSERVER, http_buf1, http_buf1_len); if (r != 0) { printf("toserver chunk 1 returned %" PRId32 ", expected 0: ", r); FLOWLOCK_UNLOCK(f); goto end; } FLOWLOCK_UNLOCK(f); http_state = f->alstate; if (http_state == NULL) { printf("no http state: "); goto end; } /* do detect */ SigMatchSignatures(&tv, de_ctx, det_ctx, p); if (!PacketAlertCheck(p, 1)) { printf("sig 1 didn't alert, but it should: "); goto end; } result = 1; end: if (alp_tctx != NULL) AppLayerParserThreadCtxFree(alp_tctx); if (det_ctx != NULL) DetectEngineThreadCtxDeinit(&tv, det_ctx); if (de_ctx != NULL) SigGroupCleanup(de_ctx); if (de_ctx != NULL) DetectEngineCtxFree(de_ctx); StreamTcpFreeConfig(TRUE); UTHFreePackets(&p, 1); UTHFreeFlow(f); return result; } /** \test test if the engine detect the proto and doesn't match * because the sig expects another proto (ex ftp)*/ static int AppLayerProtoDetectTest18(void) { int result = 0; Flow *f = NULL; HtpState *http_state = NULL; uint8_t http_buf1[] = "POST /one HTTP/1.0\r\n" "User-Agent: Mozilla/1.0\r\n" "Cookie: hellocatch\r\n\r\n"; uint32_t http_buf1_len = sizeof(http_buf1) - 1; TcpSession ssn; Packet *p = NULL; Signature *s = NULL; ThreadVars tv; DetectEngineThreadCtx *det_ctx = NULL; DetectEngineCtx *de_ctx = NULL; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); memset(&tv, 0, sizeof(ThreadVars)); memset(&ssn, 0, sizeof(TcpSession)); p = UTHBuildPacket(http_buf1, http_buf1_len, IPPROTO_TCP); f = UTHBuildFlow(AF_INET, "1.1.1.1", "2.2.2.2", 1024, 80); if (f == NULL) goto end; f->protoctx = &ssn; f->proto = IPPROTO_TCP; p->flow = f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; f->alproto = ALPROTO_HTTP; StreamTcpInitConfig(TRUE); de_ctx = DetectEngineCtxInit(); if (de_ctx == NULL) { goto end; } de_ctx->flags |= DE_QUIET; s = de_ctx->sig_list = SigInit(de_ctx, "alert ftp any any -> any any " "(msg:\"Test content option\"; " "sid:1;)"); if (s == NULL) { goto end; } SigGroupBuild(de_ctx); DetectEngineThreadCtxInit(&tv, (void *)de_ctx, (void *)&det_ctx); FLOWLOCK_WRLOCK(f); int r = AppLayerParserParse(NULL, alp_tctx, f, ALPROTO_HTTP, STREAM_TOSERVER, http_buf1, http_buf1_len); if (r != 0) { printf("toserver chunk 1 returned %" PRId32 ", expected 0: ", r); FLOWLOCK_UNLOCK(f); goto end; } FLOWLOCK_UNLOCK(f); http_state = f->alstate; if (http_state == NULL) { printf("no http state: "); goto end; } /* do detect */ SigMatchSignatures(&tv, de_ctx, det_ctx, p); if (PacketAlertCheck(p, 1)) { printf("sig 1 alerted, but it should not (it's not ftp): "); goto end; } result = 1; end: if (alp_tctx != NULL) AppLayerParserThreadCtxFree(alp_tctx); if (det_ctx != NULL) DetectEngineThreadCtxDeinit(&tv, det_ctx); if (de_ctx != NULL) SigGroupCleanup(de_ctx); if (de_ctx != NULL) DetectEngineCtxFree(de_ctx); StreamTcpFreeConfig(TRUE); UTHFreePackets(&p, 1); UTHFreeFlow(f); return result; } /** \test test if the engine detect the proto and doesn't match * because the packet has another proto (ex ftp) */ static int AppLayerProtoDetectTest19(void) { int result = 0; Flow *f = NULL; uint8_t http_buf1[] = "MPUT one\r\n"; uint32_t http_buf1_len = sizeof(http_buf1) - 1; TcpSession ssn; Packet *p = NULL; Signature *s = NULL; ThreadVars tv; DetectEngineThreadCtx *det_ctx = NULL; DetectEngineCtx *de_ctx = NULL; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); memset(&tv, 0, sizeof(ThreadVars)); memset(&ssn, 0, sizeof(TcpSession)); p = UTHBuildPacketSrcDstPorts(http_buf1, http_buf1_len, IPPROTO_TCP, 12345, 88); f = UTHBuildFlow(AF_INET, "1.1.1.1", "2.2.2.2", 1024, 80); if (f == NULL) goto end; f->protoctx = &ssn; f->proto = IPPROTO_TCP; p->flow = f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; f->alproto = ALPROTO_FTP; StreamTcpInitConfig(TRUE); de_ctx = DetectEngineCtxInit(); if (de_ctx == NULL) { goto end; } de_ctx->flags |= DE_QUIET; s = de_ctx->sig_list = SigInit(de_ctx, "alert http any !80 -> any any " "(msg:\"http over non standar port\"; " "sid:1;)"); if (s == NULL) { goto end; } SigGroupBuild(de_ctx); DetectEngineThreadCtxInit(&tv, (void *)de_ctx, (void *)&det_ctx); FLOWLOCK_WRLOCK(f); int r = AppLayerParserParse(NULL, alp_tctx, f, ALPROTO_FTP, STREAM_TOSERVER, http_buf1, http_buf1_len); if (r != 0) { printf("toserver chunk 1 returned %" PRId32 ", expected 0: ", r); FLOWLOCK_UNLOCK(f); goto end; } FLOWLOCK_UNLOCK(f); /* do detect */ SigMatchSignatures(&tv, de_ctx, det_ctx, p); if (PacketAlertCheck(p, 1)) { printf("sig 1 alerted, but it should not (it's ftp): "); goto end; } result = 1; end: if (alp_tctx != NULL) AppLayerParserThreadCtxFree(alp_tctx); if (det_ctx != NULL) DetectEngineThreadCtxDeinit(&tv, det_ctx); if (de_ctx != NULL) SigGroupCleanup(de_ctx); if (de_ctx != NULL) DetectEngineCtxFree(de_ctx); StreamTcpFreeConfig(TRUE); UTHFreePackets(&p, 1); UTHFreeFlow(f); return result; } void AppLayerProtoDetectUnittestsRegister(void) { SCEnter(); UtRegisterTest("AppLayerProtoDetectTest01", AppLayerProtoDetectTest01); UtRegisterTest("AppLayerProtoDetectTest02", AppLayerProtoDetectTest02); UtRegisterTest("AppLayerProtoDetectTest03", AppLayerProtoDetectTest03); UtRegisterTest("AppLayerProtoDetectTest04", AppLayerProtoDetectTest04); UtRegisterTest("AppLayerProtoDetectTest05", AppLayerProtoDetectTest05); UtRegisterTest("AppLayerProtoDetectTest06", AppLayerProtoDetectTest06); UtRegisterTest("AppLayerProtoDetectTest07", AppLayerProtoDetectTest07); UtRegisterTest("AppLayerProtoDetectTest08", AppLayerProtoDetectTest08); UtRegisterTest("AppLayerProtoDetectTest09", AppLayerProtoDetectTest09); UtRegisterTest("AppLayerProtoDetectTest10", AppLayerProtoDetectTest10); UtRegisterTest("AppLayerProtoDetectTest11", AppLayerProtoDetectTest11); UtRegisterTest("AppLayerProtoDetectTest12", AppLayerProtoDetectTest12); UtRegisterTest("AppLayerProtoDetectTest13", AppLayerProtoDetectTest13); UtRegisterTest("AppLayerProtoDetectTest14", AppLayerProtoDetectTest14); UtRegisterTest("AppLayerProtoDetectTest15", AppLayerProtoDetectTest15); UtRegisterTest("AppLayerProtoDetectTest16", AppLayerProtoDetectTest16); UtRegisterTest("AppLayerProtoDetectTest17", AppLayerProtoDetectTest17); UtRegisterTest("AppLayerProtoDetectTest18", AppLayerProtoDetectTest18); UtRegisterTest("AppLayerProtoDetectTest19", AppLayerProtoDetectTest19); SCReturn; } #endif /* UNITTESTS */
./CrossVul/dataset_final_sorted/CWE-20/c/bad_722_0